test = function() {
	if (OPT.parent_doc_type=='EcmSales') {
	  for(var i=0; i<N.rowCount(); i++) {
        var data = N.row(i).getData();
			getProductQuantity(i, "saveParentReservation");
		}
	}
}
window.onbeforeunload = function() {
	return "";
}
window.onunload = function() {
	removeDocumentReservations(document.getElementById("temp_id").value);
	if (OPT.parent_doc_type=='EcmSales') {
	  for(var i=0; i<N.rowCount(); i++) {
        var data = N.row(i).getData();
			getProductQuantity(i, "saveParentReservation");
		}
	}
}
function getAddresses() {
	//show loading
	document.getElementById('addresses').innerHTML = '<img src="themes/default/images/loading.gif" width="15px"/>';
	url='index.php?module=Accounts&action=getAddresses&account_id='+document.forms.EditView.parent_id.value+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		if (this.responseText == '0') {
			document.getElementById('addresses').innerHTML = 'Brak adresów';
		} else {
			document.getElementById('addresses').innerHTML = this.responseText;
			//document.getElementById('address_id').onchange = getAddress();
		}
	}
	req.Send(url);
}

function getAddress() {
	var id = document.getElementById('address_id').value;
	if (id=='') return;
	url='index.php?module=Accounts&action=getAddress&id='+id+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		var addr = eval(this.responseText);
		console.log(addr[0].description);
		if (addr[0].description) document.getElementById('parent_shipping_address_name').value = addr[0].description;
		if (addr[0].street) document.getElementById('parent_shipping_address_street').value = addr[0].street;
		if (addr[0].postalcode) document.getElementById('parent_shipping_address_postalcode').value = addr[0].postalcode;
		if (addr[0].city) document.getElementById('parent_shipping_address_city').value = addr[0].city;
		if (addr[0].country) document.getElementById('parent_shipping_address_country').value = addr[0].country;
	}
	req.Send(url);
}
getProductType = function(index) {
	var data = N.row(index).getData();
	var url='index.php?module=EcmFkPackages&action=getProductType&product_id='+data.id+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		var prod = eval(this.responseText);
		data.type = prod[0]['type'];
		N.row(index).setData(data);
	}
    req.Send(url);
}
function BlockProducts(){
	var tab=document.getElementById("tbody");
	var tr=tab.getElementsByTagName("tr");
	var qty;
	var total;
	for(var i=0;i<tr.length;i++){
		var inp=tr[i].getElementsByTagName("input");
		var img=tr[i].getElementsByTagName("img");
		var tx=tr[i].getElementsByTagName("textarea");
		if (inp[2].value!='') {
			inp[1].setAttribute('readonly', 'readonly');
			inp[1].setAttribute('onkeydown', '');
			if (img[0])
			img[0].setAttribute('style', 'display:none');
		}
	}
	return true;
}
function removeDocumentReservations(temp_id, operation) {
	url='index.php?module=EcmStockOperations&action=deleteDocumentReservations&temp_doc_id='+temp_id+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		if (operation) {
			if (operation=='cancel')
				window.location="index.php?module=EcmSales&action=index";
			if (operation=='list')
				window.location="index.php?module=EcmSales&action=index";
		}
	}
    req.Send(url);
}
function getProductQuantity(rowIndex, operation)
{
	var stock_id = document.getElementById("stock_id").value;
	var product_id = N.row(rowIndex).getData().id;
	url='index.php?module=EcmStockStates&action=getProductQuantity&stock_id='+stock_id+'&product_id='+product_id+'&to_pdf=1';
	var req=mint.Request();

	req.OnSuccess = function()
	{
		var data = N.row(rowIndex).getData();
		data.stock = this.responseText;
		console.log(data.stock);
		N.row(rowIndex).setData(data);
		if (!data.reserved) data.reserved = 0;
		if (operation == "saveReservation") {
			N.row(rowIndex).className='';
			console.log("stock: "+data.stock+" reservation: "+data.reserved+" quantity: "+data.quantity);
			//if qty = 0 do clear reserved field
			if (data.quantity==0) {
				data.reserved = 0;
				N.row(rowIndex).setData(data);
				removeReservation(rowIndex);
				setTimeout(function() {getProductQuantity(rowIndex);},1000);
				return;
			}
			//stock > qty  - all OK, can reserve
		    if (data.stock>=data.quantity-data.reserved) {
				console.log("normal");
				saveReservation(rowIndex, false);
				return;
			}
			if (data.quantity-data.reserved-data.stock>0) {
				data.quantity = data.stock;
				N.row(rowIndex).setData(data);
				N.row(rowIndex).className = 'orangeRow';
				saveReservation(rowIndex, true);
				return;
			}
				data.quantity = 0;
				N.row(rowIndex).setData(data);
				N.row(rowIndex).className = 'redRow';
			//no reservation

		} else if (operation=='saveParentReservation') {
			alert(data.parent_doc_rq+'    '+data.stock);
			if (data.parent_doc_rq - data.quantity >= data.stock)
				alert('do rezerwacji: '+data.parent_doc_rq);
				//saveParentReservation(rowIndex, data.parent_doc_rq);
			else
				alert('save parent, stock');
				//saveParentReservation(rowIndex, data.stock);
		}
	}
    req.Send(url);
}
function saveReservation(rowIndex, orangeRow, qty){
	var data = N.row(rowIndex).getData();
	var product_id = data.id;
	var temp_item_id = data.temp_item_id;
	var quantity;
	if (qty)
		quantity = qty;
	else
		quantity = data.quantity;
	var date = data.temp_date;
	var stock_id = document.getElementById("stock_id").value;
	var temp_doc_id = document.getElementById("temp_id").value;
	var doc_type = 'EcmFkPackages';
	var url='index.php?module=EcmStockOperations&action=saveReservation&stock_id='+stock_id+'&product_id='+product_id+'&temp_doc_id='+temp_doc_id+'&temp_item_id='+temp_item_id+'&date='+date+'&quantity='+quantity+'&to_pdf=1&doc_type='+doc_type;
	var req=mint.Request();
	req.OnSuccess = function(){
		var data = N.row(rowIndex).getData();
		data.reserved = quantity;
		N.row(rowIndex).setData(data);
		if (orangeRow == true)
			N.row(rowIndex).className = 'orangeRow';
		else
			N.row(rowIndex).className = 'greenRow';
		getProductQuantity(rowIndex, '');
	}
    req.Send(url);
}

function saveParentReservation(rowIndex){
	var data = N.row(rowIndex).getData();
	var product_id = data.id;
	var item_id = data.parent_doc_item_id;
	var quantity = data.parent_doc_rq;
	var date = data.temp_date;
	var stock_id = document.getElementById("stock_id").value;
	var doc_id = data.parent_doc_id;
	var doc_type = OPT.parent_doc_type;
	var url='index.php?module=EcmStockOperations&action=saveReservation&stock_id='+stock_id+'&product_id='+product_id+'&temp_doc_id='+temp_doc_id+'&temp_item_id='+temp_item_id+'&date='+date+'&quantity='+quantity+'&to_pdf=1&doc_type='+doc_type;
	var req=mint.Request();
	req.OnSuccess = function(){
		var data = N.row(rowIndex).getData();
		data.reserved = quantity;
		N.row(rowIndex).setData(data);
		N.row(rowIndex).className = 'greenRow';
		getProductQuantity(rowIndex, '');
	}
    req.Send(url);
}


function removeReservation(index) {
   var data = N.row(index).getData();
   var temp_item_id = data.temp_item_id;
	url='index.php?module=EcmStockOperations&action=deleteReservation&temp_item_id='+temp_item_id+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function(){}
    req.Send(url);
}

