function setColor(inp,tr){
	var color="#F0FFA0";
	for(var i=0;i<inp.length;i++){
		if(inp[10].value!=1){
			inp[i].style.backgroundColor=color;
			tr.style.backgroundColor=color;
		}
		else {
			inp[i].style.backgroundColor="";
			tr.style.backgroundColor="";
		}
	}
}
function setNo(){
	var tab=document.getElementById("tbody");
	var tr=tab.getElementsByTagName("tr");
	var n=0;
	for(var i=0;i<tr.length;i++){
		var inp=tr[i].getElementsByTagName("input");
		if(inp[10].value!=1){
			n++;
			inp[0].value=n;
		}
		else inp[0].value="";
	}
}
function updateStyles(){
	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");
		setColor(inp,tr[i]);
	}
	setNo();
	return true;
}


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

}

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

function sendToConfirmEcmInsideeOrder(record) {
	if(typeof(record) == "string") {
		var status = "s20";
		doRequest(
			'index.php',
			'module=EcmInsideOrders&action=SetStatus&to_pdf=1&status='+status+'&record='+record,
			function(results) {
				var obj = eval(results);
				if(obj[0]) obj = obj[0];
				if(typeof(obj) == "object") {
					if(document.forms.DetailView.record.value == obj['record']) {
						document.getElementById('statusEcmInsideeOrder').innerHTML = obj['status']['text'];
						if(obj['status']['code'] == "s20") {
							document.forms.DetailView.send_to_confirm.style.display = 'none';
							document.forms.DetailView.edit_button.style.display = 'none';
							var c = document.getElementById('confirmingEcmInsideeOrder');
							if(c) c.style.display = '';
						}
						if(obj['status']['code'] == "s30") {
							document.forms.DetailView.send_to_confirm.style.display = 'none';
							document.forms.DetailView.edit_button.style.display = 'none';
							document.getElementById('confirmingEcmInsideeOrder').style.display = 'none';
							document.forms.DetailView.quote_to_sale.style.display = '';
							document.forms.DetailView.quote_to_invoice.style.display = '';
						}
					}
					alert(obj['message']);
				}
			}
		);
	}
}

function AcceptEcmInsideeOrder(record) {
	if(typeof(record) == "string") {
		var status = "accepted";
		doRequest(
			'index.php',
			'module=EcmInsideOrders&action=SetStatus&to_pdf=1&status='+status+'&record='+record,
			function(results) {
				var obj = eval(results);
				if(obj[0]) obj = obj[0];
				if(typeof(obj) == "object") {
					if(document.forms.DetailView.record.value == obj['record']) {
						document.getElementById('statusEcmInsideeOrder').innerHTML = obj['status']['text'];
						if(obj['status']['code'] == "accepted") {
							document.forms.DetailView.send_to_confirm.style.display = 'none';
							document.forms.DetailView.edit_button.style.display = 'none';
							document.getElementById('confirmingEcmInsideeOrder').style.display = 'none';
							document.forms.DetailView.quote_to_sale.style.display = '';
							document.forms.DetailView.quote_to_invoice.style.display = '';
						}
					}
					alert(obj['message']);
				}
			}
		);
	}	
	location.href='index.php?module=EcmInsideOrders&action=DetailView&record='+document.forms.DetailView.record.value;
}

function RejectEcmInsideeOrder(record) {
	if(typeof(record) == "string") {
		var status = "not_accepted";
		doRequest(
			'index.php',
			'module=EcmInsideOrders&action=SetStatus&to_pdf=1&status='+status+'&record='+record,
			function(results) {
				var obj = eval(results);
				if(obj[0]) obj = obj[0];
				if(typeof(obj) == "object") {
					if(document.forms.DetailView.record.value == obj['record']) {
						document.getElementById('statusEcmInsideeOrder').innerHTML = obj['status']['text'];
						if(obj['status']['code'] == "not_accepted") {
							document.getElementById('confirmingEcmInsideeOrder').style.display = 'none';
							document.forms.DetailView.edit_button.style.display = '';
						}
					}
					alert(obj['message']);
				}
			}
		);
	}
	location.href='index.php?module=EcmInsideOrders&action=DetailView&record='+document.forms.DetailView.record.value;
}

