function searchCode(start_from) {
	url='index.php?module=EcmProducts&action=searchCode&start='+start_from+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		  document.getElementById("code").value = this.responseText;
	};
	req.Send(url);	
}

function checkCode(code) {
	if (document.forms.EditView.record.value!="") return;
	
	url='index.php?module=EcmProducts&action=checkCode&code='+code+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		  if (this.responseText=='0') alert(MOD.LBL_CODE_ERROR);
		  if (this.responseText=='2') alert('Istnieje kod typu: '+code+'_-----');
	};
	req.Send(url);		
}

function freeCodes(code) {
	window.open("index.php?module=EcmProducts&action=freeCodes&code="+code, "_blank");
}

function getBaseComponents(type) {
	if (type == 1)
		var code = OPT.base_code;
	if (type == 2)
		var code = document.getElementById("components_code").value;
	
	url='index.php?module=EcmProducts&action=getBaseComponents&product_code='+code+'&to_pdf=1';
	var req=mint.Request();
	req.OnSuccess = function() {
		  ItemListClear();
		  OPT.base_code = null;
	      try {
	          pl = eval(this.responseText);        
	          for(x in pl) { var pl_row = pl[x]; if(!pl[x].code || pl[x].code == '') {} else N.addRow().setData(pl_row); }
	        } catch(err) { pl = null; };
	};
	req.Send(url);		
}

function SetTabIndexs() {
	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++;
			}
		}
	}
}

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('name').focus(); }

function my_popup(module, field_array, met, 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, met, 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 cursorEOT(isField) {
  isRange = isField.createTextRange();
  isRange.move('textedit');
  isRange.select();
  testOverflow = isField.scrollTop;
  if (testOverflow != 0){return true}
  else {return false}
}

function adjustRows(isField) {
  while (cursorEOT(isField)){isField.rows++}
}

function insertText(isField,isText) {
  isField.value = testText;
  isField.focus();
}

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')) {
		  
		var result = confirm(MOD.LBL_CONFIRM_QUESTION);
		if(result) document.forms.EditView.status.value = (OPT['auto_commiting']?'s30':'s20');
	
		doRequest('index.php',getFormPost('Save'),function(result){
			document.forms.EditView.record.value = result.substring(result.length-36);
			alert(MOD['LBL_SAVED']);
			if(OPT['setEmailTab']) setEMAIL(true); else window.location = 'index.php?module='+document.forms.EditView.module.value+'&action=DetailView&record='+document.forms.EditView.record.value;
		},
		MOD['LBL_NOT_SAVED']
	  );      
	  } else { alert(MOD['LBL_NOT_SAVED']); HideLoadingView(); return false; }
	
  },200);

}

function ItemListClear() {
  while(N.rowCount()>0) N.row(0).deleteRow();
}




function getFormPost(action) {
  if(!action) action = 'previewPDF';
  var pd = 'to_pdf=1'+'&module=EcmQuotes&action='+action+'&record='+document.forms.EditView.record.value;
  pd += '&cache=fromJava'+ItemListSave(true);
  
  var pd2 = new Object();
  
  pd2['module'] = 'EcmQuotes';
  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;
    }
  }
  
  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(); 
		  SetTab('PREVIEW');
		  EcmPreviewPDF('index.php?module=EcmQuotes&action=previewPDF&to_pdf=1&from=EcmQuotes',{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=EcmQuotes&action=previewPDF&to_pdf=1&from=EcmQuotes',{zoom:75}); 
	  }
	  else{
      	  SetTab('PREVIEW');
      	  document.getElementById('previewPDF').innerHTML = "<iframe style='border:none;width:100%;height:1200px;' frameborder='no' src='index.php?module=EcmQuotes&action=previewPDF&to_pdf=1&from=EcmQuotes#zoom=75'>Yours browser not accept iframes!</iframe>";
	  }
    }
  );
}

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

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

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

  

    ItemListSave = function(json) { 
      //if(CheckDiscount() == -1) { ERROR = true; return false; }
      //calculateTotal();
      var data = new Object();
	  for(var i=0; i<N.rowCount(); i++) {
        data[i.toString()] = N.row(i).getData();
      }
      return json ? JSON.stringifyNoSecurity(data) : data;
    } 
    var sqs_objects = [];
    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=EcmQuotes&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; 
        },
        ''
      );
    };   

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

    CHANGER.startTimer();


	  var check_form_ = check_form;
	  check_form = function(formname) {
	      CTABLE.saveItems();
	      ATABLE.saveItems();
		 // return false;
		  if ((document.getElementById('group_ks').value)=='0') {
			  alert('Grupa księgowa nie może być pusta!');
			  return false;		  
		  }
		  //document.forms.EditView.position_list.value = ItemListSave(true);
		  saveItems3();
		  saveItems4();
		  
		  return check_form_(formname);
	  }
	  
  
  
  }

);



