<?php
$cs = Yii::app()->getClientScript();

$baseUrl = Yii::app()->baseUrl;

$livesite = Yii::app()->getBaseUrl(true) . "/";
?>

<?php $cs->registerScript('pins-notify', 'function notification(msg,type) {
            var opts = {
                title: "Messages",
                text: msg,
                hide: true,
                nonblock: false,
                nonblock_opacity: .2,
                animation: {
                    "effect_in": "drop",
            }
            };
            switch (type) {
              case "error":
              opts.title = "Error";
              opts.text = msg;
              opts.type = "error";
              opts.hide = false;
              break;
              case "info":
              opts.title = "Information";
              opts.text = msg;
              opts.type = "info";
              opts.hide = false;
              break;
              case "success":
              opts.title = "Success";
              opts.text = msg;
              opts.type = "success";
              opts.nonblock= true;
              break;
            }
            $.pnotify(opts);
          }
  ', CClientScript::POS_HEAD); ?>
        <?php $cs->registerScript("autocomplete-source-section", " function autoCompleteSource(request, response,url) {  console.log('auto-complete-common'); $.ajax({ type      : 'GET', data    : 'term='+ request.term, url       : url, dataType  : 'json', success : function(data) { response($.map( data, function( n, i ) { return { label :  n.label,  value : n.value,tble:n.tble,orderid:n.orderid, shipaddress : n.shipaddress,billaddress : n.billaddress,address : n.address, currency : n.currency,currency_id : n.currency_id, description : n.description,unit_id : n.unit_id,discount_id:n.discount_id,exchangerate: n.exchangerate,payment_term : n.payment_term,unit_name : n.unit_name,tax_code : n.tax_code ,time : n.time,service_item_name : n.service_item_name,total_qty : n.total_qty,allocated_qty : n.allocated_qty,cost : n.cost, warehouse : n.warehouse, product_id : n.product_id ,p_value : n.p_value ,rate :n.rate,total_q: n.total_q,customer_id:n.customer_id,customer_name:n.customer_name,file_id:n.file_id,sales_group:n.sales_group,contact_id:n.contact_id,contact_name:n.contact_name,part_number:n.part_number,supercede_id:n.supercede_id,supercede_name:n.supercede_name,supercede_des:n.supercede_des,supercede_unit_name:n.supercede_unit_name,supercede_unit_id:n.supercede_unit_id,other:n.other,pdt_loc_hiring:n.pdt_loc_hiring,customername:n.customername,serialno:n.serialno, free_qty:n.free_qty,quantity:n.quantity,tax_vat_percentage:n.tax_vat_percentage,tax_vat_amount:n.tax_vat_amount,net_amount:n.net_amount,actual_cost_rate:n.actual_cost_rate,addition_percentage:n.addition_percentage,deduction_percentage:n.deduction_percentage,addition_amount:n.addition_amount,deduction_amount:n.deduction_amount,amount:n.amount,msg:n.msg,default_hour:n.default_hour,purchasefrm:n.purchasefrm,cubicmeter:n.cubicmeter,selling_price:n.selling_price,unit_factor:n.unit_factor,bar_code:n.bar_code}  })); } }); } ", CClientScript::POS_HEAD); ?>
        <?php $cs->registerScript("isRowEmpty", " function isRowEmpty(tr) { var rowfilled=false; tr.find('td:gt(0)').each(function() { inpt    =   $(this).find('input').val(); if(typeof inpt !== 'undefined' && inpt!=='' && inpt!=='0.00') { rowfilled=true; return false;  } }); if(rowfilled) return (confirm('Do you want to remove this item?')); return true; } ", CClientScript::POS_HEAD); ?>
        <?php $cs->registerScript("addTableRow", " function addTableRow(jQtable) {
            $('.quotation-helper,.purchase-helper,.stock-helper').each(function(){ $(this).hide(); $(this).find('table').remove();});
            formId              =   jQtable.attr('id');
            formIdStarter       =   jQtable.attr('id').split(/_(.+)?/)[0];
            lastId = jQtable.find('tr:last input:first').attr('id');
            thenum = lastId.match(/\d+/g);
            newId = Number(thenum) + 1;
            var date = $('#PurchasingOrderStockItem_'+thenum+'_expected_delivery_date').val();
            var salegroup=$('#Quotes_sales_group').val();
             if($('.vis_hiring').length > 0 && formId == 'hiring_item_table'){
                newrow= jQtable.find('tr.vis_hiring:last').clone();
             }
             else{
                 newrow= jQtable.find('tr:last').clone();
             }
            //newrow= jQtable.find('tr:last').clone();
            newrow.find('label:first').html(newId+1);
            newrow.attr('class',newId);
            newrow.find('.hasDatepicker').removeClass('hasDatepicker');
            newrow.find('.datetimepicker').siblings().remove();
            newrow.find('.datetimepicker').datetimepicker( 'destroy' );
            newrow.find('div,input,textarea,checkbox,td,select,.errorMessage,a,span').each(function() {
                this.id= this.id.replace(/\d+/,newId);
               if(!$(this).is(':checkbox'))
                    this.value  = '';
                else
                    $(this).prop('checked', false);
                (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   '';});
            jQtable.append(newrow);
            if($('#div_previous_price_'+newId).length > 0){
                $('#div_previous_price_'+newId).html('');
            }
            if(salegroup!==undefined){
                if(salegroup == 2){
                    $('.cls_hiring').hide();
                    $('.cls_td_bill_type').show();
                    $('.cls_td_unit').hide();
                }
                else{
                    $('.hiring_li').hide();
                    $('.cls_hiring').show();
                    $('.cls_td_bill_type').hide();
                    $('.cls_td_unit').show();
                }
            }
            //autoCompletePO(formId,'po');//for productionorder
            $('#EmployeeSalary_'+newId+'_consider_for_leave_payment').val('Y');
            $('#remove_button_'+newId).show();
//                auto_complete2(formIdStarter,newId);
              $('#MaterialRequest_'+newId+'_status').val('N');
         //      $('#PurchasingEnquiryItem_'+newId+'_quantity').val(1);
         //      $('#PurchasingEnquiryItem_'+newId+'_quantity').val(1);
             $('#QuotesItem_'+newId+'_checked').prop('checked', true );
         //     $('#PurchasingRequisitionNonStockItem_'+newId+'_non_stock_item_quantity').val(1);
         //      $('#PurchasingRequisitionStockItem_'+newId+'_stock_item_quantity').val(1);
         //      $('#QuotesItem_'+newId+'_quantity').val(Number(1).toFixed(2));
               if($('#QuotesItem_'+newId+'_addition_percentage').length > 0){
                    $('#QuotesItem_'+newId+'_addition_percentage').val(0);
               }
               if($('#QuotesItem_'+newId+'_deduction_percentage').length > 0){
                    $('#QuotesItem_'+newId+'_deduction_percentage').val(0);
               }
               if($('#OrderItem_'+newId+'_addition_percentage').length > 0){
                    $('#OrderItem_'+newId+'_addition_percentage').val(0);
               }
               if($('#OrderItem_'+newId+'_deduction_percentage').length > 0){
                    $('#OrderItem_'+newId+'_deduction_percentage').val(0);
               }
               if($('#OrderItem_'+newId+'_addition_amount').length > 0){
                    $('#OrderItem_'+newId+'_addition_amount').val('0.00');
               }
               if($('#OrderItem_'+newId+'_deduction_amount').length > 0){
                    $('#OrderItem_'+newId+'_deduction_amount').val('0.00');
               }
               if($('#OrderItem_'+newId+'_expected_delivery_date').length > 0){
                    var previous_date = $('#OrderItem_'+thenum+'_expected_delivery_date').val();
                    $('#OrderItem_'+newId+'_expected_delivery_date').val(previous_date);
               }
       //      $('#OrderItem_'+newId+'_quantity').val(Number(1).toFixed(2));
             $('#FileTasks_'+newId+'_start_date').datetimepicker({format: 'DD/MM/YYYY'});
             $('#FileTaskItems_'+newId+'_task_date').datetimepicker({format: 'DD/MM/YYYY'});
             $('#FileTaskItems_'+newId+'_actual_date').datetimepicker({format: 'DD/MM/YYYY'});
             $('#PurchasingOrderStockItem_'+newId+'_expected_delivery_date').datetimepicker({format: 'DD/MM/YYYY'}).val(date);
             $('#EmployeeSalary_'+newId+'_consider_for_leave_payment').val('N');
             $('#PurchasingOrderStockItem_'+newId+'_stock_item_tolerance').val(0);
             //$('#OrderItem_'+newId+'_expected_delivery_date').datetimepicker({format: 'DD/MM/YYYY'}).val(date);
             $('#EmployeeInoutDocument_'+newId+'_in_out_date').datetimepicker({format: 'DD/MM/YYYY'});
            $('#EmployeeSalary_'+newId+'_valid_from').datetimepicker({format: 'DD/MM/YYYY'});
            $('#EmployeeSalary_'+newId+'_valid_to').datetimepicker({format: 'DD/MM/YYYY'});
            $('#EmployeeSalary_'+newId+'_valid_from').addClass('salarydate');
            $('#EmployeeAsset_'+newId+'_asset_date_issue').datetimepicker({format: 'DD/MM/YYYY'}).val(date);
            $('#EmployeeAsset_'+newId+'_asset_date_return').datetimepicker({format: 'DD/MM/YYYY'}).val(date);
             var default_warehouseid  = $('#layout_default_warehouse_id').val();
             $('#InventoryGoodsReceiptItem_'+newId+'_factor').val(1);
             $('#InventoryGoodsIssueItem_'+newId+'_factor').val(1);
             $('#InventoryDirectTransferItem_'+newId+'_factor').val(1);
             $('#InventoryIndirectTransferItem_'+newId+'_factor').val(1);
             $('#QuotesItem_'+newId+'_product_name').focus();
            var table_length=$('#salary_item_table').find('tr:gt(0)').length;
            for(i=0;i<=table_length;i++){
                var salary_type = $('#EmployeeSalary_'+i+'_salary_type').val();
                if((parseFloat(salary_type)>0)){
                    $('#EmployeeSalary_'+newId+'_salary_type option[value='+salary_type+']').remove();
                }
            }
    }", CClientScript::POS_HEAD); ?>
        <?php
        $cs->registerScript("autoCompleteEmployee", "function autoCompleteEmployee(field_id,frm){
        var arr_fields= field_id.split('_');
        var model_name= arr_fields[0];
        var row_field_name 	= arr_fields[1];
        var url = '" . Yii::app()->createUrl('employee/SearchEmployee') . "'+'&frm='+frm;
        $('#'+field_id).autocomplete({
            minLength   : 1,
            source      : function (request, response) { autoCompleteSource(request, response,url) },
            focus       : function( event, ui ) { $(this).val((ui.item.label).split(':')[1]); return false;},
            select      : function( event, ui ) {
                event.preventDefault();
                trigger_target_id  	=   $(event.target).attr('id');
                var emp_id=ui.item.value;
                var emp_name=ui.item.label;
                $('#'+model_name+'_employee_id').val(emp_id);
                if(model_name=='EmployeeLeaveDetail'){
                    masterleavetype(emp_id);
                }
                if(model_name=='EmployeeLeaveEncashment'){
                    masterencashmentleave(emp_id);
                }
            }
        })
    }", CClientScript::POS_HEAD);
        $cs->registerScript("masterleavetype", "function masterleavetype(id) {
        jQuery.ajax({
            'dataType':'json',
             'data': {'id':id}  ,
             'type':'post',
             'url': '" . Yii::app()->createUrl('leave/masterleavetype') . "',
             'cache': false,
              'success': function(data) {
               $('#emp_leave_1').html(data.leavetype);
               $('#EmployeeLeaveDetail_function_type').val(data.functiontype);
               $('#EmployeeLeaveDetail_last_approved_level').val(data.maxlevel);
             },
             'beforeSend':function(){
                 $('#loader').show();
             },
             'complete':function(){
                 $('#loader').hide();
             }
        });
    };", CClientScript::POS_HEAD);
        $cs->registerScript("masterencashmentleave", "function masterencashmentleave(id) {
        jQuery.ajax({
            'dataType':'json',
             'data': {'id':id}  ,
             'type':'post',
             'url': '" . Yii::app()->createUrl('leave/masterencashmentleave') . "',
             'cache': false,
              'success': function(data) {
               $('#enc_leave_1').html(data.leavetype);
             }
        });
    };", CClientScript::POS_HEAD);
        $cs->registerScript("removeTableRow", " function removeTableRow(jQtable,evt) {
        formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
        var num_rows    =   jQtable.find('tr:gt(0)').length;
        if(num_rows>1){
        var tr  =   $(evt).parent().parent();
        if(isRowEmpty(tr)) {
            amount = $(evt).parents('tr').find('[id$=\"_amount\"]').val();
            total =   $('.'+formIdStarter+'_total .total').text();
            total =   (Number(total)-Number(amount)).toFixed(2);
            $('.'+formIdStarter+'_total .total').text(total)
            gd_total =   $('.'+formIdStarter+'_grand_total .grandtotal').text();
            gd_total =   (Number(gd_total)-Number(amount)).toFixed(2);
            $('.'+formIdStarter+'_grand_total .grandtotal').text(gd_total);
            $(evt).parents('tr').remove();
            var i=0;
            jQtable.find('tr:gt(0)').each(function() { $(this).find('input,select,textarea,.errorMessage').each(function(){
            old_id   =   $(this).attr('id');
            new_id   =   old_id.replace(/\d+/,i);
            $(this).attr('id',new_id);
            old_name =   $(this).attr('name');
            if(old_name!==undefined) {
                new_name =   old_name.replace(/\d+/,i);
                $(this).attr('name',new_name);} });
                $(this).find('td:first label').html(++i); }); }
                //adjustPopup();
                //calculateemployeesalaryamount();
        }else
        alert('Atleast one item needed here');
    }", CClientScript::POS_HEAD);
        $cs->registerScript("autoCompleteCustomer", "function autoCompleteCustomer(field_id,frm){
        var url = '" . Yii::app()->createUrl('customer/GetCustomerDetails') . "'+'&frm='+frm;
        $('#'+field_id).autocomplete({
            minLength   : 1,
            source      : function (request, response) { autoCompleteSource(request, response,url) },
            focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},
            select          : function( event, ui ) {
            event.preventDefault();
            trigger_target_id  	=   $(event.target).attr('id');
                            var customer_id=ui.item.value;
                      //      $('#'+field_id+'').val(customer_id);
                    $('#InventoryGoodsIssue_customer_id').val(customer_id);
                    $('#InventoryGoodsReceipt_customer_id').val(customer_id);
                    $('#auto_customer_id').val(customer_id);
            }
        })
    }", CClientScript::POS_HEAD);
        $cs->registerScript("autoCompleteVendor", "function autoCompleteVendor(field_id,frm){
        var url = '" . Yii::app()->createUrl('vendor/Getvendor') . "'+'&frm='+frm;
        $('#'+field_id).autocomplete({
            minLength   : 1,
            source      : function (request, response) { autoCompleteSource(request, response,url) },
            focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},
            select          : function( event, ui ) {
            event.preventDefault();
            trigger_target_id  	=   $(event.target).attr('id');
            var customer_id=ui.item.value;
    //      $('#'+field_id+'').val(customer_id);
            $('#auto_customer_id').val(customer_id);
        }
        })
    }", CClientScript::POS_HEAD);
        $cs->registerScript("autoCompleteCustomerWithContact", "function autoCompleteCustomerWithContact(field_id,frm,div_id,contact_field_id){
        var arr_field_id = field_id.split('_');
        var model_name   =  arr_field_id[0];
        var url = '" . Yii::app()->createUrl('customer/Getcustomer') . "'+'&frm='+frm;
        $('#'+field_id).autocomplete({
        minLength   : 1,
        source      : function (request, response) { autoCompleteSource(request, response,url) },
        focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},
        select      : function( event, ui ) {
        event.preventDefault();
        trigger_target_id  	=   $(event.target).attr('id');
            var crm_user_id=ui.item.value;
            var currency=ui.item.currency;
            var currency_id=ui.item.currency_id;
            $('#'+model_name+'_customer_id').val(crm_user_id);
            jQuery.ajax({
                'data' :{'id':crm_user_id,'model_name':model_name,'contact_field_id':contact_field_id},
                'dataType' : 'json',
                'type':'post',
                'url': '" . Yii::app()->createUrl('customercontact/getcustomercontactdetails') . "',
                'success': function(data) {
                  $('#'+div_id).html(data.dt);
                }
            });
        }
        })
    }", CClientScript::POS_HEAD);
        $cs->registerScript("capitalize-first-letter", " function capitaliseFirstLetter(string) {console.log('letter-capitalise'); return string.charAt(0).toUpperCase() + string.slice(1); } ", CClientScript::POS_HEAD);
        $cs->registerScript("autocomplete-product2", " function auto_complete2(formIdStarter,newId){
        var url = '';
        (formIdStarter=='order' || formIdStarter=='quotation' )? url  =  '" . Yii::app()->createUrl('quotation/SearchProductForOrder') . "':url = '" . Yii::app()->createUrl('quotation/SearchProduct') . "';
       // var url = '" . Yii::app()->createUrl('quotation/SearchProduct') . "';
        model   =   capitaliseFirstLetter(formIdStarter);
        element =   $('#'+model+'Item_'+newId+'_product_name');
        element.autocomplete({
            minLength   : 1,
            source      : function (request, response) { autoCompleteSource(request, response,url) },
            focus       :function( event, ui ) { $(this).val( (ui.item.label).split(':')[0] ); return false;},
           /* change : function(event,ui){
                if(formIdStarter   !== 'purchasingRequisition' && formIdStarter   !== 'purchasingEnquiry')
                    $(this).val(ui.item ? (ui.item.label).split(':')[0] : '');


            },*/
            select          : function( event, ui ) {
            event.preventDefault();
            trigger_target_id  =   $(event.target).attr('id');
            var product_id  =   ui.item.value;
            id_product_name =   $(event.target).attr('id');
            var selected_element_id = id_product_name.match(/\d+/g);
             company_id=$('#'+id_product_name).parents('.popup_inner_element,.popup_inner_element0').find('[id $=_company_id]').val();
            jQuery.ajax({
                'type': 'post',
                'data': 'product_id='+product_id+'&company_id='+company_id,
                'dataType': 'json',
                'url': '" . Yii::app()->createUrl('quotation/getProduct') . "',
                'cache': false,
                'success': function(data) {
                var rate = data.rate;
                var xchangerate = 1;
                var flag=1;
                if(model=='PurchasingOrder')
                    rate=0;
                if(rate==undefined && $('#'+model+'Item_'+selected_element_id+'_rate').length > 0)
                {
                    $('#'+model+'Item_'+selected_element_id+'_product_name').val('');
                    flag=0;
                    alert('Please select a customer from general tab');
                }
                if($('#'+model+'_exchange_rate').length > 0 && Number($('#'+model+'_exchange_rate').val())==0)
                {
                    $('#'+model+'Item_'+selected_element_id+'_product_name').val('');
                    if(flag!=0) alert('Please select a currency from general tab');//already showed a message
                    flag=0;
                }
                else
                    xchangerate=Number($('#'+model+'_exchange_rate').val());
                if(flag) {
                    $('#'+model+'Item_'+selected_element_id+'_product_id').val(data.store.id);
                    $('#'+model+'Item_'+selected_element_id+'_product_name').val(data.store.part_number);
                    $('#'+model+'Item_'+selected_element_id+'_description').val(data.store.description);
                    if(data.unit!=null){
                        $('#'+model+'Item_'+selected_element_id+'_unit').val(data.unit.symbol);
                    }else {
                        $('#'+model+'Item_'+selected_element_id+'_unit').val('ea');
                    }
                    $('#'+model+'Item_'+selected_element_id+'_quantity').val(1);
                    $('#'+model+'Item_'+selected_element_id+'_net_amount').val(Number(data.rate).toFixed(2));
                    $('#'+model+'Item_'+selected_element_id+'_amount').val(Number(data.rate).toFixed(2));
                    if(Number(rate)>0 && model!='PurchasingOrder')
                        $('#'+model+'Item_'+selected_element_id+'_rate').attr('readonly','readonly');
                    else
                        $('#'+model+'Item_'+selected_element_id+'_rate').attr('readonly',false);
                    // $('#'+model+'Item_'+selected_element_id+'_rate').val((Number(rate)/Number(xchangerate)).toFixed(3));
                    $('#'+model+'Item_'+selected_element_id+'_rate').val((Number(rate)/Number(xchangerate)).toFixed(2));
                    if(data.tax)
                     $('#'+model+'Item_'+selected_element_id+'_addition_percentage').val(data.tax.percentage);
                     if(formIdStarter   !== 'purchasingRequisition' && formIdStarter   !== 'purchasingEnquiry' && formIdStarter   !== 'productionBillofmaterial')
                        calculateValues($('#'+formIdStarter+'_item_table'));
                    if(jQuery(element).parents('table').find('.product-search').filter(function(){ return !$(this).val(); }).length != 1)
                        addTableRow($('#'+formIdStarter+'_item_table'));
                    }
                    }
                });
            }
        });
    }", CClientScript::POS_HEAD);
        ?>
        <?php
        $cs->registerScript("removeExtrasRow", " function removeExtrasRow(jQtable,evt) {
        formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
        var num_rows    =   jQtable.find('tr').length;
        if(jQtable.attr('id')=='invoice_final_add_table'||jQtable.attr('id')=='invoice_final_ded_table'){
            extra_val = $(evt).parents('tr').find('input:eq(3)').val();
        }
        else{
            extra_val = $(evt).parents('tr').find('input:eq(1)').val();
        }
        gd_total =   $('.'+formIdStarter+'_grand_total .grandtotal').text();
        gd_total=gd_total.replace(/,/g , '');
        if(jQtable.attr('id')==='purchasingOrder_final_add_table' || jQtable.attr('id')==='quotes_final_add_table' || jQtable.attr('id')==='order_final_add_table'|| jQtable.attr('id')=='invoice_final_add_table'){
            gd_total =   (Number(gd_total)-Number(extra_val)).toFixed(2);
        }
        else gd_total =   (Number(gd_total)+Number(extra_val)).toFixed(2);
        $('.'+formIdStarter+'_grand_total .grandtotal').text(gd_total);
        if(num_rows>1) $(evt).parents('tr').remove();
        else $(evt).parents('tr').find('input').val('');
    }", CClientScript::POS_HEAD);
        $cs->registerScript("isNumberKey", " function isNumberKey(evt,num=0) {
        console.log('is-number-key');
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        /*added by jisha for checking already hav decimal---start----*/
        var non_decimal_flag=true;
        if(charCode==46){
            if(num.includes('.')){
                non_decimal_flag=false;
            }
        }
        /*added by jisha for checking already decimal --end--*/
        if ((charCode > 31 && (charCode < 48 || charCode > 57) && charCode !== 46 && charCode !== 37 && charCode !== 45  && charCode !== 8 && charCode !== 35) ||!(non_decimal_flag)) {
            return false;
        }
        return true;
    }", CClientScript::POS_HEAD);
        $cs->registerScript("isNumber", " function isNumber(n) { console.log('is-number'); return !isNaN(parseFloat(n)) && isFinite(n); } ", CClientScript::POS_HEAD);
        ?>
        <?php
        $cs->registerScript("isPositiveNumber", " function isPositiveNumber(event) {
            if (event.which != 8 && event.which != 0 &&(event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        } ", CClientScript::POS_HEAD);
        ?>
        <?php
        //8-backspace,49-0,57-9
        $cs->registerScript("isPositiveInteger", " function isPositiveInteger(event) {
            if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
            console.log('is-positive_integer');
        } ", CClientScript::POS_HEAD);
        ?>
        <?php $cs->registerScript("calculateExtra", " function calculateExtra(jQtable,total) {
        var temp_value  =   0;
    jQtable.find('tr').each(function(){
        var temp = null;
        temp  =   $(this).find('[id $=_particular_value]').val();
        count = temp.match(/%/g);
        temp   =   temp.replace(/%/,'');
        if(isNumber(temp))
            temp  =   (count!==null && count.length>0) ? (Number(total)*(Number(temp)/100)) : temp;
        $(this).find('[id $=_calculated_value]').val(Number(temp).toFixed(2));
        temp_value    =   Number(temp_value) + Number(temp);
    });
        return temp_value;
    } ", CClientScript::POS_HEAD);
        ?>
        <?php
        $cs->registerScript("calculateValues", " function calculateValues(jQtable,frm) {
        $('.quotation-helper,.purchase-helper,.stock-helper').each(function(){ $(this).hide(); $(this).find('table').remove();});
            formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
            var count,qty,rate,amount,addition_value,deduction_value,net;
            var other_additions = 0;
            var other_deductions = 0;
            var total   =   0;
            var grand_total =   0;
            var total_vat_amount	= 0;
            jQtable.find('tr:gt(0)').each(function() {
                net = 0;
                qty =   $(this).find('[id $=_quantity]').val();
               rate =   $(this).find('[id $=_rate]').val();
              // var ch = $(this).find('[id $=_checked]').val();
                amount  =   (Number(qty)*Number(rate)).toFixed(2);
                if(formIdStarter!='purchasingOrder' && formIdStarter !='productionGoodsReceipt')
                {
                    addition_value  =   $(this).find('[id $=_addition_percentage]').val();
                    deduction_value  =   $(this).find('[id $=_deduction_percentage]').val();
                    if(addition_value!=undefined)
                    {
                     count = addition_value.match(/%/g);
                     addition_value   =   addition_value.replace(/%/,'');
                     var value = Number(addition_value)/100;
                    }
                    if(isNumber(addition_value))
                        addition_value  =   (count!==null && count.length>0) ? (amount*value) : addition_value;
                    if(deduction_value!=undefined)
                    {
                        count = deduction_value.match(/%/g);
                        deduction_value   =   deduction_value.replace(/%/,'');
                        var value = Number(deduction_value)/100;
                    }
                    if(isNumber(deduction_value))
                        deduction_value  =  (count!==null && count.length>0) ? (amount*value) : deduction_value;
                    net =   Number(addition_value) - Number(deduction_value);
                }
                net =   (Number(net)+Number(amount)).toFixed(2);
                if(net != 0){
                    total   =   Number(total)+Number(net);
                }
                else{
                    total   =   Number(total);
                }
                $(this).find('[id $=_amount]').val(Number(amount).toFixed(2));
                if($(this).find('[id $=_tax_vat_percentage]').length > 0)
                {
                 tax_percentage = $(this).find('[id $=_tax_vat_percentage]').val();
                     tax_amount = (net * tax_percentage) / 100;
                                 $(this).find('[id $=_tax_vat_amount]').val(Number(tax_amount).toFixed(2));
                     total_vat_amount+=tax_amount;
                }
                $(this).find('[id $=_addition_amount]').val(Number(addition_value).toFixed(2));
                $(this).find('[id $=_deduction_amount]').val(Number(deduction_value).toFixed(2));
                $(this).find('[id $=_net_amount]').val(Number(net).toFixed(2));
            });
        other_additions    =   calculateExtra($('#'+formIdStarter+'_final_add_table'),total);
        other_deductions  =    calculateExtra($('#'+formIdStarter+'_final_ded_table'),total);
        grand_total =   Number(total)   +   Number(other_additions);
        grand_total -=  Number(other_deductions);
        if($('.'+formIdStarter+'_grand_total .vat_total_val').length > 0){
            $('.'+formIdStarter+'_grand_total .vat_total_val').text(Number(total_vat_amount).toFixed(2));
            grand_total = parseFloat(grand_total) + parseFloat(total_vat_amount);
        }
        if(other_deductions > total && frm!=''){
            $('#'+frm).val('');
            calculateValues(jQtable,frm);
        }else{
            $('.'+formIdStarter+'_total .total').html(Number(total).toFixed(2));
            $('.'+formIdStarter+'_grand_total .grandtotal').text(Number(grand_total).toFixed(2));
            $('#grnd_total_id').val(Number(grand_total).toFixed(2));
        }
    }", CClientScript::POS_HEAD);
        $cs->registerScript("checkall", "function checkall(jQtable){
        $('#ckbCheckAll').click(function () {
            $('.checkBoxClass').prop('checked', $(this).prop('checked'));
            $('.quotation-helper,.purchase-helper,.stock-helper').each(function(){ $(this).hide(); $(this).find('table').remove();});
            formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
            var count,qty,rate,amount,addition_value,deduction_value,net;
            var other_additions = 0;
            var other_deductions = 0;
            var total   =   0;
            var grand_total =   0;
            jQtable.find('tr:gt(0)').each(function() {
                net = 0;
                qty =   $(this).find('[id $=_quantity]').val();
               rate =   $(this).find('[id $=_rate]').val();
              // var ch = $(this).find('[id $=_checked]').val();
                amount  =   (Number(qty)*Number(rate)).toFixed(2);
                if(formIdStarter!='purchasingOrder' && formIdStarter !='productionGoodsReceipt')
                {
                    addition_value  =   $(this).find('[id $=_addition_percentage]').val();
                    deduction_value  =   $(this).find('[id $=_deduction_percentage]').val();
                    if(addition_value!=undefined)
                    {
                     count = addition_value.match(/%/g);
                     addition_value   =   addition_value.replace(/%/,'');
                     var value = Number(addition_value)/100;
                    }
                    if(isNumber(addition_value))
                        addition_value  =   (count!==null && count.length>0) ? (amount*value) : addition_value;
                    if(deduction_value!=undefined)
                    {
                        count = deduction_value.match(/%/g);
                        deduction_value   =   deduction_value.replace(/%/,'');
                        var value = Number(deduction_value)/100;
                    }
                    if(isNumber(deduction_value))
                        deduction_value  =  (count!==null && count.length>0) ? (amount*value) : deduction_value;
                    net =   Number(addition_value) - Number(deduction_value);
                }
                net =   (Number(net)+Number(amount)).toFixed(2);
                if(net != 0){
                    total   =   Number(total)+Number(net);
                }
                else{
                    total   =   Number(total);
                }
                $(this).find('[id $=_amount]').val(Number(amount).toFixed(2));
                $(this).find('[id $=_addition_amount]').val(Number(addition_value).toFixed(2));
                $(this).find('[id $=_deduction_amount]').val(Number(deduction_value).toFixed(2));
                $(this).find('[id $=_net_amount]').val(Number(net).toFixed(2));
            });
            other_additions    =   calculateExtra($('#'+formIdStarter+'_final_add_table'),total);
            other_deductions  =    calculateExtra($('#'+formIdStarter+'_final_ded_table'),total);
            grand_total =   Number(total)   +   Number(other_additions);
            grand_total -=  Number(other_deductions);
            if( $('.checkBoxClass').prop('checked') == true){
                $('.'+formIdStarter+'_total .total').html(Number(total).toFixed(2));
                $('.'+formIdStarter+'_grand_total .grandtotal').text(Number(grand_total).toFixed(2));
                $('#grnd_total_id').val(Number(grand_total).toFixed(2));
            }
            else if($('.checkBoxClass').prop('checked') == false){
                 $('.'+formIdStarter+'_total .total').html('0.00');
                $('.'+formIdStarter+'_grand_total .grandtotal').text('0.00');
                $('#grnd_total_id').val(0);
            }
        })
    }", CClientScript::POS_HEAD);
        $cs->registerScript("AddMaster", "function AddMaster(from,type){
            if(type == 'industry'){
                var url = '" . Yii::app()->createUrl('industry/directadd') . "';
                var name = $('#industry_name').val();
                var data = {'from':from,'name':name};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'country'){
                var url = '" . Yii::app()->createUrl('country/directadd') . "';
                var name = $('#country_name').val();
                var code = $('#country_code').val();
                var data = {'from':from,'name':name,'code':code};
                if(name == '' || code == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'paymentterm'){
                var url = '" . Yii::app()->createUrl('paymentterms/directadd') . "';
                var code = $('#paymentterm_code').val();
                var term = $('#paymentterm_term').val();
                var days = $('#paymentterm_days').val();
                var data = {'from':from,'term':term,'days':days,'code':code};
                if(term == '' || days == '' || code == ''){
                   alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'currency'){
                var url = '" . Yii::app()->createUrl('currency/directadd') . "';
                var name = $('#currency_name').val();
                var code = $('#currency_code').val();
                var rate = $('#currency_rate').val();
                var data = {'from':from,'name':name,'code':code,'rate':rate};
                if(name == '' || code == '' || rate == ''){
                   alert('Please Fill All Fields!');
                   return false;
                }
            }
             if(type == 'salesgroup'){
                var url = '" . Yii::app()->createUrl('salesgroup/directadd') . "';
                var name = $('#salesgroup_name').val();
                var data = {'from':from,'name':name};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'shipping'){
                var url = '" . Yii::app()->createUrl('shippingmethod/directadd') . "';
                var via = $('#via').val();
                var dec = $('#description').val();
                var data = {'from':from,'via':via,'dec':dec};
                if(via == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'probability'){
                var url = '" . Yii::app()->createUrl('probability/directadd') . "';
                var name = $('#probability').val();
                var data = {'from':from,'name':name};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'phase'){
               var url = '" . Yii::app()->createUrl('workshop/project/addPhase') . "';
                var name = $('#phase_name').val();
                var projectid = $('#WsProject_id').val();
                var data = {'from':from,'name':name,'projectid':projectid};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }else{
                    $('#phase_name').val('');
                }

            }
            if(type == 'generic'){
                var url = '" . Yii::app()->createUrl('generic/directadd') . "';
                var name = $('#generic_name').val();
                var des = $('#generic_des').val();
                var data = {'from':from,'name':name,'des':des};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'brand'){
                var url = '" . Yii::app()->createUrl('brand/directadd') . "';
                var name = $('#brand_name').val();
                var des = $('#brand_des').val();
                var auto_generated_no = $('#brand_auto_generated_no').val();
                var data = {'from':from,'name':name,'des':des,'auto_generated_no':auto_generated_no};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'unit'){
                var url = '" . Yii::app()->createUrl('unit/directadd') . "';
                var name = $('#unit_name').val();
                var symbol = $('#unit_symbol').val();
                var unit_type = $('#unit_type').val();
                var data = {'from':from,'name':name,'symbol':symbol,'type':unit_type};
                if(name == '' || symbol == '' || type == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'tax'){
                var url = '" . Yii::app()->createUrl('unit/directaddtax') . "';
                var name = $('#tax_name').val();
                var percent = $('#tax_percent').val();
                var data = {'from':from,'name':name,'percent':percent};
                if(name == '' || percent == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
             if(type == 'tax_1'){
                var url = '" . Yii::app()->createUrl('unit/directaddtax') . "';
                var name = $('#tax_name_1').val();
                var percent = $('#tax_percent_1').val();
                var data = {'from':from,'name':name,'percent':percent};
                if(name == '' || percent == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
             if(type == 'tax_2'){
                var url = '" . Yii::app()->createUrl('unit/directaddtax') . "';
                var name = $('#tax_name_2').val();
                var percent = $('#tax_percent_2').val();
                var data = {'from':from,'name':name,'percent':percent};
                if(name == '' || percent == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
             if(type == 'tax_3'){
                var url = '" . Yii::app()->createUrl('unit/directaddtax') . "';
                var name = $('#tax_name_3').val();
                var percent = $('#tax_percent_3').val();
                var data = {'from':from,'name':name,'percent':percent};
                if(name == '' || percent == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }
            if(type == 'warehouse'){
                var url = '" . Yii::app()->createUrl('warehouse/directadd') . "';
                var name = $('#warehouse_name').val();
                var data = {'from':from,'name':name};
                if(name == ''){
                    alert('Please Fill All Fields!');
                   return false;
                }
            }

            if(type == 'rack'){

                var url = '" . Yii::app()->createUrl('rack/directadd') . "';

                var name = $('#rack_name').val();

                var data = {'from':from,'name':name};

                if(name == ''){

                    alert('Please Fill All Fields!');

                   return false;

                }

            }

            if(type == 'bin'){

                var url = '" . Yii::app()->createUrl('bin/directadd') . "';

                var name = $('#bin_name').val();

                var rack = $('#rack_id').val();

                var data = {'from':from,'name':name,'rack':rack};

                if(name == ''){

                    alert('Please Fill All Fields!');

                   return false;

                }

            }

            if(type == 'bank'){

                var url = '" . Yii::app()->createUrl('bank/directadd') . "';

                var name = $('#bank_name').val();

                var data = {'from':from,'name':name};

                if(name == ''){

                    alert('Please Fill All Fields!');

                   return false;

                }

            }

            if(type == 'tracking'){

                var url = '" . Yii::app()->createUrl('Materialreceipt/updateTrackingno') . "';

                var tracking_no = $('#tracking_no').val();

                var trackupdateid  = $('#trackupdateid').val();

                var data = {'from':from,'tracking_no':tracking_no,'trackupdateid':trackupdateid};

                if(tracking_no == ''){

                    alert('Please Fill All Fields!');

                   return false;

                }

            }

            jQuery.ajax({

                'dataType':'json',

                'data': data,

                'type':'post',

                'url': url,

                'cache': false,

                'success': function(data) {

                       if(data.status == 'success'){

                            if(from == 'customer' && type=='industry'){

                                $('#customer_industry_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'customer' && type =='country'){

                                $('#customer_country_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'customer' && type =='paymentterm'){

                                $('#customer_paymentterm_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'customer' && type =='currency'){

                                $('#customer_currency_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'lead' && type =='currency'){

                                $('#lead_currency_div').html(data.drop);

                                $('#MasCurrency_exchange_rate').val(data.rate);

                                $('.cst-btn.expand').click();



                            }

                            if(from == 'lead' && type =='salesgroup'){

                                $('#lead_salesgroup_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'quote' && type =='paymentterm'){

                                $('#quote_paymentterm_div').html(data.drop);

                                $('.cst-btn.expand').click();



                            }

                            if(from == 'quote' && type =='currency'){

                                $('#quote_currency_div').html(data.drop);

                                $('#Quotes_exchange_rate').val(data.rate);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'quote' && type =='salesgroup'){

                                $('#quote_salesgroup_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'quote' && type =='shipping'){

                                $('#quote_shipping_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'quote' && type =='probability'){

                                $('#quote_probalility_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'order' && type =='salesgroup'){

                                $('#order_salesgroup_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'order' && type =='currency'){

                                $('#order_currency_div').html(data.drop);

                                $('#Order_exchange_rate').val(data.rate);

                                $('.cst-btn.expand').click();

                            }
                             if(from == 'projectenquiry' && type =='phase'){
                                $('#phase_div').html(data.drop);
                                $('.cst-btn.expand').click();
                            }
                            if(from == 'order' && type =='paymentterm'){

                                $('#order_paymentterm_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'invoice' && type =='salesgroup'){

                                $('#invoice_salesgroup_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'invoice' && type =='currency'){

                                $('#invoice_currency_div').html(data.drop);

                                $('#Invoice_exchange_rate').val(data.rate);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'invoice' && type =='paymentterm'){

                                $('#invoice_paymentterm_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='generic'){

                                $('#inventory_generic_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='brand'){

                                $('#brand_name').val('');

                                $('#brand_auto_generated_no').val(data.auto_no);

                                $('#brand_des').val('');

                                $('#inventory_brand_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='unit'){

                                $('#inventory_unitz_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='tax'){

                                $('#inventory_tax_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory_1' && type =='tax_1'){

                                $('#inventory_tax_1_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory_2' && type =='tax_2'){

                                $('#inventory_tax_2_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory_3' && type =='tax_3'){

                                $('#inventory_tax_3_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='warehouse'){

                                $('#inventory_warehouse_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='rack'){

                                $('#inventory_rack_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'inventory' && type =='bin'){

                                $('#inventory_bin_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'vendor' && type =='country'){

                                $('#vendor_country_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'vendor' && type =='paymentterm'){

                                $('#vendor_paymentterm_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'vendor' && type =='currency'){

                                $('#vendor_currency_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'vendor' && type =='bank'){

                                $('#vendor_bank_div').html(data.drop);

                                $('.cst-btn.expand').click();

                            }

                            if(from == 'materialreceipt' && type=='tracking'){

                                $('.cst-btn.expand').click();

                                $('#PurchasingMaterialreceipt_tracking_no').val(data.tracking_no);

                            }

                       }else{

                            $.each(data, function(key, val) {

                                     t8.error(''+val+'');

                            });

                       }

                 }

           });

        }", CClientScript::POS_HEAD);

        $cs->registerScript("getallvendors_and_customers", "function getallvendors_and_customers(field_id){

        var url = '" . Yii::app()->createUrl('finance/getallcustomersandvendors') . "';

        $('#'+field_id).autocomplete({

             minLength   : 1,

             source      : function (request, response) { autoCompleteSource(request, response,url) },

             focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},

             select          : function( event, ui ) {

                  event.preventDefault();

                  trigger_target_id  	=   $(event.target).attr('id');

                  $('#FinOutstandingInvoices_customer_vendor_id').val(ui.item.value);

                  $('#FinOutstandingInvoices_customer_vendor_type').val(ui.item.other);

                }

            })

    }", CClientScript::POS_HEAD);
        ?>

        <?php
        $cs->registerScript("moveRows", '$(document).ready(function(){

     $("body").on("click",".up",function(){

        var thisRow = $(this).closest("tr");

        var prevRow = thisRow.prev();

        if (prevRow.length) {

            prevRow.before(thisRow);

        }

    });

    $("body").on("click",".down",function(){

        var thisRow = $(this).closest("tr");

        var nextRow = thisRow.next();

        if (nextRow.length) {

            nextRow.after(thisRow);

        }

    });

    /*jQuery("body").on("click",".up,.down",function(){

        var current_row = $(this).parents("tr:first");

        if ($(this).is(".up")) {

            if(current_row.prev().find("th").length==0){ //If its Title row

                row_need_to_replace    =   current_row.prev();

            }

        } else {

            row_need_to_replace    =   current_row.next();

        }

        if(row_need_to_replace.find(":input").length>0)

        {

            var i=0;

            current_row.find("input,textarea").each(function(){

                input_need_to_replace=row_need_to_replace.find(":input:eq("+i+")");

                temp   =   input_need_to_replace.val();

                input_need_to_replace.val($(this).val());

                $(this).val(temp);

                this_readonly=$(this).is(\'[readonly]\')

                input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');

                $(this).attr(\'readonly\',input_need_to_replace_readonly);

                input_need_to_replace.attr(\'readonly\',this_readonly);

                i++;

            });

        }

    });*/

});', CClientScript::POS_READY);

        $cs->registerScript("insRows", '$(document).ready(function(){

    jQuery("body").on("click",".left",function(){

//    var current_row = $(this).closest("table").children("tr:last");

         var jQtable=$(\'#quotes_item_table\');

        $(".quotation-helper,.purchase-helper,.stock-helper").each(function(){

        $(this).hide();

        $(this).find("table").remove();

        });

        formIdStarter   =   jQtable.attr("id").split(/_(.+)?/)[0];

        lastId = jQtable.find("tr:last input:first").attr("id");

        thenum = lastId.match(/\d+/g);

        newId = Number(thenum) + 1;

        newrow= jQtable.find("tr:last").clone();

        newrow.find("label:first").html(newId+1);

        newrow.find("input,textarea,checkbox,select,.errorMessage").each(function() {

            this.id= this.id.replace(/\d+/,newId);

           if(!$(this).is(":checkbox"))

                this.value  = "";

            else

                $(this).prop("checked", false);

            (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   "display:none;";});

        jQtable.append(newrow);

        auto_complete2(formIdStarter,newId);

        //$.colorbox.resize();

        var current_row = $(this).parents("tr:last");

        lastrow=newId;

        lastId = $(this).closest("tr").find("input[type=text]").attr("id");

        thenum = lastId.match(/\d+/g);

        thenum=parseInt(thenum);

        lastrow=parseInt(lastrow);

        diff=lastrow-thenum;

        for(j=thenum;j<lastrow;j++)

        {

        if(j==thenum)

        {

        row_need_to_replace    =   current_row.next();

        }

        else {

        row_need_to_replace    =   row_need_to_replace.next();

        }

        }

        last_replace=row_need_to_replace;

        for(j=lastrow;j>thenum;j--)

        {

        if(j==thenum)

        {

        row_need_to_replace    =   current_row.next();

        if(current_row.find("input,textarea").length>0)

        {

        var i=0;

        row_need_to_replace.find(":input").each(function(){

        input_need_to_replace=current_row.find(":input :eq("+i+")");

        temp   =   input_need_to_replace.val();

        alert("ok ="+temp);

        input_need_to_replace.val($(this).val());

        $(this).val(temp);

        this_readonly=$(this).is(\'[readonly]\')

        input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');

        $(this).attr(\'readonly\',input_need_to_replace_readonly);

        input_need_to_replace.attr(\'readonly\',this_readonly);

        i++;

        });

        }

        }

        else {

        if(j==lastrow)

        {

        pre=last_replace;

        row_need_to_replace    =   last_replace.prev();

        }

        else {

        pre=row_need_to_replace;

        row_need_to_replace    =   row_need_to_replace.prev();

        }

        if(pre.find("input,textarea").length>0)

        {

            var i=0;

            row_need_to_replace.find(":input").each(function(){

            input_need_to_replace=pre.find(":input :eq("+i+")");

            alert("ok 1 ="+input_need_to_replace);

            temp   =   input_need_to_replace.val();

            input_need_to_replace.val($(this).val());

            $(this).val(temp);

            this_readonly=$(this).is(\'[readonly]\')

            input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');

            $(this).attr(\'readonly\',input_need_to_replace_readonly);

            input_need_to_replace.attr(\'readonly\',this_readonly);

            i++;

            });

            }

        }

    }

//                            row_need_to_replace1    =   current_row.next();

//                            row_need_to_replace    =   row_need_to_replace1.next();

//        if(row_need_to_replace.find("input,textarea").length>0)

//        {

//

//            var i=0;

//            row_need_to_replace1.find(":input").each(function(){

//                input_need_to_replace=row_need_to_replace.find(":input :eq("+i+")");

//                temp   =   input_need_to_replace.val();

//                input_need_to_replace.val($(this).val());

//                $(this).val(temp);

//                this_readonly=$(this).is(\'[readonly]\')

//                input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');

//                $(this).attr(\'readonly\',input_need_to_replace_readonly);

//                input_need_to_replace.attr(\'readonly\',this_readonly);

//                i++;

//            });

//        }

        });

    });', CClientScript::POS_READY);
        ?>

        <?php
        $cs->registerScript("autoCompletePaymentcharge", "function autoCompletePaymentcharge(field_id,frm,slectedType,typevalue){

        var arr_fields 		= field_id.split('_');

        var model_name 		= arr_fields[0];

        var row_id 			= arr_fields[1];

        var row_field_name 	= arr_fields[2];

        var url = '" . Yii::app()->createUrl('finance/SearchPaymntAccount') . "'+'&type='+slectedType;

        $('#'+field_id).autocomplete({

            minLength   : 1,

            source      : function (request, response) { autoCompleteSource(request, response,url) },

            focus       : function( event, ui ) { $(this).val((ui.item.label).split(':')[1]); return false;},

            select          : function( event, ui ) {

                event.preventDefault();

                trigger_target_id  	=   $(event.target).attr('id');

                var fin_account_id				=	ui.item.value;

                var fin_account_description		=	ui.item.label;

                $('#fin_account_id_newcharge').val(fin_account_id);

                 $('#bank_account_id').val(fin_account_id);

                return getSubLedgerByAccount1(model_name,row_id,fin_account_id,slectedType);

            }

        })

    }", CClientScript::POS_HEAD);

        $cs->registerScript("autoCompleteParent", "function autoCompleteParent(field_id,frm,slectedType,typevalue){

        var arr_fields 		= field_id.split('_');

        var model_name 		= arr_fields[0];

        var row_id 			= arr_fields[1];

        var row_field_name 	= arr_fields[2];

        var url = '" . Yii::app()->createUrl('finance/SearchPaymntAccount') . "&frm='+frm;

        $('#'+field_id).autocomplete({

            minLength   : 1,

            source      : function (request, response) { autoCompleteSource(request, response,url) },

            focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},

            select          : function( event, ui ) {

                event.preventDefault();

                trigger_target_id  	=   $(event.target).attr('id');

                var fin_account_id				=	ui.item.value;

                var fin_account_description		=	ui.item.label;

                $('#'+model_name+'_'+row_id+'_fin_account_id').val(fin_account_id);

                $('#account_id').val(fin_account_id);

                $('#accounts').val(fin_account_id);

                $('#accounts1').val(fin_account_id);

                $('#voucher_check').val(fin_account_id);

                return getSubLedgerByAccount(model_name,row_id,fin_account_id,slectedType,frm);

            }

        })

    }", CClientScript::POS_HEAD);

        $cs->registerScript("getSubLedgerByAccount", " function getSubLedgerByAccount(model_name,row_id,fin_account_id,slectedType,frm){

        var selected_element_id=row_id;

        var model=model_name;

        jQuery.ajax({

            'type': 'post',

            'dataType':'json',

             'data': { 'id':fin_account_id ,'slectedType':slectedType,'i':row_id }  ,

            'url': '" . Yii::app()->createUrl('finance/getDescriptionAcc') . "&frm='+frm,

            'success': function(data) {

          //    $('#'+model+'_'+selected_element_id+'_subledger').html(data.subledger);

              $('#FinGeneralLedger_'+selected_element_id+'_fin_subledger').val('');

              $('#GeneralLedger_'+selected_element_id+'_subledger').html(data.subledger);

               $('#GeneralLedger_0_subledger_new').html(data.subledger);

                $('#subledger_div').html(data.subledger);

                if(data.bank=='Y'){

                    $('#paymentbutton'+selected_element_id).show();

                }else{

                    $('#paymentbutton'+selected_element_id).hide();

                }

             }

        });

    } ", CClientScript::POS_HEAD);

        $cs->registerScript("getExchangeRate", " function getExchangeRate(currency_id,attribute,line_item,company_id) {

        jQuery.ajax({

            'type': 'post',

            'dataType': 'json',

            'data': 'currency_id=' + currency_id,

            'url': '" . CController::createUrl('fetchcurrencydetails') . "',

            'success':function(data){

                $(attribute).val(data.exchange_rate);

                if(line_item!='')

                resetLineItemPrice(line_item,data.exchange_rate,company_id);

            }

        });

    } ", CClientScript::POS_HEAD);

        $cs->registerScript("autoCompletePayment", "function autoCompletePayment(field_id,frm,slectedType,typevalue){

        var arr_fields 		= field_id.split('_');

        var model_name 		= arr_fields[0];

        var row_id 			= arr_fields[1];

        var row_field_name 	= arr_fields[2];

        var url = '" . Yii::app()->createUrl('finance/SearchPaymntAccount') . "';

        $('#'+field_id).autocomplete({

            minLength   : 1,

            source      : function (request, response) { autoCompleteSource(request, response,url) },

            focus       : function( event, ui ) { $(this).val((ui.item.label).split(':')[1]); return false;},

            select          : function( event, ui ) {

                event.preventDefault();

                trigger_target_id  	=   $(event.target).attr('id');

                var fin_account_id				=	ui.item.value;

                var fin_account_description		=	ui.item.label;

                $('#fin_account_id_new').val(fin_account_id);

               $('#bank_account_id').val(fin_account_id);

                return getSubLedgerByAccount1(model_name,row_id,fin_account_id,slectedType);

            }

        })

    }", CClientScript::POS_HEAD);

        $cs->registerScript("autoCompletePaymentcdc", "function autoCompletePaymentcdc(field_id,frm,slectedType,typevalue){

        var arr_fields 		= field_id.split('_');

        var model_name 		= arr_fields[0];

        var row_id 			= arr_fields[1];

        var row_field_name 	= arr_fields[2];

        var url = '" . Yii::app()->createUrl('finance/SearchPaymntAccount') . "';

                        $('#'+field_id).autocomplete({

        minLength   : 1,

        source      : function (request, response) { autoCompleteSource(request, response,url) },

        focus       : function( event, ui ) { $(this).val((ui.item.label).split(':')[1]); return false;},

        select          : function( event, ui ) {

            event.preventDefault();

            trigger_target_id  	=   $(event.target).attr('id');

            var fin_account_id				=	ui.item.value;

            var fin_account_description		=	ui.item.label;

            $('#fin_account_id_newcdc').val(fin_account_id);

            $('#cdc_bank_account_id').val(fin_account_id);

            return getSubLedgerByAccount1(model_name,row_id,fin_account_id,slectedType);

        }

    })

    }", CClientScript::POS_HEAD);

        $cs->registerScript("getSubLedgerByAccount1", " function getSubLedgerByAccount1(model_name,row_id,fin_account_id,slectedType){

        var selected_element_id=row_id;

        var model=model_name;

        jQuery.ajax({

            'type': 'post',

            'dataType':'json',

             'data': { 'id':fin_account_id ,'slectedType':slectedType,'i':row_id }  ,

            'url': '" . Yii::app()->createUrl('finance/getDescriptionAcc1') . "',

            'success': function(data) {

             //  $('#GeneralLedger_0_subledger_new').html(data.subledger);

                 $('#AccountLedger').html(data.subledger);

                if(data.bank=='Y'){

                    $('#paymentbutton'+selected_element_id).show();

                }else{

                    $('#paymentbutton'+selected_element_id).hide();

                }

             }

        });

    } ", CClientScript::POS_HEAD);

        $cs->registerScript("reloadTable", "function reloadTable(table_id){

        var table = $(table_id).DataTable();

        table.ajax.reload( function ( json ) {

              $('#myInput').val( json.lastInput );

        });

    }", CClientScript::POS_HEAD);

        $cs->registerScript("addTableRows1", " function addTableRows1(jQtable) {

        if(jQtable.attr('id')!=undefined){

            $('.quotation-helper,.purchase-helper,.stock-helper').each(function(){ $(this).hide(); $(this).find('table').remove();});

            var formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];

            var lastId = jQtable.find('tr:last textarea:first').attr('id');

            var thenum = lastId.match(/\d+/g);

            var newId = Number(thenum) + 1;

            var newrow= jQtable.find('tr:last').clone();

            newrow.find('label').html(newId+1);

            newrow.attr('class',newId);

            newrow.find('div,input,textarea,select,.errorMessage').each(function() {

                this.id= this.id.replace(/\d+/,newId);

                this.value  = '';

           //     (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   'display:none;';

                 if(this.name!==undefined)  this.name= this.name.replace(/\d+/,newId);

                 });

            jQtable.append(newrow);

            auto_complete2(formIdStarter,newId);

//                //$.colorbox.resize();

        }

    }", CClientScript::POS_HEAD);

        $cs->registerScript("autoCompleteSubLedger", "function autoCompleteSubLedger(field_id,frm,slectedType){

        var arr_fields 		= field_id.split('_');

        var model_name 		= arr_fields[0];

        var row_id 			= arr_fields[1];

        var row_field_name 	= arr_fields[2];

        var account_id = 0;

        if( frm == 'journal' || frm == 'debitnote' || frm == 'creditnote')

            account_id = $('#FinGeneralLedger_'+row_id+'_fin_account_id').val();

        if( frm == 'receipt' || frm == 'payment' )

            account_id = $('#account_id').val();

        if( frm == 'allocatevoucher' )

            account_id = $('#accounts').val();

        if( frm == 'gllist' || frm == 'glstatement' || frm == 'glsummary' || frm == 'ageing')

            account_id = $('#FinGeneralLedger_0_fin_account_id').val();

            var url = '" . Yii::app()->createUrl('finance/SearchSubLedger') . "&account_id='+account_id;

            $('#'+field_id).autocomplete({

                minLength   : 1,

                source      : function (request, response) { autoCompleteSource(request, response,url) },

                focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},

                select          : function( event, ui ) {

                event.preventDefault();

                trigger_target_id  	=   $(event.target).attr('id');

                    var company_id=	ui.item.value;

                    var company_name=ui.item.label;

                    if(slectedType==1){

                    $('#'+model_name+'_'+row_id+'_fin_subledger').val(company_id);

                    }else if(slectedType==0){

                     $('#fin_givenname').val(company_id);

                    }else if(slectedType==2){

                     $('#fin_subledger_new').val(company_id);

                    }

                    $('#subledger').val(company_id);

                    $('#subledger_id').val(company_id);

                    $('#subledger1').val(company_id);

                }

            })

    }", CClientScript::POS_HEAD);

        $cs->registerScript("removeExtrasRowSforfin", " function removeExtrasRowSforfin(jQtable,evt,idvalue) {

        formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];

        var num_rows    =   jQtable.find('tr').length;

        extra_val = $(evt).parents('tr').find('input:eq(2)').val();

        gd_total =   $('.'+formIdStarter+'_grand_total .grandtotal').text();

        gd_total=gd_total.replace(/,/g , '');

        if(jQtable.attr('id')==='purchasingOrder_final_add_table' || jQtable.attr('id')==='quotes_final_add_table' ||

        jQtable.attr('id')==='order_final_add_table')

            gd_total =   (Number(gd_total)-Number(extra_val)).toFixed(2);

        else gd_total =   (Number(gd_total)+Number(extra_val)).toFixed(2);

        $('.'+formIdStarter+'_grand_total .grandtotal').text(gd_total);

        if(num_rows>1){

            $(evt).parents('tr').remove();

            $('#labelacc'+idvalue).remove();

            $('#FinGeneralLedger_'+idvalue+'_realisation_date').remove();

            $('#FinGeneralLedger_'+idvalue+'_chk_no').remove();

            $('#FinGeneralLedger_'+idvalue+'_chk_description').remove();

        }

        else $(evt).parents('tr').find('input').val('');

       // $.colorbox.resize();

    }", CClientScript::POS_HEAD);

        /*         * **************** Code added By Mereena On 28/11/2017 for material allocation ****************** */

        $cs->registerScript("saveMaterialAllocation", "function saveMaterialAllocation(id,modelName,cntrlName,tblName){

        var r = confirm('Are you sure you want to allocate materials?');

        if(r==true)

        {

        jQuery.ajax({

            'type'  : 'post',

            'dataType' : 'json',

            'data'  : 'id=' + id+'&modelName='+modelName,

            'url'  : $('#liveSite').val()+'index.php?r='+cntrlName+'/MaterialAllocation',

            'cache': false,

            'success':function(data){

                if(data=='fail'){

                    alert('Allocation Not Possible', 'Alert');

                }else {

                     reloadTable('#'+tblName);

                      if(data.shoratage!=''){

                         t8.error(data.shoratage);

                     }

                     t8.success(data.no_of_items_allocated+' Items Allocated Successfully!','success');

                }

            }

        });

        }

    };", CClientScript::POS_HEAD);

        $cs->registerScript("updateSubleadgers", "function updateSubleadgers(){

        $('#loader').show();

        jQuery.ajax({

            'type': 'post',

            'url': '" . Yii::app()->createUrl('finance/core/importsystemsubledgers') . "',

            'success': function(data) {

                t8.success('Done!');

                $('#loader').hide();

                reloadTable('#tbl_fin_subledger');

            }

        });

    }", CClientScript::POS_HEAD);

        $cs->registerScript("updateSubleadgersType", "function updateSubleadgersType(id){

        $('#loader').show();

        jQuery.ajax({

            'type': 'post',

            'data'  : 'id=' + id,

            'url': '" . Yii::app()->createUrl('finance/core/ImportsystemsubledgersType') . "',

            'success': function(data) {

                t8.success('Done!');

                $('#loader').hide();

                reloadTable('#tbl_fin_subledger');

            }

        });

    }", CClientScript::POS_HEAD);

        /*         * ***************** End code for material allocation ******************************************* */

        /*         * Outstanding invoice sync */

        $cs->registerScript("syncinvoices", "function syncinvoices(){

        var r = confirm('Do you want to Sync Invoices with finance?');

            if(r==true)

            {

                jQuery.ajax({

              'type'  : 'post',

              'url'  : $('#liveSite').val()+'index.php?r=finance/syncinvoices',

                  'cache': false,

                  'success':function(data){

                    if(data=='fail'){

                        t8.error('Something went wrong!');

                    }else {

                        reloadTable('#tble_receipt_list');

                        t8.success('Synced!');

                    }

                   }

                });

            }

    };", CClientScript::POS_HEAD);