function dump()
{
	var cos = document.forms.EditView.elements;
	for ( foo in cos ){
		console.log(cos[foo].name + " = " + cos[foo].value);
	}

}

function checkcash(){
	 var val = document.getElementById('ecmcash_id').value;
	 url='index.php?module=EcmKpkw&action=getcash&kasa='+val+'&to_pdf=1';
	var req=mint.Request();
	var wal;
	req.OnSuccess = function() {
		if (this.responseText == -1) return;
		if (this.responseText!=''){
		this.responseText = this.responseText.replace('.', ',');
		wal=this.responseText;
		    var sel = document.getElementById('currency_id');
    var opts = sel.options;
    for(var opt, j = 0; opt = opts[j]; j++) {
        if(opt.value == wal) {
            sel.selectedIndex = j;
            break;
        }
    }
		}
	}
	req.Send(url);	

}


function getNBPCurrencyExchange() {
	var c_id = document.getElementById('currency_id').value;
	var date = document.getElementById('register_date').value;
	
	url='index.php?module=Currencies&action=getNBPCurrencyExchange&c_id='+c_id+'&date='+date+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		if (this.responseText == -1) return;
		if (this.responseText!=''){
		this.responseText = this.responseText.replace('.', ',');
		document.getElementById('currency_value').value = (this.responseText);
		}
	}
	req.Send(url);	
}
setInterval('getNBPCurrencyExchange();',1000);

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 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('ecmkpkw_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, 600, 400, "", 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 ItemListClear() {

    while (N.rowCount() > 0)
        N.row(0).deleteRow();

}




	preview_pdf = function() {
	
			//console.log('test');         
			var type = document.getElementById('preview_type').value;
                
               switch(type)
				{
                    default:
                        type = '';
                        break;
                    case 'exp':
                        type = 'exp';
                        break;
                    case 'pl':
                        type = 'pl';
                        break;
                }
                
				console.log(type);
	
			  document.getElementById('previewPDF').innerHTML = '<iframe style="border:none;width:100%;height:1200px;" frameborder="no" src="index.php?module=EcmKpkw&action=previewPDF&type='+type+'&to_pdf=1&method=I&record='+document.forms.DetailView.record.value+'#zoom=75">Yours browser not accept iframes!</iframe>';
	}



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 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=EcmKpkw&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 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=EcmKpkw&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('ecmkpkw_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=EcmKpkw&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'] = 'EcmKpkw';
  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'] = 'EcmKpkw';
  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=EcmKpkw&action=previewPDF&to_pdf=1&from=EcmKpkw',{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=EcmKpkw&action=previewPDF&to_pdf=1&from=EcmKpkw',{zoom:75}); 
	  }
	  else{
      	  SetTab('PREVIEW');
      	  document.getElementById('previewPDF').innerHTML = "<iframe style='border:none;width:100%;height:1200px;' frameborder='no' src='index.php?module=EcmKpkw&action=previewPDF&to_pdf=1&from=EcmKpkw#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=EcmKpkw&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();	
    };
    function generateNumber() {
	//alert('p');
      if(document.getElementById('template_id').value == '') { alert('There are no DocumentTemplates in data base!'); return;}
	 
      doRequest(
        'index.php',
        'to_pdf=1&generate=1&module=EcmKpkw&action=generateNumber&type=normal&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; 
		  //alert('p');
        },
        ''
      );
    };   
	    if(OPT['new_number']) generateNumber();   
      
    // 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=EcmKpkw&action=generateNumber'+
			// '&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; 
        // },
        // ''
      // );
    // };   
       
    //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();
      // }
    // }    
	
	//CHANGER.add('ecmpaymentcondition_id', 'value', function(obj){ 
		//updatePaymentDate();
     // },
     //// false
  //  );
    //CHANGER.add('parent_id','value',function(){alert('zmiana parent');},true);  
    
	
    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('index_dbf'); if(tmp) tmp.value = (str.index_dbf)?str.index_dbf:'';
		tmp = document.getElementById('parent_name_copy'); if(tmp) tmp.value = (str.name)?str.name:'';
//        tmp = document.getElementById('to_nip'); if(tmp) tmp.value = (str.sic_code)?str.sic_code:'';

      }
    }
    

    //create Contact
    // contactFL = new FormLoader(); 
    // contactFL.load('EcmKpkw','Contacts','contactFL');
    // contactFL.onResponseData = function(data) { 
	  // hideSmartInputFloat	er(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=EcmKpkw&action=getData&'+list+'&gdId='+obj.value+'&to_pdf=1',setToAddrEmail);
//		getAddresses();
		}
	    		
	}
	
	
	

	
    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=EcmKpkw&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('EcmKpkw','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();
    };


    
  
  
    



    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
	checkcash();
    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;		
			}
	};

	}
*/	
    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);
		

	
	}
 
);

preview_pdf = function() {
	
			console.log('test');         
			var type = document.getElementById('preview_type').value;
                
               switch(type)
				{
                    default:
                        type = '';
                        break;
                    case 'exp':
                        type = 'exp';
                        break;
                    case 'pl':
                        type = 'pl';
                        break;
                }
                
				console.log(type);
 
			  document.getElementById('previewPDF').innerHTML = '<iframe style="border:none;width:100%;height:1200px;" frameborder="no" src="index.php?module=EcmKpkw&action=previewPDF&type='+type+'&to_pdf=1&method=I&record='+document.forms.DetailView.record.value+'#zoom=75">Yours browser not accept iframes!</iframe>';
	}