addEvent(

  window,

  'load',

  function () {



    //initialize table

    N = new MyTable('itemsTable');



    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;

        

        var img = this.cells.item(1).getElementsByTagName('img');

        if(!this.newPos) img[0].src = "modules/EcmInsideOrders/images/edit.gif";

                    else img[0].src = "modules/EcmInsideOrders/images/editset.gif";

        

        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 = new Object();

        this.cells.item(3).getData(data,true);

        this.cells.item(4).getData(data,true);

        this.cells.item(5).getData(data,true);

        this.cells.item(6).getData(data,true);

        this.cells.item(7).getData(data,true);

        if(data.quantity && data.price)

          data.total = data.quantity*data.price;

        else

          data.total = 0;

        this.cells.item(6).setData(data);

        calculateTotal();

      }

    }

    N.onCreateCell = function(cell) {

      

      var i = cell.index;

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

      cell.noSelect = true;
      

      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.getData = function(data) {

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

          data.code = cn[0].value;

          data.id = cn[1].value;
       

        }

        cell.setData = function(data) {

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

          if(data.code) cn[0].value = data.code;

          if(data.id) cn[1].value = data.id;
       

        }

        

        var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" autocomplete="off" >';

        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_value = document.createElement('input');

        vat_value.setAttribute('type','hidden');

        vat_value.setAttribute('value',OPT['default_vat']);

        cell.appendChild(vat_value);

        var category_id = document.createElement('input');

        category_id.setAttribute('type','hidden');

        category_id.setAttribute('value',OPT['default_category']);

        cell.appendChild(category_id); 

        

      }

      

      if(i == 2) {  

      

        cell.getData = function(data) {

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

          data.name = cn[0].value;      

        }

        cell.setData = function(data) {

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

          if(data.name) cn[0].value = data.name;        

        }           

        var textarea = '<textarea tabindex="1" readonly="readonly" style="height:100%"; class="inputs"></textarea>';

        cell.innerHTML = textarea;      

      }

      

      if(i == 3) {
        cell.getData = function(data,noAlert) {
          var tmp = UserFormatNumberToNumber(this.firstChild.value);
          if(tmp == -1) {
            ERROR = true;
            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,'',4,2); else this.firstChild.value = NumberToUserFormatNumber(0);
        }
        var edit = '<input type="text" readonly="readonly" tabindex="1" style="text-align:right;" autocomplete="off" class="inputs" value="'+NumberToUserFormatNumber(1)+'">';
        cell.innerHTML = edit;
      }
      if(i == 4) {
        cell.getData = function(data,noAlert) {
          var tmp = UserFormatNumberToNumber(this.firstChild.value);
          if(tmp == -1) {
            ERROR = true;
            data.prod_quantity = 0;
            this.firstChild.style.color = 'red';            
          }
		  else {
            data.prod_quantity = tmp;
            this.firstChild.style.color = 'black';
          }
        }
        cell.setData = function(data) {
          if(data.prod_quantity) this.firstChild.value = NumberToUserFormatNumber(data.prod_quantity,'',4,2); else this.firstChild.value = NumberToUserFormatNumber(0);
        }
        var edit = '<input type="text" readonly="readonly" tabindex="1" style="text-align:right;" autocomplete="off" class="inputs" value="'+NumberToUserFormatNumber(1)+'">';
        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.price = 0;

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

          } else {

            data.price = tmp;

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

          }

        }

        cell.setData = function(data) {

          if(data.price) this.firstChild.value = NumberToUserFormatNumber(data.price); else this.firstChild.value = NumberToUserFormatNumber(0);

        }

       

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

        cell.innerHTML = edit;      

      }

      
      if(i == 6) {               
         
        cell.getData = function(data,noAlert) {
			var cn = this.getElementsByTagName('input');
            data.component = cn[0].value;
            data.component_quantity = cn[1].value;
            data.product_id = cn[2].value;
            data.guid = cn[3].value;
        }
        cell.setData = function(data) {
          if(data.component) this.getElementsByTagName('input')[0].value = data.component;
          if(data.component_quantity) this.getElementsByTagName('input')[1].value = data.component_quantity;
          if(data.product_id) this.getElementsByTagName('input')[2].value = data.product_id;
          if(data.guid) this.getElementsByTagName('input')[3].value = data.guid;
        }
        cell.onDeselect = function() {
          ERROR = false;
          var data = new Object();
          this.getData(data);
          if(!ERROR) {
            this.setData(data);
          }
        }    

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

      if(i == 7) {

        //cell.select = function() {  };

        cell.getData = function(data) {

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

          data.total = UserFormatNumberToNumber(cn[0].value);

        }

        cell.setData = function(data) {

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

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

        }   

        var edit = document.createElement('input');

        edit.setAttribute('type','text');

        edit.setAttribute('value',NumberToUserFormatNumber(0));

        edit.setAttribute('readOnly','readonly');

        edit.className = 'inputs';
        
        edit.style.textAlign = "right";
        
        cell.appendChild(edit);      

      }

  



    }  

    N.onSetCellData = function(row,cell,data) {

      if(cell.innerHTML == '') cell.innerHTML = '&nbsp;';

    }



    var pl = document.getElementById('position_list').value;

    if(pl && pl != '') {

      try {

        pl = eval(pl);

        for(x in pl) { 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();


    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.total;
          }
        }
        subtotal += data.total;
		cbm_total += data.cbm*data.quantity;
      }
         
      total = subtotal;
      var rt = document.getElementById('result_table');
      for(var i=1; i<rt.rows.length-4; 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;
      document.getElementById('total').value = total;
      
    } 

        

    calculateTotal();

    

    setPREVIEW = function() {  
	  if(SHOW_PDF_IN_DIV==1){
		  //HideLoadingView(); 
		  //SetTab('preview_PREVIEW');
		  EcmPreviewPDF('index.php?module=EcmInsideOrders&action=previewPDF&to_pdf=1&method=I&record='+document.forms.DetailView.record.value,{zoom:75}); 
	  }
	  else{
          SetTab('panel_PREVIEW');
		  document.getElementById('previewPDF').innerHTML = '<iframe style="border:none;width:100%;height:1200px;" frameborder="no" src="index.php?module=EcmInsideOrders&action=previewPDF&to_pdf=1&method=I&record='+document.forms.DetailView.record.value+'#zoom=75">Yours browser not accept iframes!</iframe>';
	  }
    }    