function updateReservation(index, quantity) {
   var data = N.row(index).getData();
   var item_id = data.parent_doc_item_id;
   var doc_id = data.parent_doc_id;

	url='index.php?module=EcmStockOperations&action=updateReservation&item_id='+item_id+'&to_pdf=1&doc_id='+doc_id+'&quantity='+quantity;
	var req=mint.Request();
	req.OnSuccess = function(){}
    req.Send(url);
}

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 updatePaymentDate(){
	var rd=document.getElementById("register_date").value;
	d=rd.split(".");
	var days = 0;
	if (document.getElementById('payment_date_d').value!='')
		days = document.getElementById('payment_date_d').value;
	doRequest('index.php','to_pdf=1&module=EcmFkPackages&action=getPaymentDate&day='+d[0]+'&month='+d[1]+'&year='+d[2]+'&days='+days,function(result){
		document.getElementById("payment_date").value = result;
		}
	);
}
function updateUnitNames(){
	var tab=document.getElementById("tbody");
	var tr=tab.getElementsByTagName("tr");
	var qtyinstock;
	var qty;
	var total;
	for(var i=0;i<tr.length;i++){
		//if(tr[i].getElementsByTagName("input")[4] && tr[i].getElementsByTagName("input")[5]){
		//alert(document.getElementById('ecmlanguage').value+" "+tr[i].getElementsByTagName("input")[4]);
		if(UNIT_LANG[document.getElementById('ecmlanguage').value][tr[i].getElementsByTagName("input")[8].value])tr[i].getElementsByTagName("input")[9].value=UNIT_LANG[document.getElementById('ecmlanguage').value][tr[i].getElementsByTagName("input")[8].value];
		//}
	}
	return true;
}
function SetTabIndexs(buttons) {
	var main = document.getElementById('main');
	var td = main.getElementsByTagName('td');
	var selectedTable = null;
	//var selectingColor = 'red';
	//var selectingCellTable = 'green';
	var TableIndex = 0;
	for(var i=0; i<td.length; i++) {
		if(td[i].className == 'tabEditViewDF') {
			var TI = 0;
			if(td[i].parentNode.cells.item(1) == td[i]) TI = 101+TableIndex; else TI = 102+TableIndex;

			var nodes = td[i].getElementsByTagName('input');
			for(var j=0; j<nodes.length; j++) nodes[j].tabIndex = TI;
			var nodes = td[i].getElementsByTagName('select');
			for(var j=0; j<nodes.length; j++) nodes[j].tabIndex = TI;
			var nodes = td[i].getElementsByTagName('textarea');
			for(var j=0; j<nodes.length; j++) nodes[j].tabIndex = TI;

			if(td[i].parentNode.parentNode.parentNode !== selectedTable) {
				//if(selectingColor == 'red') selectingColor = 'blue'; else selectingColor = 'red';
				selectedTable = td[i].parentNode.parentNode.parentNode;
				TableIndex++;
			}
		}
	}
	if(buttons==0){
		var TableIndex = 0;
		for(var i=0; i<td.length; i++) {
			if(td[i].className == 'tabEditViewDF') {
				var TI = 0;
				if(td[i].parentNode.cells.item(1) == td[i]) TI = 101+TableIndex; else TI = 102+TableIndex;

				var nodes = td[i].getElementsByTagName('input');
				for(var j=0; j<nodes.length; j++) {
					if(nodes[j].className=="button")nodes[j].tabIndex = TI+100000;
				}

				if(td[i].parentNode.parentNode.parentNode !== selectedTable) {
					//if(selectingColor == 'red') selectingColor = 'blue'; else selectingColor = 'red';
					selectedTable = td[i].parentNode.parentNode.parentNode;
					TableIndex++;
				}
			}
		}
	}
}

function changeValidateRequired(formname,name,required) {
//  for(var i=0; i<validate[formname].length; i++)
   // if(validate[formname][i][0] == name) { validate[formname][i][2] = required; break; }
}

function set_focus() { document.getElementById('name').focus(); }

function my_popup(module, field_array, call_back_function, form_name) {
  if(!call_back_function) call_back_function = "set_return";
  if(!form_name) form_name = "EditView";
  return open_popup(module, 900, 700, "", true, false, {"call_back_function":call_back_function,"form_name":form_name,"field_to_name_array":field_array});
}

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 findPos(obj) {
    var nleft = 0;
    var ntop = 0;
    if (obj.offsetParent) {
        nleft = obj.offsetLeft
        ntop = obj.offsetTop
        while (obj = obj.offsetParent) {
            nleft += obj.offsetLeft
            ntop += obj.offsetTop
        }
    }
    return [nleft,ntop];
}

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 ERROR = false;

var ItemListSave = function(json) { }

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){
			/*
			console.log(result);
			HideLoadingView();
			return;
			*/

			document.forms.EditView.record.value = result.substring(result.length-36);
			alert(MOD['LBL_SAVED']);
			window.onbeforeunload='';
			window.onunload='';
			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=EcmFkPackages&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'] = 'EcmFkPackages';
  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'] = 'EcmFkPackages';
  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=EcmFkPackages&action=previewPDF&to_pdf=1&from=EcmFkPackages',{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=EcmFkPackages&action=previewPDF&to_pdf=1&from=EcmFkPackages',{zoom:75});
	  }
	  else{
      	  SetTab('PREVIEW');
      	  document.getElementById('previewPDF').innerHTML = "<iframe style='border:none;width:100%;height:1200px;' frameborder='no' src='index.php?module=EcmFkPackages&action=previewPDF&to_pdf=1&from=EcmFkPackages#zoom=75'>Yours browser not accept iframes!</iframe>";
	  }
    }
  );
}

