<?
  include_once('views/invoice-tabbed.php');
  include_once('models/poModel.php');
?>
 <script type="text/javascript" src="calendar1.js"></script>
<div id='tab-body:0' class='tab-body' <? if ($_SESSION['Xactivetab']=="0") { echo "style='border: none; display: block;'"; } else { echo "style='border: none; display: none;'"; } ?>>
  <table width="945" border="1">
    <tr>
      <td width="115" class=listheader>Invoice No</td>
      <td width="162"><label>
        <input type="text" name="txt_newinvoice" id="txt_newinvoice" />
      </label></td>
      <td width="38">&nbsp;</td>
      <td width="114" class=listheader>Vendor</td>
      <td width="488"><label>
      <select name="vendor_list" id="vendor_list" style="width: 410px;" onchange="resetAllSelection();PO_List(PO_List02,$('#vendor_list').val());">
      		<? 
			//include('object-selectsupplier.tpl');
			include('object-selectsupplierproject.php'); 
			?>
	  </select>
      </label></td>
    </tr>
    <tr>
      <td class=listheader>Date  </td>
      <td><input type="text" name="txt_invoicedate" id="txt_invoicedate" /><a href="javascript:cal1.popup();"><img src="images/icon/cal.gif" width="16" height="16" border="0" alt="Click to select date"></td>
      <td>&nbsp;</td>
      <td class=listheader>PO No</td>
      <td><label>
      <select name="PO_List02" id="PO_List02" style="width: 120px;"  onchange="validateInvoiceCriteria()">
		<option value='' selected>--Select PO--</option>
      </select>
      </label></td>
    </tr>
    <tr>
      <td class=listheader>Amount</td>
      <td><input type="text" name="txt_amount" id="txt_amount" disabled="True" style="background-Color:#BFB9AE" /></td>
      <td>&nbsp;</td>
      <td class=listheader>DO No</td>
      <td><label>
      <select name="DO_List02" id="DO_List02" style="width: 120px" onchange="Ajax_Request(do_detail2,'page=invoice&task=do_listtable&param1='+ $('#DO_List02 option:selected').text()  + '&param2='+ $('#vendor_list').val()+ '&param3='+ $('#PO_List02').val())">
	  <option value='' selected>--Select DO--</option>
	  </select>
      </label></td>
    </tr>
    <tr>
      <td class=listheader>Add. Charges</td>
      <td><input type="text" name="txt_addcharge" id="txt_addcharge" /></td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
 
	<hr/>   
	Available Invoice : <Select id="lst_doinvoice" name="lst_doinvoice">
							<option value="" selected>--Select INVOICE--</option>");
						</Select>
						<input type="button" name="btn_dotoinvoice" id="btn_dotoinvoice" value="add" onclick="fnc_dotoinvoice()" />
						<input type="button" name="btn_dotonewinvoice" id="btn_dotonewinvoice" value="add New" onclick="fnc_dotonewinvoice()" />
	<hr/>

   <div  id="do_detail2" name="do_detail2"></div>
   <div  id="invoice_detail2" name="invoice_detail2"></div>

  <br />
  <table width="943" border="0">
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td align="right"><input type="button" name="btn_saveinvoice" id="btn_saveinvoice" value="Save" onclick="fnc_saveinvoice()" />
         <!-- <input type="button" name="button3" id="button3" value="Edit" /> yusr -->
          <input type="button" name="button4" id="button4" value="Cancel" onclick="validateInvoiceCriteria()" /></td>
    </tr>
  </table>
  </div>