if(!OPT.user.access.send_email) 
	setEMAIL = function() { alert(MOD['LBL_ACCESS_UNAVAIBLE_DELETE_EMAIL']); };
else
    setEMAIL = function(noCheck) {  

        SetTab('panel_EMAIL');

        document.getElementById('emailTAB').innerHTML = '<iframe id="emailIFRAME" style="border:none;width:100%;height:670px;" frameborder="no" src="index.php?module=EcmInsideOrders&action=Emails&to_pdf=1&type=out&pTypeTo='+document.forms.DetailView.parent_type.value+'&pIdTo='+document.forms.DetailView.parent_id.value+'&pTypeFrom=Users&pIdFrom='+document.forms.DetailView.assigned_user_id.value+'&quote_id='+document.forms.DetailView.record.value+'&record='+document.forms.DetailView.email_id.value+'">Yours browser not accept iframes!</iframe>';

    }  


    
    setInterval(function() {
          doRequest('index.php',"module=EcmInsideOrders&action=subpanels&to_pdf=1&record="+document.forms.DetailView.record.value,
            function(result) {
              if(result != '') document.getElementById('subpanels_div').innerHTML = result;
            }
          );
      },
      10000
    );
	
    setInterval("updateStyles();",100);
    
	
    //quick view
    var main = document.getElementById('main');
    if(main) {
      var h2 = main.getElementsByTagName('h2')[0];
      if(h2) {
        h2.style.display = 'inline';
		var quickInfoH2 = document.getElementById('quickInfoH2');
		if(quickInfoH2) { h2.parentNode.appendChild(quickInfoH2); quickInfoH2.style.display = ''; }
      }
    }

	if(OPT['setTab'] && OPT['setTab'] != '') {
		if(OPT['setTab'] == 'EMAIL') setEMAIL();	
	}

  }

);