function canConfirm() {
  if(document.forms.EditView.status.value == "accepted" && !OPT.user.confirm_invoiceouts) {
    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;
}

function CheckDiscount(noAlert) {
  var discount = 0;
  //var tmp = UserFormatNumberToNumber(document.getElementById('discount').value);
  var tmp = UserFormatNumberToNumber("0%");
      if(tmp == -1) {
        if(!noAlert)
          alert(MOD['LBL_DISCOUNT_ERROR']+' ('+document.getElementById('discount').value+')');
        discount = -1;
        //document.getElementById('discount').style.color = 'red';
      } else {
        discount = tmp;
        //document.getElementById('discount').value = NumberToUserFormatNumber(discount);
        //document.getElementById('discount').style.color = 'black';
      }
  return discount;
}

//document.getElementById('previewPDF').innerHTML = "<iframe style='border:0px; width:100%; height:100%;' src='index.php?module=EcmFkPackages&action=InvoicePDFPreview&to_pdf=1'>Yours browser not accept iframes!</iframe>";
//ProductListSave();
//YAHOO.util.Connect.asyncRequest('POST','index.php',{success:this.Display,failure:this.Fail},this.postData());


var AjaxSearchProducts;

var parentFL;
var productFL;

addEvent(
  window,
  'load',
  function () {
      var CHANGER = new changer();

     CHANGER.interval = 500;

    set_focus();

    //initialize table
    N = new MyTable('itemsTable');
	N.divParent = document.getElementById('itemsTableDIV');

    var from_popup_return  = false;
    function returnedData(popup_reply_data) {
    from_popup_return = true;
    var form_name = popup_reply_data.form_name;
    var name_to_value_array = popup_reply_data.name_to_value_array;
    	for (var the_key in name_to_value_array) {
    		if(the_key == 'toJSON'){}
    		else {
    			var displayValue=name_to_value_array[the_key].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');;
    			var e = document.getElementById(the_key);

          if(e) { e.value = displayValue; }
    		}
    	}
      //if(N.selectedRow) N.selectedRow.calculateTotal();
    };

    N.onRefreshRowIndex = function(row) {
      var data = new Object();
      data['index'] = (row.index+1).toString();
      row.cells.item(0).setData(data);
    }
    N.onCreateRow = function(row) {
      row.newPos = false;
      row.ondblclick = function() {
        this.newPos = !this.newPos;
        for(var i=0; i<this.myTable.colCount(); i++)
          this.cells.item(i).change(!this.newPos);

      }
      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);
		}
      }
      row.calculateTotal = function() {

		var data = this.getData();

		if (data.startprice && data.quantity) {

			if (!data.discount) data.discount = 0;

			data.subprice = data.startprice - (data.startprice * data.discount / 100);
			data.price = data.subprice + (data.subprice * data.vat_value / 100);
			data.subtotal = data.quantity * data.subprice;
			data.total = data.quantity * data.price;

			this.setData(data);
		}
        calculateTotal();
      }
    }

	var itd = document.getElementById('itemsTableDIV');
	itd.onscroll = function() {
		if(!AjaxSearchProducts.AjaxSearchFrozen)
		if(N.selectedCell && N.selectedCell.LeftPosition && N.selectedCell.TopPosition) {
			var top = N.selectedCell.TopPosition+N.selectedCell.offsetHeight;
			if(((N.selectedCell.offsetTop+N.selectedCell.offsetHeight-this.scrollTop) > (this.offsetHeight+5)) || ((N.selectedCell.offsetTop-this.scrollTop) < (-10)))
				AjaxSearchProducts.div.style.display = 'none';
			else
				AjaxSearchProducts.div.style.display = '';
			AjaxSearchProducts.div.style.top = top - this.scrollTop;
		}
	}

    N.onCreateCell = function(cell) {

      var i = cell.index;
      cell.change = function(select) {};
  	  cell.style.height = OPT['row_item_height'];

	  cell.onDeselect2 = function() {
		 var data = this.parentNode.getData();
		 if(!data.id || data.id == '')  {
		 var data2 = new Object();
		 	this.parentNode.setData(data2);
		 }
	  }

      if(i == 0) {

        cell.setData = function(data) {
          if(data.index) cell.firstChild.value = data.index;
        };
        cell.getData = function(data) {
          data.index = cell.firstChild.value;
        }
        cell.select = function() { this.selectNext(); }

        var edit = document.createElement('input');
        edit.setAttribute('type','text');
        edit.setAttribute('readOnly','readonly');
        edit.setAttribute('tabIndex',1);
        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[3]; c.name = 'vat_id_p'; c.id = 'vat_id_p';
            c = cn[3]; c.name = 'category_id_p'; c.id = 'category_id_p';
            c = cn[4]; c.name = 'currency_id_p'; c.id = 'currency_id_p';
            c = cn[5]; c.name = 'currency_symbol_p'; c.id = 'currency_symbol_p';
			c = cn[6]; c.name = 'ecmstockdocout_id'; c.id = 'ecmstockdocout_id';
            c = cn[7]; c.name = 'temp_item_id_p'; c.id = 'temp_item_id_p';
            c = cn[8]; c.name = 'temp_date_p'; c.id = 'temp_date_p';
            c = cn[9]; c.name = 'type_p'; c.id = 'type_p';
            c = cn[10]; c.name = 'parent_doc_id'; c.id = 'parent_doc_id';
            c = cn[11]; c.name = 'parent_doc_type'; c.id = 'parent_doc_type';
            c = cn[12]; c.name = 'parent_doc_item_id'; c.id = 'parent_doc_item_id';
          }
           else {
            c = cn[0]; c.name = ''; c.id = ''; c.className = 'inputs';
            c = cn[1]; c.name = ''; c.id = '';
            //c = cn[3]; c.name = ''; c.id = '';
            c = cn[3]; c.name = ''; c.id = '';
            c = cn[4]; c.name = ''; c.id = '';
            c = cn[5]; c.name = ''; c.id = '';
            c = cn[6]; c.name = ''; c.id = '';
            c = cn[7]; c.name = ''; c.id = '';
            c = cn[8]; c.name = ''; c.id = '';
            c = cn[9]; c.name = ''; c.id = '';
            c = cn[10]; c.name = ''; c.id = '';
            c = cn[11]; c.name = ''; c.id = '';
            c = cn[12]; c.name = ''; c.id = '';
          }
		}
		cell.onSelect = function() {
		  var xy = findPos(this);
		  this.TopPosition = xy[1];
		  this.LeftPosition = xy[0];
		  var top = xy[1]+this.offsetHeight;
		  var itd = document.getElementById('itemsTableDIV');
		  if(document.getElementById('type').value!='correct'){
		  AjaxSearchProducts.setInputCode(this.getElementsByTagName('input')[0]);
		  if(!AjaxSearchProducts.AjaxSearchFrozen) {
  		    AjaxSearchProducts.div.style.left = xy[0];
		  	AjaxSearchProducts.div.TopPosition = top;
		  	AjaxSearchProducts.div.style.top = top-itd.scrollTop;
		  }
		  this.ajax_search = false;
		  this.parentNode.noHideASP = false;
		  }
		}
		cell.onDeselect = function() {
			if(document.getElementById('type').value!='correct')if(!this.parentNode.noHideASP) AjaxSearchProducts.div.style.display = 'none';
			this.ajax_search = false;
		}
        cell.getData = function(data) {
          var cn = this.getElementsByTagName('input');
          data.code = cn[0].value;
          data.id = cn[1].value;
          //data.vat_id = cn[3].value;
          data.category_id = cn[3].value;
          data.currency_id = cn[4].value;
          data.currency_symbol = cn[5].value;
		  data.ecmstockdocout_id = cn[6].value;
          data.temp_item_id = cn[7].value;
          data.temp_date = cn[8].value;
          data.type = cn[9].value;
          data.parent_doc_id = cn[10].value;
          data.parent_doc_type = cn[11].value;
          data.parent_doc_item_id = cn[12].value;
        }
        cell.setData = function(data) {
			console.log(data);
          var cn = this.getElementsByTagName('input');
          cn[0].value = ((data.code)?data.code:'');
          cn[1].value = ((data.id)?data.id:'');
          //if(data.vat_id) cn[3].value = data.vat_id;
          cn[3].value = ((data.category_id)?data.category_id:OPT['default_category']);
          cn[4].value = ((data.currency_id)?data.currency_id:OPT['default_currency_id']);
          cn[5].value = ((data.currency_symbol)?data.currency_symbol:OPT['default_category']);
		  cn[6].value = ((data.ecmstockdocout_id)?data.ecmstockdocout_id:"");
          cn[7].value = ((data.temp_item_id)?data.temp_item_id:'');
          cn[8].value = ((data.temp_date)?data.temp_date:'');
          cn[9].value = ((data.type)?data.type:'');
          cn[10].value = ((data.parent_doc_id)?data.parent_doc_id:'');
          cn[11].value = ((data.parent_doc_type)?data.parent_doc_type:'');
          cn[12].value = ((data.parent_doc_item_id)?data.parent_doc_item_id:'');
        }
		cell.onKeyDownEvent = function(ev,input) {

			var keynum; if(window.event) keynum = ev.keyCode; else keynum = ev.which;
			if(keynum != 13 && keynum != 9) this.ajax_search = true;

			if(this.ajax_search == true) {
				AjaxSearchProducts.div.style.display = '';
				setTimeout( function() {
							AjaxSearchProducts.inputSearch.value=input.value;
							AjaxSearchProducts.inputSearchOnKeyDown(keynum,"clear");
						}, 50 );
			}
			if(input.value == '' && keynum == 40) { setSelectionRange(AjaxSearchProducts.inputSearch); return false; }
			if(keynum == 13 || keynum == 9) {
				if(input.value == '') return false;
				if(this.ajax_search != true && this.parentNode.myTable.selectedCell && this.parentNode.myTable.selectedCell.index == 1) this.selectNext();
				return false;
			}
			if(keynum == 27) { return false; }
			return true;
			//return input.parentNode.myTable.KeyPressed(ev,input.parentNode,null,true);
		}
        if(document.getElementById('type').value!='correct')var edit = '<input type="text" onFocus="this.parentNode.select();" tabindex="1" class="inputs" style="height:16px;" autocomplete="off" onKeyDown="return this.parentNode.onKeyDownEvent(event,this);"><br>';
		else var edit = '<input type="text" readonly="readonly" onFocus="this.parentNode.select();" tabindex="1" class="inputs" style="height:16px;" autocomplete="off" onKeyDown="return this.parentNode.onKeyDownEvent(event,this);"><br>';
        cell.innerHTML = edit;
        cell.align = 'right';
        var id = document.createElement('input');
        id.setAttribute('type','hidden');
        cell.appendChild(id);
        var unit_id = document.createElement('input');
        unit_id.setAttribute('type','hidden');
        unit_id.setAttribute('value',OPT['default_unit']);
        cell.appendChild(unit_id);

		/*
		var vat_id = document.createElement('input');
        vat_id.setAttribute('type','hidden');
        vat_id.setAttribute('value',OPT['default_vat']);
        cell.appendChild(vat_id);
        */

        var category_id = document.createElement('input');
        category_id.setAttribute('type','hidden');
        category_id.setAttribute('value',OPT['default_category']);
        cell.appendChild(category_id);

        var currency_id = document.createElement('input');
        currency_id.setAttribute('type','hidden');
        currency_id.setAttribute('value',OPT['default_currency']);
        cell.appendChild(currency_id);

        var currency_symbol = document.createElement('input');
        currency_symbol.setAttribute('type','hidden');
        currency_symbol.setAttribute('value',OPT['default_category']);
        cell.appendChild(currency_symbol);

		var ecmstockdocout_id = document.createElement('input');
        ecmstockdocout_id.setAttribute('type','hidden');
        ecmstockdocout_id.setAttribute('value','');
        cell.appendChild(ecmstockdocout_id);

        var item_id = document.createElement('input');
        item_id.setAttribute('type','hidden');
        item_id.setAttribute('value','');
        cell.appendChild(item_id);

        var temp_item_id = document.createElement('input');
       	temp_item_id.setAttribute('type','hidden');
        temp_item_id.setAttribute('value','');
        cell.appendChild(temp_item_id);

        var temp_date = document.createElement('input');
       	temp_date.setAttribute('type','hidden');
        temp_date.setAttribute('value','');
        cell.appendChild(temp_date);

        var type = document.createElement('input');
       	type.setAttribute('type','hidden');
        type.setAttribute('value','');
        cell.appendChild(type);

		var parent_doc_id = document.createElement('input');
       	parent_doc_id.setAttribute('type','hidden');
        parent_doc_id.setAttribute('value','');
        cell.appendChild(parent_doc_id);

		var parent_doc_type = document.createElement('input');
       	parent_doc_type.setAttribute('type','hidden');
        parent_doc_type.setAttribute('value','');
        cell.appendChild(parent_doc_type);

		var parent_doc_item_id = document.createElement('input');
       	parent_doc_item_id.setAttribute('type','hidden');
        parent_doc_item_id.setAttribute('value','');
        cell.appendChild(parent_doc_item_id);

        var img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_IMG_SEARCH']);
        img.setAttribute('src','modules/EcmFkPackages/images/search.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() { try { this.parentNode.select(); } catch(e) {} if(!this.parentNode.noHideASP) AjaxSearchProducts.div.style.display = 'none'; this.parentNode.ajax_search = false;
		var ecmpopup = my_popup('EcmProducts',{'id':'id_p','index_dbf':'code_p','unit_name':'unit_id_p','unit_name':'unit_name_p','name':'name_p','vat_id':'vat_id_p','vat_value':'vat_value_p','vat_name':'vat_name_p', 'currency_id':'currency_id_p', 'currency_symbol':'currency_symbol_p'});
		setTimeout(function(){ecmpopup.focus();},200);
		}
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
		/*
        cell.appendChild(document.createTextNode(" "));
        var img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_IMG_EDIT']);
        img.setAttribute('src','modules/EcmFkPackages/images/edit_position.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() { try { this.parentNode.select(); } catch(e) {} if(!this.parentNode.noHideASP) AjaxSearchProducts.div.style.display = 'none'; this.parentNode.ajax_search = false;
		  var data = new Object();
		  this.parentNode.getData(data);
          var ecmpopup = window.open("index.php?module=EcmFkPackages&action=formloader&to_pdf=1&loaderAction=ViewForm&loaderFieldName=productFL&createModule=EcmProducts&fl_record="+data.id ,"New","resizable=yes,scrollbars=no,status=no,height=700,width=900");
		  setTimeout(function(){ecmpopup.focus();},200);
		};
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
		*/
		/*
        cell.appendChild(document.createTextNode(" "));
        var img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_IMG_NEW']);
        img.setAttribute('src','modules/EcmFkPackages/images/add_position.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() { try { this.parentNode.select(); } catch(e) {} if(!this.parentNode.noHideASP) AjaxSearchProducts.div.style.display = 'none'; this.parentNode.ajax_search = false;
          var ecmpopup = window.open("index.php?module=EcmFkPackages&action=formloader&to_pdf=1&loaderAction=ViewForm&loaderFieldName=productFL&createModule=EcmProducts" ,"Create","resizable=yes,scrollbars=no,status=no,height=700,width=900");
		  setTimeout(function(){ecmpopup.focus();},200);
          */
          /*
          this.parentNode.addToBase = !this.parentNode.addToBase;
          if(!this.parentNode.addToBase) this.src = 'modules/EcmFkPackages/images/new.gif';
                                   else this.src = 'modules/EcmFkPackages/images/newset.gif'


        };
		*/
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
      }

      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:'');
        }
        if(document.getElementById('type').value!='correct')var textarea = '<textarea tabindex="1" onFocus="this.parentNode.select();" style="width:100%;height:100%;" class="inputs" onKeyDown="return this.parentNode.myTable.KeyPressed(event,this.parentNode,null,true);"></textarea>';
		else var textarea = '<textarea tabindex="1" readonly="readonly" onFocus="this.parentNode.select();" style="width:100%;height:100%;" class="inputs" onKeyDown="return this.parentNode.myTable.KeyPressed(event,this.parentNode,null,true);"></textarea>';
        cell.innerHTML = textarea;
      }
      if(i == 3) {
	  var old_val;
        cell.change = function(select) {
          var c;
          if(select) {
            c = this.childNodes[0]; c.name = 'quantity_p'; c.id = 'quantity_p';
          }
           else {
            c = this.childNodes[0]; c.name = ''; c.id = '';
          }
        }
        cell.getData = function(data,noAlert) {
          var tmp = UserFormatNumberToNumber(this.firstChild.value);
          if(tmp == -1) {
            ERROR = true;
            //if(!noAlert)
              //alert(MOD['LBL_FORMAT_NUMBER_ERROR']+' ('+this.firstChild.value+')');
            data.quantity = 0;
            this.firstChild.style.color = 'red';
          } else {
            data.quantity = tmp;
            this.firstChild.style.color = 'black';
          }
        }
        cell.setData = function(data) {
          if(data.quantity) this.firstChild.value = NumberToUserFormatNumber(data.quantity); else this.firstChild.value = NumberToUserFormatNumber(0);
        }

		cell.onSelect = function() {
			var data = this.parentNode.getData();
			old_val = data.quantity;
			getProductQuantity(this.parentNode.index,'');
			var index = this.parentNode.index;
			setTimeout(function() {getProductType(index)},1000);
		}
        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            data.quantity = data.quantity;
            this.setData(data);
          }

		  if (data.type == 'service') return;


		  if (old_val!=data.quantity) getProductQuantity(this.parentNode.index, "saveReservation");
        }
        var edit = '<input type="text" tabindex="1" autocomplete="off" class="inputs" style="text-align:center;" value="'+NumberToUserFormatNumber(0)+'">';
        cell.innerHTML = edit;
      }
      if(i == 4) {
        cell.getData = function(data,noAlert) {
			var cn = this.getElementsByTagName('input');
			if (cn[0]) data.startprice = UserFormatNumberToNumber(cn[0].value);
			else data.startprice = 0;
        }
        cell.setData = function(data) {
          if(data.startprice) this.firstChild.value = NumberToUserFormatNumber(data.startprice); else this.firstChild.value = NumberToUserFormatNumber(0);
        }
        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            data.startprice = data.startprice;
            this.setData(data);
          }
		  this.parentNode.calculateTotal();
        }
        var edit = '<input type="text" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" onKeyDown="return this.parentNode.myTable.KeyPressed(event,this.parentNode,\'decimalNumber\');" value="'+NumberToUserFormatNumber(0)+'">';
        cell.innerHTML = edit;
      }
      if(i == 5) {

        cell.getData = function(data,noAlert) {

          var tmp = UserFormatNumberToNumber(this.firstChild.value,'%');

          if(tmp == -1) {

            ERROR = true;

            if(!noAlert)

              alert(MOD['LBL_FORMAT_NUMBER_ERROR']+' ('+this.firstChild.value+')');

            data.discount = 0;

            this.firstChild.style.color = 'red';

          } else {

            data.discount = tmp;

            this.firstChild.style.color = 'black';

          }

        }

        cell.setData = function(data) {

          if(data.discount) this.firstChild.value = NumberToUserFormatNumber(data.discount,'%'); else this.firstChild.value = NumberToUserFormatNumber(0,'%');

        }

        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            data.discount = data.discount;
            this.setData(data);
          }
		  this.parentNode.calculateTotal();
        }

        cell.selectNext = function() { var row = this.parentNode.selectNext(); row.select(); row.cells.item(0).select(); };

        var edit = '<input type="text" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="'+NumberToUserFormatNumber(0,'%')+'">';

        cell.innerHTML = edit;

      }
    if(i == 6) {
        cell.change = function(select) {
          var c;
          if(select) {
            c = this.childNodes[0]; c.name = 'vat_name_p'; c.id = 'vat_name_p';
            c = this.childNodes[1]; c.name = 'vat_value_p'; c.id = 'vat_value_p';
            c = this.childNodes[2]; c.name = 'vat_id_p'; c.id = 'vat_id_p';
          }
           else {
            c = this.childNodes[0]; c.name = ''; c.id = '';
            c = this.childNodes[1]; c.name = ''; c.id = '';
            c = this.childNodes[2]; c.name = ''; c.id = '';
          }
        }
        cell.getData = function(data,noAlert) {
			var cn = this.getElementsByTagName('input');
            data.vat_value = cn[1].value;
            data.vat_id = cn[2].value;
            //if(VAT[cn[2].value])data.vat_name = VAT[cn[2].value].name;
        }
        cell.setData = function(data) {
          if(data.vat_value) this.getElementsByTagName('input')[1].value = data.vat_value; //0->1, 1->2, 2->0
          if(data.vat_id) this.getElementsByTagName('input')[2].value = data.vat_id;
          if(data.vat_name) this.getElementsByTagName('input')[0].value = data.vat_name;
        }
        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            data.vat_id = data.vat_id;
            this.setData(data);
          }
        }
		var div=document.createElement('div');
		div.setAttribute('style','display:none;float:right;text-align:right;border: 1px #cccccc solid;padding:3px;');
		var key;
		for(key in VAT){
			if(VAT[key]){
				var option=document.createElement('a');
				option.setAttribute('id',VAT[key].id);
				option.setAttribute('name',VAT[key].name);
				option.onclick=function(){
					cell.getElementsByTagName('input')[0].value=this.name;
					cell.getElementsByTagName('input')[1].value=VAT[this.id].value;
					cell.getElementsByTagName('input')[2].value=this.id;
					div.style.display='none';
				}
				option.innerHTML=VAT[key].name+'<br>';
				option.setAttribute('style','cursor:pointer;');
				div.appendChild(option);
			}
		}

		var img=document.createElement('img');
		img.setAttribute('src','modules/EcmFkPackages/images/edit_position.gif');
		img.setAttribute('style','cursor:pointer;display:inline;');
		img.onclick=function(){
			if(div.style.display=='none')div.style.display='block';
			else div.style.display='none';
		}

		var edit = '<input type="text" tabindex="1" class="inputs" readonly style="text-align:right;" autocomplete="off" onKeyDown="return this.parentNode.myTable.KeyPressed(event,this.parentNode,\'decimalNumber\');" value="'+NumberToUserFormatNumber(0,"%")+'"><input type="hidden"><input type="hidden"><br>';
        cell.innerHTML = edit;
		cell.appendChild(div);
		if(document.getElementById('type').value!='correct')cell.appendChild(img);
      }
	if(i == 7) {
        cell.getData = function(data,noAlert) {
			var cn = this.getElementsByTagName('input');
			if (cn[0]) data.subprice = UserFormatNumberToNumber(cn[0].value);
			else data.subprice = 0;

			if (cn[1]) data.price = UserFormatNumberToNumber(cn[1].value);
			else data.price = 0;
        }

        cell.setData = function(data) {

		  var cn = this.getElementsByTagName('input');

          if(data.subprice) cn[0].value = NumberToUserFormatNumber(data.subprice);
		  else cn[0].value = NumberToUserFormatNumber(0);

          if(data.price) cn[1].value = NumberToUserFormatNumber(data.price);
		  else cn[1].value = NumberToUserFormatNumber(0);

        }



        var edit = '<input type="text"  readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="'+NumberToUserFormatNumber(0)+'"><br><input type="text"  readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="'+NumberToUserFormatNumber(0)+'">';

        cell.innerHTML = edit;

    }
      if(i == 8) {

        cell.change = function(select) {
          var c;
          if(select) {
            c = this.childNodes[0]; c.name = 'unit_name_p'; c.id = 'unit_name_p';
            c = this.childNodes[1]; c.name = 'unit_id_p'; c.id = 'unit_id_p';
          }
           else {
            c = this.childNodes[0]; c.name = ''; c.id = '';
            c = this.childNodes[1]; c.name = ''; c.id = '';
          }
        }
        cell.getData = function(data,noAlert) {
		  var cn=this.getElementsByTagName('input');

          data.unit_id = cn[0].value;
          data.unit_name = cn[0].value;
        }
        cell.setData = function(data) {
		  var cn=this.getElementsByTagName('input');
		  var cn=this.getElementsByTagName('input');
          if(data.unit_name){
			  cn[0].value = data.unit_name;
         	  cn[1].value = data.unit_name;
		  }
        }
        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            data.unit_id = data.unit_id;
            data.unit_name = data.unit_name;
            this.setData(data);
          }
        }
        var edit = '<input type="text" tabindex="1" style="display:none;"><input type="text" tabindex="1" autocomplete="off" class="inputs" style="text-align:right;">';
        cell.innerHTML = edit;
      }
	if(i == 9) {
        //cell.select = function() {  };
        cell.getData = function(data,noAlert) {
			var cn = this.getElementsByTagName('input');
			if (cn[0]) data.subtotal = UserFormatNumberToNumber(cn[0].value);
			else data.subtotal = 0;

			if (cn[1]) data.total = UserFormatNumberToNumber(cn[1].value);
			else data.total = 0;
        }

        cell.setData = function(data) {

		  var cn = this.getElementsByTagName('input');

          if(data.subtotal) cn[0].value = NumberToUserFormatNumber(data.subtotal);
		  else cn[0].value = NumberToUserFormatNumber(0);

          if(data.total) cn[1].value = NumberToUserFormatNumber(data.total);
		  else cn[1].value = NumberToUserFormatNumber(0);

        }

        var edit = '<input type="text"  readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="'+NumberToUserFormatNumber(0)+'"><br><input type="text"  readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="'+NumberToUserFormatNumber(0)+'">';

        cell.innerHTML = edit;
      }
	 if(i == 10) {
		  cell.change = function(select) {
          var c;
          if(select) {
            c = this.childNodes[0]; c.name = 'stock_p'; c.id = 'stock_p';
          }
           else {
            c = this.childNodes[0]; c.name = ''; c.id = '';
          }
        }
        cell.getData = function(data,noAlert) {
          var tmp = UserFormatNumberToNumber(this.firstChild.value);
          if(tmp == -1) {
            ERROR = true;
            data.stock = 0;
          } else {
            data.stock = tmp;
          }
        }
        cell.setData = function(data) {
		  if (data.type=='service') {this.firstChild.value='usługa'; return;}
		  console.log('set data: '+data.stock+' type: '+data.type);
          if(data.stock) this.firstChild.value = NumberToUserFormatNumber(data.stock); else this.firstChild.value = NumberToUserFormatNumber(0);
        }

		var stock;

  		stock = document.createElement('input');
  		stock.setAttribute('type','text');
        stock.className = 'inputs';
  		stock.style.textAlign = "right";
		stock.cell = cell;

		cell.appendChild(stock);
      }

      if(i == 11) {
        cell.getData = function(data) {
          var cn = this.getElementsByTagName('input');
           data.reserved = cn[0].value;
           data.parent_doc_rq = cn[1].value;

        }
        cell.setData = function(data) {
          var cn = this.getElementsByTagName('input');
          cn[0].value = ((data.reserved)?data.reserved:'');
          cn[1].value = ((data.parent_doc_rq)?data.parent_doc_rq:'');
  		}

	    var reserved = document.createElement('input');
       	reserved.setAttribute('type','hidden');
        reserved.setAttribute('value','');
        cell.appendChild(reserved);

	    var parent_doc_rq = document.createElement('input');
       	parent_doc_rq.setAttribute('type','hidden');
        parent_doc_rq.setAttribute('value','');
        cell.appendChild(parent_doc_rq);

        var img;
        //insert
        img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_INSERT_NEW_ROW']);
        img.setAttribute('src','modules/EcmFkPackages/images/insertrow.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() {
          this.parentNode.myTable.addRow(this.parentNode.parentNode.index+1);
        };
        //delete
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
        if(document.getElementById('type').value!='correct')cell.appendChild(document.createTextNode(" "));
        img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_DELETE_ROW']);
        img.setAttribute('src','modules/EcmFkPackages/images/deleterow.gif');
        img.style.cursor = 'pointer';
		//this.parentNode.parentNode.deleteRow();
        img.onclick = function() {
			removeReservation(cell);
			this.parentNode.parentNode.deleteRow();
		};
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
        if(document.getElementById('type').value!='correct')cell.appendChild(document.createElement('br'));
        //move up
        img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_MOVE_ROW_UP']);
        img.setAttribute('src','modules/EcmFkPackages/images/moverowup.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() { this.parentNode.parentNode.moveUp(); };
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
        if(document.getElementById('type').value!='correct')cell.appendChild(document.createTextNode(" "));
        //move down
        img = document.createElement('img');
        img.setAttribute('alt',MOD['LBL_MOVE_ROW_DOWN']);
        img.setAttribute('src','modules/EcmFkPackages/images/moverowdown.gif');
        img.style.cursor = 'pointer';
        img.onclick = function() { this.parentNode.parentNode.moveDown(); }
        if(document.getElementById('type').value!='correct')cell.appendChild(img);
      }
    }
    N.onSetCellData = function(row,cell,data) {
      if(cell.innerHTML == '') cell.innerHTML = '&nbsp;';
    }

    function ItemListFill() {
      var pl = document.getElementById('position_list').value;
      if(pl && pl != '') {
        try {
          pl = eval(pl);
          for(x in pl) { if(typeof(pl[x].code) != "undefined") { var pl_row = pl[x]; N.addRow().setData(pl_row); } }
        } catch(err) { pl = null; };
      }

      if(N.rowCount() == 0) N.addRow();
    }

    ItemListFill();
    calculateTotal = function() {

      var vats = new Object();
      var subtotal = 0;
      var total = 0;
	  //var cbm_total = 0;

      for(var i=0; i<N.rowCount(); i++) {
        var data = N.row(i).getData();
        if(OPT.to_is_vat_free == 0) {
          if(data.vat_id && data.name != '') {
            if(typeof(vats[data.vat_id]) != "object") { vats[data.vat_id] = new Object(); vats[data.vat_id]['vat'] = 0;}
            vats[data.vat_id]['vat'] += data.subtotal;
          }
        }
        subtotal += data.subtotal;
		//cbm_total += data.cbm;
      }

      total = subtotal;
      var rt = document.getElementById('result_table');
      for(var i=1; i<rt.rows.length-1; i++) { if(!vats[rt.rows.item(i).id]) { rt.deleteRow(i); --i; } else vats[rt.rows.item(i).id]['node'] = rt.rows.item(i); }
      for(var x in vats) {
        if(VAT[x]){
        	vats[x]['vat'] = vats[x]['vat']*(parseFloat(VAT[x].value)/100);
			total += vats[x]['vat'];
        	var txL = MOD['LBL_VAT']+' ('+VAT[x].name+')';
        	var txF = NumberToUserFormatNumber(vats[x]['vat']);
		}

        if(vats[x]['node']) {
          vats[x]['node'].id = x;
          vats[x]['node'].cells.item(0).innerHTML = txL;
          vats[x]['node'].cells.item(1).innerHTML = "<input type='text' readonly='readonly' style='border:0px;font-weight:900;width:100%;text-align:right;' value='"+txF+"'>";
        } else {
          rt.insertRow(1);
          rt.rows.item(1).id = x;
          rt.rows.item(1).insertCell(0);
          rt.rows.item(1).cells.item(0).className = 'positionsLabel';
          rt.rows.item(1).cells.item(0).innerHTML = txL;
          rt.rows.item(1).insertCell(1);
          rt.rows.item(1).cells.item(1).className = 'positionsField';
          rt.rows.item(1).cells.item(1).innerHTML = "<input type='text' readonly='readonly' style='border:0px;font-weight:900;width:100%;text-align:right;' value='"+txF+"'>";
        }

      }


      var total2 = total;

      var discount;
      if((discount = CheckDiscount(true)) == -1) discount = 0;

      var discount2 = subtotal*discount/100;

      total = total2-discount2;

      discount2 = NumberToUserFormatNumber(discount2).toString();
      total2 = ((OPT['type'] == "correct")?'-':'')+NumberToUserFormatNumber(total2).toString();
      total = ((OPT['type'] == "correct")?'-':'')+NumberToUserFormatNumber(total).toString();


      document.getElementById('subtotal').value = NumberToUserFormatNumber(subtotal);
      if(document.getElementById('total_2')) document.getElementById('total_2').value = total2;
      //rt.rows.item(rt.rows.length-2).cells.item(0).innerHTML = MOD['LBL_DISCOUNT']+' ('+NumberToUserFormatNumber(discount,'%')+')';
      //document.getElementById('discount_2').value = discount2;
      document.getElementById('total').value = total2;
      //document.getElementById('cbm_total').value = cbm_total;

	  document.getElementById('to_paid').innerHTML = total;

	  var paid_val = '0,00';
	  if (document.getElementById('paid_val').value!='')
		paid_val = document.getElementById('paid_val').value;
	  prepaid = '0,00';
	  if (document.getElementById('prepaid').value!='')
		prepaid = document.getElementById('prepaid').value;
	  var left = UserFormatNumberToNumber(total) - UserFormatNumberToNumber(paid_val) - UserFormatNumberToNumber(prepaid);

	  document.getElementById('left').innerHTML = NumberToUserFormatNumber(left);

    }

    ItemListSave = function(json) {
      //if(CheckDiscount() == -1) { ERROR = true; return false; }
      //calculateTotal();
      var data = '';
	  for(var i=0; i<N.rowCount(); i++) {
        data = data + '&p_' + i.toString() + '=' + JSON.stringifyNoSecurity(N.row(i).getData());
      }

      return data;
    }

    sqs_objects["code_p"] = {
      "method":"get_product_array",
      "modules":["EcmProducts"],
			"field_list":["date_entered", "code", "id", "encoded_unit_id", "vat_id", "encoded_category_id", "name", "selling_price", "currency_id"],
			"populate_list":["code_p", "code_p", "id_p", "unit_id_p", "vat_id_p", "category_id_p", "name_p", "price_p", "currency_id_p"],
      "conditions":[{"name":"code","op":"like_custom","end":"%","value":""}],
      "limit":"30",
      "order":"code",
      "no_match_text":"No Match"
    };
    sqs_objects["name_p"] = {
      "method":"get_product_array",
      "modules":["EcmProducts"],
			"field_list":["date_entered", "name", "id", "encoded_unit_id", "vat_id", "encoded_category_id", "code", "selling_price", "currency_id"],
			"populate_list":["name_p", "name_p", "id_p", "unit_id_p", "vat_id_p", "category_id_p", "code_p", "price_p", "currency_id_p"],
      "conditions":[{"name":"name","op":"like_custom","end":"%","value":""}],
      "limit":"30",
      "order":"name",
      "no_match_text":"No Match"
    };

    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=EcmFkPackages&action=generateNumber&type='+document.getElementById('type').value+'&template_id='+document.getElementById('template_id').value+'&record='+document.forms.EditView.record.value+'&type='+document.forms.EditView.type.value,
        function(result){
          var arr = eval(result)[0];
          document.getElementById('number').value = arr.number;
          document.getElementById('document_no').value = arr.document_no;
        },
        ''
      );
    };

    calculateTotal();
    if(OPT['new_number']) generateNumber();

    if(document.getElementById('template_id').value != '') document.getElementById('template_id').onchange();

    addEvent('template_id','change',generateNumber);

    //addEvent(document.forms.EditView.status,'change',canConfirm);

    setPREVIEW = function() {
      if(CheckDiscount() != -1) {
        calculateTotal();
        sendFormPostToPdf();
      }
    }

    setITEMS = function() {
      if(CheckDiscount() != -1) {
        calculateTotal();
        SetTab('ITEMS');
      }
    }


    setEMAIL = function(noCheck) {
      if(CheckDiscount() != -1) { calculateTotal();
        OPT['setEmailTab'] = 0;
        var view = true;
        if(!noCheck) {
          var record = document.forms.EditView.record.value;
          if(record == '') {
            alert('FkPackage is not saved!');
            view = false;
          }
          else {
            if(confirm('Save invoiceout changes?')) {
              OPT['setEmailTab'] = 1;
              view = false;
              SaveForm();
            }
          }
        }
        if(view) {
          SetTab('EMAIL');
		  //alert(document.forms.EditView.record.value);
          document.getElementById('emailTAB').innerHTML = "<iframe id=\'emailIFRAME\' style='border:none;width:100%;height:670px;' frameborder='no' src='index.php?module=EcmFkPackages&action=Emails&to_pdf=1&bodyclass=tabForm&type=out&pTypeTo="+document.getElementById('parent_type').value+"&pIdTo="+document.getElementById('parent_id').value+"&pTypeFrom=Users&pIdFrom="+document.getElementById('assigned_user_id').value+"&invoiceout_id="+document.forms.EditView.record.value+"&record="+document.forms.EditView.email_id.value+"'>Yours browser not accept iframes!</iframe>";
        }
      }
    }


    CHANGER.add('to_is_vat_free', 'checked', function(obj){
        obj.value = (obj.checked) ? 1 : 0;
        OPT['to_is_vat_free'] = obj.value;
        calculateTotal();
      },
      false
    );
	CHANGER.add('sell_date', 'value', function(obj){
		updatePaymentDate();
      },
      false
    );

	document.getElementById('payment_date_d').onchange = function() {
		updatePaymentDate();
	}
	//CHANGER.add('ecmpaymentcondition_id', 'value', function(obj){
		//updatePaymentDate();
     // },
     //// false
  //  );
    //CHANGER.add('parent_id','value',function(){alert('zmiana parent');},true);

	document.getElementById('prepaid').onchange = function() {
		calculateTotal();
	}

    document.getElementById('paid_val').onchange = function() {
		calculateTotal();
	}

    function setToAddrEmail(str) {
      if(str && str != '') str = eval(str); else str = '';
      if(typeof(str) == "object") str = str[0]; else str = '';
      if(document.getElementById('parent_type').value == 'Accounts') {
        //= 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:'';
		document.getElementById('payment_method').value = str.payment_method;
		if(str.payment_deadline) {
			document.getElementById('payment_date_d').value = str.payment_deadline;
			updatePaymentDate();
		}
        tmp = document.getElementById('to_nip'); if(tmp) tmp.value = (str.nip)?str.nip:'';
		if (str.name) {
			document.getElementById('parent_name_copy').value = str.name;
			document.getElementById('parent_name').value = str.name;
		}
        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:'';
        tmp = document.getElementById('supplier_code'); if(tmp) tmp.value = (str.supplier_code)?str.supplier_code:'';

		if (str.index_dbf) {
			document.getElementById('parent_index_dbf').innerHTML = '<a target="new" href="index.php?module=Accounts&action=DetailView&record='+str.id+'">'+str.index_dbf+'</a>';
		}
		if (str.invoice_type=='K')
			document.getElementById('ecmlanguage').value = "pl_pl";
		else {
			document.getElementById('ecmlanguage').value = "en_us";

			}

		//clear shipping address
		document.getElementById('parent_shipping_address_name').value = '';
		document.getElementById('parent_shipping_address_street').value = '';
		document.getElementById('parent_shipping_address_city').value = '';
		document.getElementById('parent_shipping_address_postalcode').value = '';
		document.getElementById('parent_shipping_address_country').value = '';
      }
    }


    //create Contact
    contactFL = new FormLoader();
    contactFL.load('EcmFkPackages','Contacts','contactFL');
    contactFL.onResponseData = function(data) {
	  //hideSmartInputFloater(true);
      document.forms.EditView.contact_id.value = data['id'];
      document.forms.EditView.contact_name.value = data['name'];
	  document.forms.EditView.parent_contact_name.value = data['name'];
	  document.forms.EditView.parent_contact_title.value = data['title'];
    };