<div id='tab-body:1' class='tab-body' <? if ($_SESSION['Xactivetab']=="1") { echo "style='border: none; display: block;'"; } else { echo "style='border: none; display: none;'"; } ?>>
  <table width="558" border="1">
    <tr>
      <td width="124" class=listheader>Vendor Name</td>
      <td colspan="2">
	  <select name="vendorname" id="vendorname" style="width: 410px;" onchange="PO_List(PO_List01,$('#vendorname').val())">
		<? 
			//include('object-selectsupplier.tpl');
			include('object-selectsupplierproject.php'); 
		?>
	  </select>
	  </td>
    </tr>
    <tr>
      <td class=listheader>PO No.</td>
      <td colspan="2">
		<select name="PO_List01" id="PO_List01" onchange="$('#search_invoice').click()">
			<option value='' selected>--Select PO--</option>
		</select>
	  </td>
    </tr>
    <tr>
      <td class=listheader>Invoice No</td>
      <td width="146"><label>
        <input type="text" name="txt_invoicesearch" id="txt_invoicesearch" 
		onkeypress="if(event.keyCode == 13){$('#search_invoice').click();}" />
	  </label></td>
      <td width="266"><input type="button" name="search_invoice" id="search_invoice" value="Search"   onclick="$('#invoice_detail').html('');   Ajax_Request(invoice_result01,'page=invoice&task=invoice_listtable&param1='+ $('#vendorname').val()+'&param2='+ $('#PO_List01').val()  + '&param3=' + $('#txt_invoicesearch').val() )"/></td>
    </tr>
  </table>
  <br />
  <div  id="invoice_result01" name="invoice_result01">
	  <table width="947" border="1">
		<tr>
		  <td width="176" class=listheader>INVOICE NO</td>
		  <td width="465" class=listheader>VENDOR NAME</td>
		  <td width="133" class=listheader>PO</td>
		  <td width="145" class=listheader>AMOUNT</td>
		</tr> 
	  </table>
  </div>
  <div  id="invoice_detail" name="invoice_detail"></div>
  </div>

<div style='visibility:hidden'><image src=bigrotation2.gif></image></div>
<script type="text/javascript">

    var cal1 = new calendar1(txt_invoicedate);
    cal1.year_scroll = true;
    cal1.time_comp = false;



function fnc_saveinvoice(){
	Ajax_Request(do_detail2,'page=invoice&task=save_invoice&param1='
		+ $('#vendor_list').val()+ '&param2='+ $('#PO_List02').val() 
		+'&param3=' + $('#txtdo_removelist').val() 
		+'&param4=' + $('#txtdo_newlist').val());
	Ajax_Request(invoice_detail2,'page=invoice&task=invoice_listdetail&param1='+ $('#vendor_list').val()+ '&param2='+ $('#PO_List02').val());
}

function fnc_dotonewinvoice(){
	
	//Check For Invoice	
	if ($('#txt_newinvoice').val()==''){
		alert('Please insert Invoice No.!');
		return;
	}

	//Check For Invoice Availability
	if($('#lst_doinvoice option[text="'
		+$('#txt_newinvoice').val()+'"]').length!=0){
		$('#lst_doinvoice option[text="'+$('#txt_newinvoice').val()+'"]').attr('selected',true);
		alert('Invoice No. Already Exist In the List!');
		return;
	}

	//Check For DO	
	if ($('#DO_List02').val()==''){
		alert('DO Not Selected');
		return;
	}
	
	//Send To To Invoice List
	$('#lst_doinvoice').append($('<option></option>')
			.val('new').html($('#txt_newinvoice').val()).attr('selected',true));
	//$('#lst_doinvoice').change();
	fnc_dotoinvoice(true);
}