//    contactFL.setEditDblClick(document.forms.EditView.contact_name);
    contactFL.onEditDblClick = function() {
		var ret =  "&fl_record="+document.forms.EditView.contact_id.value;
		if(document.forms.EditView.parent_type.value == "Accounts") ret += "&fl_account_id="+document.forms.EditView.parent_id.value+"&fl_account_name="+document.forms.EditView.parent_name.value;
					var ccc = document.forms.EditView.contact_name.value;
					var cc_pos = ccc.indexOf(" ");
					if(cc_pos != -1) {
						var cc_ = '&fl_first_name='+ccc.substr(0,cc_pos)+'&fl_last_name='+ccc.substr(cc_pos+1,ccc.length);
						ret += cc_;
					}
		return ret;
	}
    contactFL.onButtonClick = function() {
		var ret =  "&fl_record="+document.forms.EditView.contact_id.value;
		if(document.forms.EditView.parent_type.value == "Accounts") ret += "&fl_account_id="+document.forms.EditView.parent_id.value+"&fl_account_name="+document.forms.EditView.parent_name.value;
					var ccc = document.forms.EditView.contact_name.value;
					var cc_pos = ccc.indexOf(" ");
					if(cc_pos != -1) {
						var cc_ = '&fl_first_name='+ccc.substr(0,cc_pos)+'&fl_last_name='+ccc.substr(cc_pos+1,ccc.length);
						ret += cc_;
					}
		return ret;
	}
    //document.forms.EditView.contact_id.parentNode.appendChild(contactFL.createButton());

    function ParentIdChange(obj) {
       var list = '';
        if(document.getElementById('parent_type').value == 'Accounts') {
          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|nip|index_dbf|currency_id|invoice_type|id|payment_method|payment_deadline';
        }
        if(document.getElementById('parent_type').value == 'Contacts') {
          list = 'gdModule=Contacts&gdData=full_name|email1|primary_address_street|primary_address_city|primary_address_postalcode|primary_address_country';
        }
	   if (obj.value != '') {
		doRequest('index.php','module=EcmFkPackages&action=getData&'+list+'&gdId='+obj.value+'&to_pdf=1',setToAddrEmail);
		getAddresses();
		}

       if(obj.value == '' || (document.getElementById('stock_id').value=='' && OPT.selectStock!=false)) {
			setToAddrEmail('');
			var block = document.getElementById('blockAllFields');
			if(block) {
			} else {
				var main = document.getElementById('main');
				ChangeAccessFunction(main,'disabled');
			}
		} else {
			var main = document.getElementById('main');
			ChangeAccessFunction(main,'');
		}
	}



	document.getElementById('stock_id').onchange = function() {
		var main = document.getElementById('main');
		if (document.getElementById('parent_id').value!='' && this.value!='')
			ChangeAccessFunction(main,'');
		if (this.value!='')
			document.getElementById('stock_id').disabled='disabled';
	}

    CHANGER.add('parent_id', 'value', ParentIdChange, OPT['check_parent_id']);


	CHANGER.add('contact_id', 'value', function(obj) {
		if(obj.value == '') {
			document.forms.EditView.parent_contact_name.value = '';
			document.forms.EditView.parent_contact_title.value = '';
		} else {
			doRequest('index.php','module=EcmFkPackages&action=getData&gdModule=Contacts&gdData=full_name|title&gdId='+obj.value+'&to_pdf=1', function(str) {
				if(str && str != '') str = eval(str); else str = '';
      			if(typeof(str) == "object") str = str[0]; else str = '';
				document.forms.EditView.parent_contact_name.value = str.full_name;
				document.forms.EditView.parent_contact_title.value = str.title;
			});
		}
	},false);

	if(document.getElementById('parent_id').value == '') ParentIdChange(document.getElementById('parent_id'));


    var setTexts = function(no_confirm_question) {
		var resp = true;
		if(!no_confirm_question)
			resp = confirm(MOD.LBL_ALERT_ECMLANGUAGE_CHANGE);
		if(resp) {
			var el = document.getElementById('ecmlanguage');
			if (!el.value || el.value=="") el.value="pl_pl";
			//document.forms.EditView.header_text.value = OPT['ecmlanguage'][el.value]['texts']["Accounts"]['header_text'];
			//document.forms.EditView.footer_text.value = OPT['ecmlanguage'][el.value]['texts']["Accounts"]['footer_text'];
			//document.forms.EditView.ads_text.value = OPT['ecmlanguage'][el.value]['texts']["Accounts"]['ads_text'];
		}
    }
	YAHOO.util.Event.addListener(document.getElementById('ecmlanguage'),'change',function(){setTexts();});


    if(document.forms.EditView.record.value == '') setTexts(true);


    //create Parent
    parentFL = new FormLoader();
    parentFL.load('EcmFkPackages','Parents','parentFL');
    parentFL.onResponseData = function(data) {
      document.forms.EditView.parent_id.value = data['id'];
      document.forms.EditView.parent_name.value = data['name'];
	  ParentIdChange(document.forms.EditView.parent_id);

	};
    //parentFL.setEditDblClick(document.forms.EditView.parent_name);
    parentFL.onEditDblClick = function() { parentFL.createModule=document.forms.EditView.parent_type.value; return "&fl_record="+document.forms.EditView.parent_id.value; }
    parentFL.onButtonClick = function() { parentFL.createModule=document.forms.EditView.parent_type.value; return "&fl_name="+document.forms.EditView.parent_name.value; }
    //document.forms.EditView.parent_id.parentNode.appendChild(parentFL.createButton());

    //create Product
    productFL = new FormLoader();
    productFL.load('EcmQuestions','Parents','productFL');
    productFL.onResponseData = function(data) {
      data.price = data.selling_price;
      data.quantity = '1';
      N.selectedRow.setData(data);
      N.selectedRow.calculateTotal();
    };

	if(document.getElementById('type').value!='correct')AjaxSearchProducts = new AjaxSearch(document.getElementById('ITEMS'),true);



    //change normal to correct
    function InvoiceTypeChange(from_invoice) {
      var type = document.getElementById('type').value;
      if(type == "normal") {
        changeValidateRequired("EditView","ecminvoiceout_id",false);
        changeValidateRequired("EditView","ecminvoiceout_name",false);
        document.getElementById('ecminvoiceout_name').disabled = 'disabled';
        document.forms.EditView.btn_ecminvoiceout_name.disabled = 'disabled';
        document.forms.EditView.btn_clr_ecminvoiceout_name.disabled = 'disabled';
        OPT.invoice.type = type;

        if(from_invoice) {
          document.getElementById('ecminvoiceout_id').value = '';
          document.getElementById('ecminvoiceout_name').value = '';
          generateNumber();
        }
      }
      else if(type == "correct") {
        changeValidateRequired("EditView","ecminvoiceout_id",true);
        changeValidateRequired("EditView","ecminvoiceout_name",true);
        document.getElementById("ecminvoiceout_name").disabled = '';
        document.forms.EditView.btn_ecminvoiceout_name.disabled = '';
        document.forms.EditView.btn_clr_ecminvoiceout_name.disabled = '';
        OPT.invoice.type = type;
        calculateTotal();
        if(from_invoice) {
          var id = document.forms.EditView.record;
          if(id.value != "") {
            document.getElementById("ecminvoiceout_id").value = id.value;
            id.value = "";
            var name = document.getElementById("name");
            if(name)
              document.getElementById("ecminvoiceout_name").value = name.value;
            name.value = "";
            generateNumber();
            OPT.dontLoadInvoice = true;
          }
          generateNumber();
        }
      }
    }
    addEvent('type','change',function() { InvoiceTypeChange(true); });
    InvoiceTypeChange();

    function ViewCorrectInfo(record) {
      if(OPT.dontLoadInvoice == true) { OPT.dontLoadInvoice = false; return; }
      this.postData = function() {
        var pd = 'module=EcmFkPackages&action=GetCorrectInfo&to_pdf=1&record='+record;
        return pd;
      }
      this.Display = function(result) {

        var r = eval(result.responseText)[0];
        OPT.dontLoadAddress = true;
        for(x in r) {
          document.getElementById(x).value = r[x];
        }
        document.getElementById('to_is_vat_free').checked = (r['to_is_vat_free'] == 0) ? false : true;
        OPT['to_is_vat_free'] = r['to_is_vat_free'];
        ItemListClear(true);
        ItemListFill();

      }
      this.Fail = function(result){ alert('Error loading invoice correct info!');}
      YAHOO.util.Connect.asyncRequest('POST','index.php',{success:this.Display,failure:this.Fail},this.postData());
    }

    CHANGER.add('ecminvoiceout_id', 'value', function(obj) {
        if(obj.value != '') ViewCorrectInfo(obj.value);

      },
      true
    );
    CHANGER.add('ecminvoiceout_id', 'value', function(obj) {
		if(document.getElementById('type').value=="correct"){
			addToValidate('EditView', 'ecminvoiceout_id', 'text', false,MOD.LBL_ECMINVOICEOUT_NAME);
		}
	},
	true
	);
    //setInterval("updateUnitNames();",1000);
    //setInterval("updatePaymentDate();",2000);



    //quick view
    var main = document.getElementById('main');
    if(main) {
      var h2 = main.getElementsByTagName('h2')[0];
      if(h2) {
        h2.style.display = 'inline';
        var span = document.createElement('span');
        span.innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id="document_no_h"></span> - <span id="parent_name_h"></span> - <span id="parent_contact_name_h"></span> - <span id="parent_address_street_h"></span>&nbsp; &nbsp;<span id="parent_address_postalcode_h"></span>&nbsp;<span id="parent_address_city_h"></span>&nbsp; &nbsp;<span id="parent_address_country_h"></span> - <span id="total_h"></span>'
        h2.parentNode.appendChild(span);
      }
    }
    CHANGER.add('document_no','value',function(obj){document.getElementById('document_no_h').innerHTML = obj.value;},false);
    CHANGER.add('parent_contact_name','value',function(obj){document.getElementById('parent_contact_name_h').innerHTML = obj.value;},false);
    CHANGER.add('parent_address_street','value',function(obj){document.getElementById('parent_address_street_h').innerHTML = obj.value;},false);
    CHANGER.add('parent_address_postalcode','value',function(obj){document.getElementById('parent_address_postalcode_h').innerHTML = obj.value;},false);
    CHANGER.add('parent_address_city','value',function(obj){document.getElementById('parent_address_city_h').innerHTML = obj.value;},false);
    CHANGER.add('parent_address_country','value',function(obj){document.getElementById('parent_address_country_h').innerHTML = obj.value;},false);
    CHANGER.add('total','value',function(obj){document.getElementById('total_h').innerHTML = obj.value;},false);

	function ChangeAccessFunction(obj,type) {
		var objs = obj.getElementsByTagName('input');
		for(var i=0; i<objs.length; i++)
			if(objs[i].id != 'parent_name' && objs[i].id != 'parent_id' && objs[i].name != 'btn_parent_name' && objs[i].name != 'btn_clr_parent_name' && objs[i].name != 'btn_create_parent_name')
				objs[i].disabled = type;

		var objs = obj.getElementsByTagName('textarea');
		for(var i=0; i<objs.length; i++)
				objs[i].disabled = type;


		var objs = obj.getElementsByTagName('select');
		for(var i=0; i<objs.length; i++)
			if(objs[i].id != 'parent_type')
				if (OPT.selectStock!=false && objs[i].id=='stock_id') continue;
					else
						objs[i].disabled = type;

		if(type == 'disabled')
			TabsMainBlock = true;
		else
			TabsMainBlock = false;

	}

	//mz
	if (document.getElementById('parent_type')!='EcmStockDocOuts') {
		//addToValidate('EditView', 'stock_id', 'text', false,MOD.LBL_STOCK_NAME);
		//addToValidate('EditView', 'stock_name', 'text', false,MOD.LBL_STOCK_ID);
	} else {
		document.getElementById('stock_id').disabled='disabled';
		OPT.selectStock = false;
	}