function fnc_dotoinvoice(isNew){

	if(isNew === undefined){
		//Check For DO	
		if ($('#DO_List02').val()==''){
			alert('DO Not Selected!');
			return;
		}
		
		if ($('#lst_doinvoice option:selected').val()==''){
			alert('Invoice No. Not Selected!');
			return;
		}
	}

	//lst_doinvoice
	//$('#tbl_issuedinvoice tbody>tr:last').clone(true).insertAfter('#tbl_issuedinvoice //tbody>tr:last');
    
	var $do_no=$('#DO_List02 option:selected').text();
	var $invoice_no=$('#lst_doinvoice option:selected').text();
	var $invoce_date=hexEncode($('#txt_invoicedate').val());
	var $invoce_addcharge=hexEncode($('#txt_addcharge').val());
	var $unique_id=($do_no+"_"+$invoice_no + "_" 
				  + $invoce_date + "_" + $invoce_addcharge).replace(/ /g,'-x01-');

	if ($('#tr_' + $unique_id).length != 0)
	{
		alert('DO Already In List(s)');
		return;
	}

    $('#tbl_issuedinvoice > tbody:last').append("<tr id='tr_"+$unique_id+"' name='tr_"+$unique_id+"'>"
	   + "<td align='left' valign='top'>"
	   + "<input type='button' name='btndelete_do' id='btndelete_do' value='Delete' " 
	   + "onclick='remove_element_do(\"tr_"+$unique_id+"\")'/>"
	   +"</td></td><td align='left' valign='top'>" + $do_no + "(" + $invoice_no + ")"
	   +"</td><td>"
	   + "<table width='727' border='1'></table>"
	   +"</td></tr>");

	//put into new list
	var search_exp=new RegExp('tr_'+$unique_id+',','i');
	if($("#txtdo_currentlist").val().search(search_exp)!=-1){
		$('#txtdo_removelist').val($("#txtdo_removelist").val().replace('tr_'+$unique_id+',',''));
	}else{
		$("#txtdo_newlist").val($("#txtdo_newlist").val()+'tr_'+$unique_id+',');
	}

	//Transfer DO info to Invoice List
	if($('#tr_' + $unique_id + '>td:last>table').length!=0){
		if ($('#tbl_doview').length!=0){
			var $tbl=$('#tr_' + $unique_id + '>td:last>table');
			$tbl.html($('#tbl_doview').html());
			$('#td_invoicetotal').html(
				Number(parseFloat($('#td_dototal').html().replace(',',''))
				+parseFloat($('#td_invoicetotal').html().replace(',',''))).toFixed(2));
			$('#td_invoicetotal2').html(
				Number(parseFloat($('#td_dototal').html().replace(',',''))
				+parseFloat($('#td_invoicetotal2').html().replace(',',''))).toFixed(2));
			
			$tbl.find('tr:first,tr:last').remove();
			$tbl.find('tr>td:eq(0)').width('324');
			$tbl.find('tr>td:eq(1)').width('98');
			$tbl.find('tr>td:eq(2)').width('129');
			$tbl.find('tr>td:eq(3)').width('149');
			$('#do_detail2').html('');
			$('#DO_List02 option:selected').remove();
		}
	}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}


function remove_element_do(id){
	
	var key=id.replace(/-x01-/g,' ').split('_');
	var do_no=key[1];
	var invoice_no=key[2];

	
    //Check For Remain Invoice
	var $key_count=0
	$('#' + id).parent().find('input[id="btndelete_do"]').each(function() {
		var $remove_key=$(this).parent().parent().attr('id');
		$remove_key=$remove_key.replace(/-x01-/g,' ').split('_');
		if ($remove_key[2]==invoice_no){
			$key_count+=1;
		}
	  });
	if ($key_count<=1){
		//Remove if invoice available in List
		if($('#lst_doinvoice option[text="'
			+invoice_no+'"]').length!=0){
			$('#lst_doinvoice option[text="'+invoice_no+'"]').remove();
		}
	}

	//var $tr=$('#' + id + '>td:last>table>tbody');
	var row_total=0;
	$('#' + id + '>td:last>table>tbody>tr').each(function() {
        $("td:last",this).each(function() {
		   row_total += parseFloat($(this).html().replace(',',''));
        }); 
    });
	
	//put into remove list
	var tmp=$('#txtdo_removelist').val();
	var search_exp=new RegExp(id+',','i');
	if($("#txtdo_currentlist").val().search(search_exp)!=-1){
		$('#txtdo_removelist').val(tmp+id+',');
	}else{
		$("#txtdo_newlist").val($("#txtdo_newlist").val().replace(id+',',''));
	}
	
	
	//reduce subtotal
	$('#td_invoicetotal').html(
				Number(parseFloat($('#td_invoicetotal').html().replace(',',''))-row_total).toFixed(2));
			$('#td_invoicetotal2').html(
				Number(parseFloat($('#td_invoicetotal2').html().replace(',',''))-row_total).toFixed(2));
	//Put back into DO List
	$('#DO_List02').append($('<option></option>').val('new').html(do_no)); //.attr('selected',true));
	//$('#lst_doinvoice').change(
	
	remove_element(id);
}

 function remove_element(id){
	$('#' + id).remove();
 }

function resetAllSelection(){
	$('#do_detail2').html('');
	$('#invoice_detail2').html('');
	$('#PO_List02').html('<option value="" selected>--Select PO--</option>');
	$('#DO_List02').html('<option value="" selected>--Select DO--</option>');
	$('#lst_doinvoice').html('<option value="" selected>--Select INVOICE--</option>');
}

 function validateInvoiceCriteria(){
	$('#do_detail2').html('');
	$('#invoice_detail2').html('');
	$('#DO_List02').html('<option value="" selected>--Select DO--</option>');
	$('#lst_doinvoice').html('<option value="" selected>--Select INVOICE--</option>');
	if($('#vendor_list').val()!='' && $('#PO_List02').val()!=''){
		Ajax_Request(invoice_detail2,'page=invoice&task=invoice_listdetail&param1='+ $('#vendor_list').val()+ '&param2='+ $('#PO_List02').val());

		Ajax_Request(lst_doinvoice,'page=invoice&task=po_listinvoice&param1='+ $('#vendor_list').val()+ '&param2='+ $('#PO_List02').val() +'&param3=True');

		Ajax_Request(DO_List02,'page=invoice&task=do_list&param1='+ $('#vendor_list').val()+ '&param2='+ $('#PO_List02').val() +'&param3=True');
	}
 }

 
 
 function PO_List(obj,param) {
	 //alert(obj.id);
	 $.ajax({
         url: 'custom_response.php?page=invoice&task=po_list&param1='+param,
         success: function(response) {
             // update status element
             $('#' + obj.id).html(response);
			 if(obj.id=='PO_List01'){
				$('#search_invoice').click();
			 }
		 },
		 error: function(xhr) {
			$('#' + obj.id).html(xhr.statusText);
		 }
     });
 }
 
 function Ajax_Request(obj,param) {
	 //alert(obj.id + ' ' + param );
	 //page=invoice&task=po_list&param1=xxx
	try{ 
		showPendingImage(obj);
	   }
	catch(err){}

	 $.ajax({
         url: 'custom_response.php?'+param,
         success: function(response) {
             // update status element
             HidePendingImage(obj)
			 $('#' + obj.id).html(response);
			 //alert(response);
         },
		 error: function(xhr) {
			HidePendingImage(obj)
			$('#' + obj.id).html(xhr.statusText);
		 }
     });
 }

	function ShowPendingImage(obj){
		$('#' + obj.id).html("<image src=bigrotation2.gif>Please Wait!</image>");
	}

	function HidePendingImage(obj){
		$('#' + obj.id).html("");
	}

	
	//Encodes data to Hex(base16) format
	function hexEncode(data){
		var b16_digits = '0123456789abcdef';
		var b16_map = new Array();
		for (var i=0; i<256; i++) {
			b16_map[i] = b16_digits.charAt(i >> 4) + b16_digits.charAt(i & 15);
		}
	
		var result = new Array();
		for (var i=0; i<data.length; i++) {
			result[i] = b16_map[data.charCodeAt(i)];
		}
	
		return result.join('');
	}

	//Decodes Hex(base16) formated data
	function hexDecode(data){
		var b16_digits = '0123456789abcdef';
		var b16_map = new Array();
		for (var i=0; i<256; i++) {
			b16_map[b16_digits.charAt(i >> 4) + b16_digits.charAt(i & 15)] = String.fromCharCode(i);
		}
		if (!data.match(/^[a-f0-9]*$/i)) return false;// return false if input data is not a valid Hex string
	
		if (data.length % 2) data = '0'+data;
		
		var result = new Array();
		var j=0;
		for (var i=0; i<data.length; i+=2) {
			result[j++] = b16_map[data.substr(i,2)];
		}

		return result.join('');
	}





 </script>



<?

/*

<select id="x" style="width:200px;">
   <option>one</option>
   <option>two</option>
 </select>
 <input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
 <input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>

</br>

  <select id="myselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
 </select>
 <input type="button" value="Get Value" onclick="alert($('#myselect').val())"/>
 <input type="button" value="Get Text Value" onclick="alert($('#myselect option:selected').text())"/>


</br>
</br>

<select id="Selection01" onchange="updateStatus()">
   <option value="1">PO 001</option>
   <option value="2">PO 002</option>
   <option value="3">PO 003</option>
   <option value="4">PO 004</option>
   <option value="5">PO 005</option>
 </select>

</br>
<select id="Selection02" onchange="alert($('#Selection02 option:selected').text())"/>
</select>

<div id=status></div>


*/
/*
echo "<pre>";
print_r($_SESSION);
echo "</pre>"; */
?>