/*
	if (OPT.from_wz==false && OPT.from_sale===false) {
	TabsMainBlock = true;
	document.getElementById("stock_id").onchange= function() {
		if (document.getElementById("stock_id").value!="")
			this.disabled=true;
		if(document.getElementById("stock_id").value!="" && document.getElementById("parent_id").value!=""){
				TabsMainBlock = false;
			}
			else{
				TabsMainBlock = true;
			}
	};
	document.getElementById("parent_id").onchange= function() {
		alert('change!');
		if(document.getElementById("stock_id").value!="" && document.getElementById("parent_id").value!=""){
				TabsMainBlock = false;
			}
			else{
				TabsMainBlock = true;
			}
	};

	}
*/
	setInterval("BlockProducts();",1000);
    CHANGER.startTimer();
	document.getElementById("payment_date").readOnly=true;
	SetTabIndexs(0);
	document.VAT1=VAT;
	document.PositionList=N;
	document.forms.EditView.parent_name.focus();
	//if (OPT.from_sale==true)
		//transformSaleIntoTemponaryReservation(document.getElementById("temp_id").value);

	//manage reservations
	if (OPT.parent_doc_type=='EcmSales') {
      for(var i=0; i<N.rowCount(); i++) {
        var data = N.row(i).getData();
			updateReservation(i, data.quantity*(-1));
			getProductQuantity(i, "saveReservation");
		}
		getAddresses(document.getElementById('parent_id'));
	}

	if (document.getElementById('type').value=='correct') {

	}

	}

);