

// -------------------------------------------------------------------------------------------------------------------------------------
// embed csrf token in every ajax request as header
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

// function to check every ajax response
$(document).ajaxComplete(function( event, xhr, settings )
{
	response = JSON.parse(xhr.responseText);
	if(response.log_status == 'expired')
	{
		window.location.href = app_url()+'/login';
	}
});
// -------------------------------------------------------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------------------------------------------
// check all rows
$(document).on("click", ".check-all-btn-trigger", function(event)
{
	if($(this).hasClass('checked'))
	{
		$(this).removeClass('checked');
		$('.multi-checker-input').prop('checked',false);
	}
	else
	{
		$(this).addClass('checked');
		$('.multi-checker-input').prop('checked',true);
	}
});

$(document).on("click", ".check-all-btn-trigger-items", function(event)
{

	if($(this).is(":checked"))
	{
		$('.multi-checker-input-items').prop('checked',true);
	}
	else
	{
		$('.multi-checker-input-items').prop('checked',false);
	}
});

// function to perform multi checker
$(document).on('click','.multi-delete-btn-trigger, .multi-approve-btn-trigger',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	pointer_obj = $(this);
	url = $(this).attr('href');


	// get checked rows
	uids = [];
	$('.multi-checker-input').each(function(e)
	{
		if($(this).is(':checked'))
		{
			row_uid = $(this).attr('value');
			uids.push(row_uid);
		}
	});

	if(uids.length == 0)
	{
		// warning
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some rows to proceed.', 'No Selection');
		return false;
	}
	
	if(pointer_obj.hasClass('multi-approve-btn-trigger'))
	{
		main_title = $('#langs-span').attr('data-confirm-main-title');
		sub_title = $('#langs-span').attr('data-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-confirm-cancel-btn-text');
	}
	else
	{
		sub_title = $('#langs-span').attr('data-delete-sub-title');
		main_title = $('#langs-span').attr('data-delete-main-title');
		confirm_btn_text = $('#langs-span').attr('data-delete-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-delete-cancel-btn-text');
	}

	swal(
	{
	    title: main_title,
	    text: sub_title,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: cancel_btn_text,
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: confirm_btn_text,
	    closeOnConfirm: true
	},
	function()
	{
		$('.ibox-content').addClass('sk-loading');
		$('body').addClass('inprocess');
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: {uids:uids.join(',')},
			success:function(response)
			{
				$('body').removeClass('inprocess');
				$('.ibox-content').removeClass('sk-loading');
				response = JSON.parse(response);

				if(response.status == 'success')
				{
					$('.multi-checker-input').each(function(e)
					{
						if($(this).is(':checked'))
						{
							$(this).closest('tr').remove();
						}
					});
				}
			},
			error: function(data)
			{
				$('.ibox-content').removeClass('sk-loading');
				$('body').removeClass('inprocess');
			}
		});
	});
});
// -----------------------------------------------------------------------------------------------------------------------


// -------------------------------------------------------------------------------------------------------------------------------------
// function to delete table reords
$(document).on('click','.delete-btn-trigger, .confirm-btn-trigger',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	pointer_obj = $(this);
	url = $(this).attr('href');
	
	if(pointer_obj.hasClass('confirm-btn-trigger'))
	{
		main_title = $('#langs-span').attr('data-confirm-main-title');
		sub_title = $('#langs-span').attr('data-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-confirm-cancel-btn-text');
	}
	else
	{
		sub_title = $('#langs-span').attr('data-delete-sub-title');
		if(pointer_obj.hasClass('show-lot-note'))
		{
			sub_title = $('#langs-span').attr('data-delete-popup-lot-note');
		}
		main_title = $('#langs-span').attr('data-delete-main-title');
		confirm_btn_text = $('#langs-span').attr('data-delete-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-delete-cancel-btn-text');
	}

	swal(
	{
	    title: main_title,
	    text: sub_title,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: cancel_btn_text,
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: confirm_btn_text,
	    closeOnConfirm: true
	},
	function()
	{
		$('body').addClass('inprocess');
		ibox_obj = pointer_obj.closest('.ibox-content');
		ibox_obj.addClass('sk-loading');
		$.ajax(
		{
			url:url,
			success:function(response)
			{
				$('body').removeClass('inprocess');
				response = JSON.parse(response);

				if(pointer_obj.hasClass('emp-doc'))
				{
					pointer_obj.closest('.emp-doc-col').remove();
					ibox_obj.removeClass('sk-loading');
				}
				else
				{
					pointer_obj.closest('tr').remove();
					ibox_obj.removeClass('sk-loading');
				}

				if(response.mode == 'reload')
				{
					location.reload();
				}
			},
			error: function(data)
			{
				$('body').removeClass('inprocess');
				ibox_obj.removeClass('sk-loading');
			}
		});
	    // swal("Disabled!", "Record has been disabled.", "success"); // uncomment this line if you wana show success popu after delete
	});
});
// -----------------------------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------------------------------------------
// function to make image preview on select
$(document).on("change", ".file-upload-iput", function(event)
{
	elem_obj = $(this);
    if(this.files)
    {
        var reader = new FileReader();
        reader.onload = function (e){ elem_obj.siblings('img').attr('src',reader.result); }
        reader.readAsDataURL(event.target.files[0]);
    }
});
// -------------------------------------------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------------------------------------------
// set validate.js to not ignore hidden chosen selects
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" });


$.validator.addMethod(
"unique_batch",
function(value, element, regexp)
{
	// get the json of batch
	batch_array = $('#batch-items-json').text();
	item_id = $('#purchases-temp-item option:selected').val();
	console.log(batch_array);
	batch_array = JSON.parse(batch_array);
	console.log(batch_array);
	batch_matched = false;
	$.each(batch_array, function (_batch, _item)
	{
		if(value == _batch && item_id != _item){ batch_matched = true; }
	});

	if(batch_matched == true)
	{
		return false;
	}
	else
	{
		return true;
	}

},
"Batch used by another item"
);
// -------------------------------------

$.validator.addMethod(
"unique_batch_ti",
function(value, element, regexp)
{
	// get the json of batch
	batch_array = $('#batch-items-json').text();
	item_id = $('#transfer-in-temp-item option:selected').val();
	console.log(batch_array);
	batch_array = JSON.parse(batch_array);
	console.log(batch_array);
	batch_matched = false;
	$.each(batch_array, function (_batch, _item)
	{
		if(value == _batch && item_id != _item){ batch_matched = true; }
	});

	if(batch_matched == true)
	{
		return false;
	}
	else
	{
		return true;
	}

},
"Batch used by another item"
);
// -------------------------------------

// add user form validations
$("#user-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    email: { required: true, email: true },
	    phone: { required: true, digits: true },
	    branch: { required: function(element) { return is_branch_required(); } },
	    username: { required: true, minlength: 3 },
	    password: { required: true, minlength: 3 },
	    address: { required: true },
	}
});

function is_branch_required()
{
	user_role = $('[name=role]').val();
	if(user_role == 'USER')
	{
		return true;
	}
	else
	{
		return false;
	}
}

// edit user form validations
$("#user-edit-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    email: { email: true },
	    phone: { required: true, digits: true },
	    branch: { required: function(element) { return is_branch_required(); } },
	    username: { minlength: 3 },
	    password: { minlength: 3 },
	    address: { required: true },
	}
});

$("#branches-form").validate({
	debug: true,
	rules: {
	    branch_number: { required: true },
	    branch_name: { required: true },
	    branch_mobile: { required: true },
	    branch_address: { required: true },
	    branch_direction: { required: true },
	    branch_language: { required: true },
	}
});

// add accounts form validations
$("#accounts-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    type: { required: true },
	    code: { required: function(element) { return is_not_root(); } },
	    memo: { required: function(element) { return is_not_root(); } },
	    category: { required: function(element) { return is_category(); } },
	    sales_man: { required: function(element) { return is_sales_man(); } },
	    marketer: { required: function(element) { return is_marketer(); } },
	    username: { required: function(element) { return is_user(); }, minlength: 3 },
	    password: { required: function(element) { return is_user(); }, minlength: 3 },
	}
});

function is_not_root()
{
	account_type = $('[name=type]').val();
	if(account_type == 'root')
	{
		return false;
	}
	else
	{
		return true;
	}
}

function is_user()
{
	account_type = $('[name=type] option:selected').val();
	if(account_type == 'client')
	{
		type = $('input[name="is_user"]:checked').val();
		if(type == 'yes')
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

function is_category()
{
	account_type = $('[name=type] option:selected').val();
	if(account_type == 'client')
	{
		type = $('input[name="client_type"]:checked').val();
		if(type == 'category')
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

function is_sales_man()
{
	account_type = $('[name=type] option:selected').val();
	if(account_type == 'client')
	{
		type = $('input[name="client_type"]:checked').val();
		if(type == 'sales_man')
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

function is_marketer()
{
	account_type = $('[name=type] option:selected').val();
	if(account_type == 'client')
	{
		type = $('input[name="client_type"]:checked').val();
		if(type == 'marketer')
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

// add currency form validations
$("#currency-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    symbol: { required: true },
	    usd_equalance: { required: true },
	    branch_equalance: { required: true },
	}
});

// add currency form validations
$("#units-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    short: { required: true },
	}
});

// add currency form validations
$("#batch-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    number: { required: true },
	}
});

// add currency form validations
$("#product-category-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#journal-form").validate({
	debug: true,
	rules: {
	    journal_date: { required: true },
	    receiving_currency: { required: true },
	    payment_currency: { required: true },
	    receiving_account: { required: true },
	    payment_account: { required: true },
	    receiving_amount: { required: true },
	    payment_amount: { required: true },
	    receiving_narration: { required: true },
	    payment_narration: { required: true },
	}
});

$("#calander-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#warehouse-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    type: { required: true },
	    manager: { required: true },
	    address: { required: true },
	}
});

$("#items-form").validate({
	debug: true,
	rules: {
	    item_id: { required: true },
	    name: { required: true },
	    type: { required: true },
	    purchase_unit: { required: true },
	    purchase_unit_equalance: { required: true },
	    height: { required: true },
	    width: { required: true },
	    cost: { required: true },
	    sale_price: { required: function(element) { return is_sale_price_required(); } },
	    reorder_qty: { required: true },
	}
});

function is_sale_price_required()
{
	type = $('[name=type]').val();
	if(type == 'raw')
	{
		return false;
	}
	else
	{
		return true;
	}
}

$("#temp-purchases-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_supplier: { required: true },
	    temp_invoice: { required: true },
	    temp_item: { required: true },
	    // temp_batch: { unique_batch: true },
	    temp_warehouse: { required: true },
	    temp_cost: { required: true },
	    temp_qty: { required: true },
	    temp_unit: { required: true },
	    temp_profit: { required: true },
	    temp_tp: { required: true },
	}
});

$("#cn-purchases-form").validate({
	debug: true,
	rules: {
	    invoice: { required: true },
	    cn_date: { required: true },
	    item: { required: true },
	    currency: { required: true },
	    warehouse: { required: true },
	    supplier: { required: true },
	    unit: { required: true },
	    batch: { required: true },
	    qty: { required: true },
	    cost: { required: true },
	    total: { required: true },
	}
});

$("#temp-transfer-in-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_item: { required: true },
	    temp_warehouse: { required: true },
	    temp_cost: { required: true },
	    temp_qty: { required: true },
	    temp_unit: { required: true },
	    temp_profit: { required: true },
	    temp_tp: { required: true },
	}
});

// $("#production-raw-items-form").validate({
// 	debug: true,
// 	rules: {
// 	    temp_raw_warehouse: { required: true },
// 	    temp_raw_item: { required: true },
// 	    temp_raw_used_qty: { required: true },
// 	    temp_raw_unit: { required: true },
// 	}
// });

$("#production-produced-items-form").validate({
	debug: true,
	rules: {
	    temp_produced_item: { required: true },
	    temp_produced_warehouse: { required: true },
	    temp_sale_unit: { required: true },
	}
});

$("#production-raw-items-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    temp_raw_warehouse: { required: true },
	    temp_raw_item: { required: true },
	    temp_raw_batch: { required: true },
	    temp_raw_used_qty: { required: true },
	    temp_raw_damage_qty: { required: true },
	    temp_raw_unit: { required: true },
	}
});


$("#sales-form").validate({
	debug: true,
	rules: {
	    expense_account: { required: function(element) { return is_sales_expenses_found(); } },
	    cash_received_account: { required: function(element) { return is_sales_cash_paid_found(); } },
	}
});

function is_sales_expenses_found()
{
	return (refine_number($('#sales-form [name=trans_expense]').val()) > 0) ? true : false;
}
function is_sales_cash_paid_found()
{
	return (refine_number($('#sales-form [name=cash_received]').val()) > 0) ? true : false;
}

$("#transfer-in-form").validate({
	debug: true,
	rules: {
	    cash_paid_account: { required: function(element) { return is_transfer_in_cash_paid_found(); } },
	}
});
function is_transfer_in_cash_paid_found()
{
	return (refine_number($('#transfer-in-form [name=paid_amount]').val()) > 0) ? true : false;
}

$("#transfer-out-form").validate({
	debug: true,
	rules: {
	    cash_received_account: { required: function(element) { return is_transfer_out_cash_received_found(); } },
	}
});
function is_transfer_out_cash_received_found()
{
	return (refine_number($('#transfer-out-form [name=cash_received]').val()) > 0) ? true : false;
}

$("#sales-items-temp-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_item: { required: true },
	    temp_qty: { required: true },
	    temp_batch: { required: true },
	    temp_unit: { required: true },
	    temp_client_name: { required: function(element) { return is_cash_sale(); } },
	}
});

$("#sales-sets-form").validate({
	debug: true,
	rules: {
	    set_select: { required: true },
	}
});

$("#transfer-out-items-temp-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_item: { required: true },
	    temp_qty: { required: true },
	    temp_unit: { required: true },
	}
});

$("#sales-service-items-temp-form").validate({
	debug: true,
	rules: {
	    item_description: { required: true },
	    service_unit: { required: true },
	    service_qty: { required: true },
	    service_cost: { required: true },
	    service_sale_price: { required: true },
	}
});

function is_cash_sale()
{
	client = $('[name=temp_client]').val();
	cash_sale = 'CASHSALE';
	// CHECK IF VALUE HAS STRING CASHSALE
	if(client_id.indexOf(cash_sale) != -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

$("#quotation-temp-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_item: { required: true },
	    temp_qty: { required: true },
	    temp_unit: { required: true },
	    temp_client_name: { required: function(element) { return is_cash_sale(); } },
	}
});

$("#expenses-types-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    color: { required: true },
	}
});

$("#shareholder-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    last_name: { required: true },
	    nic: { required: true },
	    address: { required: true },
	    percentage: { required: true },
	}
});

$("#expenses-form").validate({
	debug: true,
	rules: {
	    type: { required: true },
	    exp_date: { required: true },
	    account: { required: true },
	    amount: { required: true },
	    currency: { required: true },
	    narration: { required: true },
	}
});

$("#damage-stock-form").validate({
	debug: true,
	rules: {
	    warehouse: { required: true },
	    item: { required: true },
	    qty: { required: true },
	    unit: { required: true },
	}
});

$("#transfer-form").validate({
	debug: true,
	rules: {
	    batch: { required: true },
	    receiving_warehouse: { required: true },
	    qty: { required: true },
	    unit: { required: true },
	}
});

$("#language-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    direction: { required: true },
	}
});

$("#assets-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    type: { required: true },
	    account: { required: true },
	    name: { required: true },
	    qty: { required: true },
	    price: { required: true },
	}
});

$("#employees-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    father_name: { required: true },
	    date_of_birth: { required: true },
	    phone: { required: true },
	    gender: { required: true },
	    marital_status: { required: true },
	    nationality: { required: true },
	    designation: { required: true },
	    date_of_joining: { required: true },
	    joining_salary: { required: true },
	    currency: { required: true },
	    employee_status: { required: true },
	    division: { required: true },
	}
});

$("#increments-form").validate({
	debug: true,
	rules: {
	    increment_date: { required: true },
	    employee: { required: true },
	    new_salary: { required: true },
	}
});

$("#advances-form").validate({
	debug: true,
	rules: {
	    advance_date: { required: true },
	    employee: { required: true },
	    new_advance: { required: true },
	    account: { required: true },
	}
});

$("#payslips-form").validate({
	debug: true,
	rules: {
	    pay_date: { required: true },
	    employee: { required: true },
	    account: { required: true },
	}
});

$("#transit-temp-form").validate({
	debug: true,
	rules: {
	    temp_base_currency: { required: true },
	    temp_transit_date: { required: true },
	    temp_transit_serial_num: { required: true },
	    temp_builty_num: { required: true },
	    temp_transit_company: { required: true },
	    temp_account: { required: true },
	    temp_currency: { required: true },
	    temp_amount: { required: true },
	}
});

$("#extra-income-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    account: { required: true },
	    amount: { required: true },
	    type: { required: true },
	}
});

$("#temp-lot-purchase-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_supplier: { required: true },
	    temp_receipt: { required: true },
	    temp_weight: { required: true },
	    temp_cost: { required: true },
	}
});

$("#temp-lot-purchase-form-division").validate({
	debug: true,
	rules: {
	    div_weight: { required: true },
	    div_cost: { required: true },
	}
});

$("#lot-sale-form").validate({
	debug: true,
	rules: {
	    _sold_currency: { required: true },
	    _sold_client: { required: true },
	    _sold_sale_price: { required: true },
	}
});

$("#lot-invoice-sale-form").validate({
	debug: true,
	rules: {
	    _invoice_sold_currency: { required: true },
	    _invoice_sold_client: { required: true },
	    _invoice_sold_sale_price: { required: true },
	}
});

$("#lot-move-form").validate({
	debug: true,
	rules: {
	    _move_item: { required: true },
	    _move_warehouse: { required: true },
	    _move_weight: { required: true },
	    _move_unit: { required: true },
	}
});

$("#branch-transfer-out-form").validate({
	debug: true,
	rules: {
	    item: { required: true },
	    warehouse: { required: true },
	    unit: { required: true },
	    qty: { required: true },
	    to_branch: { required: true },
	    to_warehouse: { required: true },
	}
});

$("#branch-transfer-in-form").validate({
	debug: true,
	rules: {
	    item: { required: true },
	    to_warehouse: { required: true },
	    unit: { required: true },
	    qty: { required: true },
	    from_branch: { required: true },
	    from_warehouse: { required: true },
	}
});

$("#project-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    address: { required: true },
	    company: { required: true },
	    client: { required: true },
	    currency: { required: true },
	    cost: { required: true },
	    cash_paid_account: { required: true },
	    cash_paid: { required: true },
	    start_date: { required: true },
	    end_date: { required: true },
	    username: { required: true, minlength: 3 },
	    password: { required: true, minlength: 3 },
	    confirm_password: { required: true },
	}
});

$("#project-edit-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    address: { required: true },
	    company: { required: true },
	    client: { required: true },
	    currency: { required: true },
	    cost: { required: true },
	    cash_paid_account: { required: true },
	    cash_paid: { required: true },
	    start_date: { required: true },
	    end_date: { required: true },
	    username: { required: true, minlength: 3 },
	    password: { minlength: 3 },
	    confirm_password: { required: function(element) { return is_pwd_found(); } },
	}
});

function is_pwd_found()
{
	password = $('[name=password]').val();
	if($.trim(password).length > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

$("#payment-deductions-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    amount: { required: true },
	    pdate: { required: true },
	    project: { required: true },
	    from_account: { required: true },
	    to_account: { required: true },
	}
});

$("#project-payments-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    amount: { required: true },
	    pdate: { required: true },
	    project: { required: true },
	    account: { required: true },
	    payment_type: { required: true },
	    user: { required: true },
	}
});

function expenses_deduction_mood(mood)
{
	expenses_deduction_mood = $('[name=expenses_deduction_mood]:checked').val();
	if(expenses_deduction_mood == mood)
	{
		return true;
	}
	else
	{
		return false;
	}
}

$("#expenses-deductions-form").validate({
	debug: true,
	rules: {
		// cash expenses
	    currency: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },
	    amount: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },
	    cash_date: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },
	    expense_type: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },
	    project: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },
	    account: { required: function(element) { return expenses_deduction_mood('cash_expenses'); } },

	    // inventory expenses
	    inv_project: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	    inv_date: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	    inv_item: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	    inv_warehouse: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	    inv_unit: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	    inv_qty: { required: function(element) { return expenses_deduction_mood('inventory_expenses'); } },
	}
});

$("#project-expenses-deductions-form").validate({
	debug: true,
	rules: {
		// cash expenses
		deduction_type: { required: true },
	    currency: { required: true },
	    amount: { required: true },
	    cash_date: { required: true },
	    payment_type: { required: true },
	    // expense_type: { required: true },
	    // account: { required: true },
	}
});

$("#project-report-form").validate({
	debug: true,
	rules: {
	    title: { required: true },
	    project: { required: true },
	}
});

$("#leaves-form").validate({
	debug: true,
	rules: {
	    l_date: { required: true },
	    out_time: { required: true },
	    reason: { required: true },
	    currency: { required: true },
	    expense: { required: true },
	    account: { required: true },
	}
});

$("#leave-return-form").validate({
	debug: true,
	rules: {
	    in_time: { required: true },
	    comments: { required: true },
	}
});

$("#temp-car-purchases-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_agent: { required: true },
	    temp_invoice: { required: true },
	    temp_car_name: { required: true },
	    temp_car_model: { required: true },
	    // temp_shasi_num: { required: true },
	    temp_car_color: { required: true },
	    temp_car_make: { required: true },
	    temp_cost: { required: true },
	}
});

$("#load-delivery-form").validate({
	debug: true,
	rules: {
	    purchase: { required: true },
	    account: { required: true },
	    load_plate: { required: true },
	    load_expenses: { required: true },
	    charges: { required: true },
	}
});

$("#custom-expenses-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    rate: { required: true },
	    invoice: { required: true },
	    load_delivery: { required: true },
	    agent: { required: true },
	    amount: { required: true },
	}
});

$("#custom-charges-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    rate: { required: true },
	    invoice: { required: true },
	    load_delivery: { required: true },
	    car: { required: true },
	    agent: { required: true },
	    amount: { required: true },
	}
});

$("#temp-fixing-expenses-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_rate: { required: true },
	    temp_invoice: { required: true },
	    temp_agent: { required: true },
	    temp_car: { required: true },
	    temp_amount: { required: true },
	}
});

$("#showroom-sales-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    client: { required: true },
	    invoice: { required: true },
	    sale_price: { required: true },
	    cash_paid_account: { required: function(element) { return is_showroom_cash_paid(); } },
	}
});

$("#buy-cars-sales-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    client: { required: true },
	    invoice: { required: true },
	    sale_price: { required: true },
	    cash_paid_account: { required: function(element) { return is_showroom_cash_paid(); } },
	}
});

$("#poeple-showroom-sales-form").validate({
	debug: true,
	rules: {
	    invoice: { required: true },
	    name: { required: true },
	    father_name: { required: true },
	    tazkira: { required: true },
	    mobile: { required: true },
	    cash_paid_account: { required: function(element) { return is_showroom_cash_paid(); } },
	}
});

$("#cpurchases-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    item: { required: true },
	    warehouse: { required: true },
	    invoice: { required: true },
	    supplier: { required: true },
	    rate: { required: true },
	    qty: { required: true },
	    cash_paid_account: { required: function(element) { return is_showroom_cash_paid(); } },
	}
});

$("#services-temp-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_temp_sdate: { required: true },
	    temp_unit: { required: true },
	    temp_qty: { required: true },
	    temp_rate: { required: true },
	}
});

$("#services-quotation-temp-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_client: { required: true },
	    temp_invoice: { required: true },
	    temp_temp_sdate: { required: true },
	    temp_title: { required: true },
	    temp_unit: { required: true },
	    temp_qty: { required: true },
	    temp_rate: { required: true },
	}
});

function is_showroom_cash_paid()
{
	cash_paid = $('[name=cash_paid]').val();
	if($.trim(cash_paid).length > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

$("#citems-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    unit: { required: true },
	}
});

$("#cwarehouses-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#ccontracts-form").validate({
	debug: true,
	rules: {
	    contract_type: { required: true },
	    // employee fields
	    duration_type: { required: function(element) { return is_ccontract_duration_type_required(); } },
	    employee: { required: function(element) { return is_ccontract_employee_required(); } },
	    number_of_duration: { required: function(element) { return is_ccontract_number_of_duration_required(); } },
	    amount: { required: function(element) { return is_ccontract_amount_required(); } },
	    currency: { required: function(element) { return is_ccontract_amount_required(); } },
	    working_hours_per_day: { required: function(element) { return is_ccontract_working_hours_per_day_required(); } },
	    // machinery
	    supplier: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_name: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_currency: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_rate: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_working_hours: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_driver_name: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	    machinery_driver_mobile: { required: function(element) { return is_ccontract_type_is_machinery(); } },
	}
});

function is_ccontract_duration_type_required(){ return ($('[name=contract_type]').val() == 'employee') ? true : false; }
function is_ccontract_type_is_machinery(){ return ($('[name=contract_type]').val() == 'machinery') ? true : false; }
function is_ccontract_employee_required(){ return ($('[name=duration_type]').val() == 'monthly' || $('[name=duration_type]').val() == 'days' || $('[name=duration_type]').val() == 'hours' || $('[name=duration_type]').val() == 'sqm') ? true : false; }
function is_ccontract_number_of_duration_required(){ return ($('[name=duration_type]').val() == 'monthly' || $('[name=duration_type]').val() == 'days' || $('[name=duration_type]').val() == 'hours' || $('[name=duration_type]').val() == 'sqm') ? true : false; }
function is_ccontract_amount_required(){ return ($('[name=duration_type]').val() == 'monthly' || $('[name=duration_type]').val() == 'days' || $('[name=duration_type]').val() == 'hours' || $('[name=duration_type]').val() == 'sqm') ? true : false; }
function is_ccontract_working_hours_per_day_required(){ return ($('[name=duration_type]').val() == 'monthly' || $('[name=duration_type]').val() == 'days' || $('[name=duration_type]').val() == 'hours') ? true : false; }

$("#projects-assign-form").validate({
	debug: true,
	rules: {
	    project: { required: true },
	    assign_type: { required: true },
	    // employee fields
	    employee: { required: function(element) { return is_assign_type_is_employee(); } },
	    num_of_duration: { required: function(element) { return is_assign_type_is_employee(); } },
	    // machinery
	    machinery: { required: function(element) { return is_assign_type_is_machinery(); } },
	    number_of_hours: { required: function(element) { return is_assign_type_is_machinery(); } },
	    // material
	    warehouse: { required: function(element) { return is_assign_type_is_material(); } },
	    item: { required: function(element) { return is_assign_type_is_material(); } },
	    qty: { required: function(element) { return is_assign_type_is_material(); } },
	}
});
function is_assign_type_is_employee(){ return ($('[name=assign_type]').val() == 'employee') ? true : false; }
function is_assign_type_is_machinery(){ return ($('[name=assign_type]').val() == 'machinery') ? true : false; }
function is_assign_type_is_material(){ return ($('[name=assign_type]').val() == 'material') ? true : false; }



$("#buy-cars-form").validate({
	debug: true,
	rules: {
	    car_type: { required: true },
	    currency: { required: true },
	    car_name: { required: true },
	    shasi_num: { required: true },
	}
});

$("#people-showroom-form").validate({
	debug: true,
	rules: {
	    car_type: { required: true },
	    currency: { required: true },
	    car_name: { required: true },
	    shasi_num: { required: true },
	}
});

$("#services-cat-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    unit: { required: true },
	    currency: { required: true },
	    rate: { required: true },
	}
});

$("#marketers-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    last_name: { required: true },
	    mobile: { required: true },
	    commission: { required: true },
	    email: { required: true },
	    username: { required: true },
	    password: { required: true },
	    account: { required: true },
	}
});

$("#sales-man-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    last_name: { required: true },
	    mobile: { required: true },
	    address: { required: true },
	    cnic: { required: true },
	    username: { required: true },
	    password: { required: true },
	    account: { required: true },
	}
});


// add currency form validations
$("#client-categories-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});


$("#money-receipts-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    client: { required: true },
	    amount: { required: true },
	}
});


$("#refund-seach-invoice-form").validate({
	debug: true,
	rules: {
	    client: { required: true },
	    invoice: { required: true },
	}
});

$("#temp-debit-credit-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_account: { required: true },
	    temp_amount: { required: true },
	    temp_d_account: { required: true },
	    temp_d_amount: { required: true },
	}
});

$("#temp-bookings-form").validate({
	debug: true,
	rules: {
	    temp_currency: { required: true },
	    temp_pdate: { required: true },
	    temp_memo: { required: true },
	    temp_item: { required: true },
	    temp_qty: { required: true },
	    temp_tp: { required: true },
	}
});

$("#activities-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    amount: { required: true },
	}
});

$("#suggestions-form").validate({
	debug: true,
	rules: {
	    details: { required: true },
	}
});

$("#debit-credit-voucher-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    account: { required: true },
	    amount: { required: true },
	}
});

$("#purchases-cbm-weight-form").validate({
	debug: true,
	rules: {
	    width: { required: true },
	    height: { required: true },
	    length: { required: true },
	    cbm: { required: true },
	    weight: { required: true },
	}
});

$("#b-to-b-transfer-items-form").validate({
	debug: true,
	rules: {
	    temp_t_date: { required: true },
	    temp_item: { required: true },
	    temp_unit: { required: true },
	    temp_to_branch: { required: true },
	    temp_to_warehouse: { required: true },
	    temp_qty: { required: true },
	}
});

$("#b-to-b-transfer-update-form").validate({
	debug: true,
	rules: {
	    t_date: { required: true },
	    item: { required: true },
	    unit: { required: true },
	    to_branch: { required: true },
	    to_warehouse: { required: true },
	    qty: { required: true },
	}
});

$("#assets-categories-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#share-capitals-categories-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#extra-income-type-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});

$("#share-capitals-form").validate({
	debug: true,
	rules: {
	    event_date: { required: true },
	    type: { required: true },
	    account: { required: true },
	    currency: { required: true },
	    amount: { required: true },
	    percentage: { required: true },
	    shareholder: { required: true },
	}
});

$("#metu-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    currency: { required: true },
	}
});

$("#metu-purchases-form").validate({
	debug: true,
	rules: {
	    p_date: { required: true },
	    metu: { required: true },
	    supplier: { required: true },
	    value: { required: true },
	    percentage: { required: true },
	    total: { required: true },
	}
});

$("#metu-sales-form").validate({
	debug: true,
	rules: {
	    s_date: { required: true },
	    metu: { required: true },
	    client: { required: true },
	    value: { required: true },
	    percentage: { required: true },
	    total: { required: true },
	}
});

$("#tokens-form").validate({
	debug: true,
	rules: {
	    client: { required: true },
	    item: { required: true },
	    currency: { required: true },
	    purchase_qty: { required: true },
	    account: { required: true },
	}
});

$("#turnover-add-search-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    from: { required: true },
	    to: { required: true },
	}
});

$("#shareholder-credit-form").validate({
	debug: true,
	rules: {
	    currency: { required: true },
	    shareholder: { required: true },
	    credit_account: { required: true },
	    amount: { required: true },
	    event_date: { required: true },
	    percentage: { required: true },
	}
});

$("#item-stock-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	    currency: { required: true },
	    unit: { required: true },
	}
});

$("#item-stock-in-form").validate({
	debug: true,
	rules: {
	    account: { required: true },
	    currency: { required: true },
	    item: { required: true },
	    unit: { required: true },
	    quantity: { required: true },
	    cost: { required: true },
	    bill_number: { required: true },
	}
});

$("#item-stock-out-form").validate({
	debug: true,
	rules: {
	    event_date: { required: true },
	    item: { required: true },
	    out_quantity: { required: true },
	    expense_type: { required: true },
	}
});

$("#division-form").validate({
	debug: true,
	rules: {
	    name: { required: true },
	}
});
// -------------------------------------------------------------------------------------------------------------------------------------




// -------------------------------------------------------------------------------------------------------------------------------------
// function to submit forms data
$(document).on('submit','#extra-income-type-form, #new-production-form, #new-production-formula-form, #production-raw-form, #production-raw-relation-form, #production-relation-form, #item-stock-form, #division-form, #item-stock-out-form, #item-stock-in-form, #shareholder-credit-form, #turnover-form, #shareholder-form, #tokens-form, #sets-form, #metu-sales-form, #metu-purchases-form, #metu-form, #assets-categories-form, #share-capitals-form, #share-capitals-categories-form, #items-columns-form, #sales-out-form, #b-to-b-transfer-update-form, #b-to-b-transfer-form, #process-form, #cn-purchases-form, #purchases-cbm-weight-form, #debit-credit-voucher-form, #suggestions-form, #orders-process-form, #activities-form, #bookings-form, #debit-credit-note-form, #transfer-out-form, #transfer-in-form, #sales-return-form, #money-receipts-form, #sales-man-form, #client-categories-form, #marketers-form, #services-cat-form, #services-quotation-form, #services-form, #poeple-showroom-sales-form, #buy-cars-sales-form, #people-showroom-form, #buy-cars-form, #projects-assign-form, #ccontracts-form, #cpurchases-form, #cwarehouses-form, #citems-form, #showroom-sales-form, #project-expenses-deductions-form, #project-payments-form, #fixing-expenses-form, #custom-charges-form, #custom-expenses-form, #load-delivery-form, #car-purchases-form, #leaves-form, #project-report-form, #expenses-deductions-form, #payment-deductions-form, #project-edit-form, #project-form, #branch-transfer-in-form, #branch-transfer-out-form, #lot-move-form, #lot-invoice-sale-form, #lot-sale-form, #lot-purchase-form, #extra-income-form, #quotations-form, #transit-form, #items-settings-form, #payslips-form, #advances-form, #increments-form, #employees-form, #assets-form, #invoices-counters-form, #currency-rates-form, #language-phrase-form, #language-form, #transfer-form, #damage-stock-form, #expenses-form, #expenses-types-form, #sales-form, #production-form, #purchases-form, #items-form, #warehouse-form, #calander-form, #journal-form, #product-category-form, #batch-form, #units-form, #currency-form, #accounts-form, #branches-form, #user-form, #user-edit-form',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	formDomObject = $(this);
	formUnderProcess = $(this).attr('id');

	if(formUnderProcess == 'sets-form')
	{
		if(custom_validation('sets-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'new-production-form')
	{
		if(custom_validation('new-production-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'new-production-formula-form')
	{
		if(custom_validation('new-production-formula-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'production-relation-form')
	{
		if(custom_validation('production-relation-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'production-raw-relation-form')
	{
		if(custom_validation('production-raw-relation-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'production-form')
	{
		if(custom_validation('production-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'production-raw-form')
	{
		if(custom_validation('production-raw-form','cv-required') == false){ console.warn('validation Failed!'); return false; }
	}

	if(formUnderProcess == 'items-form')
	{
		if($.trim($(".opening-stock-rows").html())==''){
			warehouse_missing_error = $('#langs-span').attr('data-opening-stock-warehouse-missing-error');
			warehouse_missing_error_message = $('#langs-span').attr('data-opening-stock-warehouse-missing-message');	

			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error(warehouse_missing_error_message, warehouse_missing_error);
			return false;
		}
	}

	if(formUnderProcess == 'project-expenses-deductions-form')
	{
		if($(this).hasClass('new-form'))
		{
			project_received_money = refine_number($('[name=project_received_money]').val());
			amount = refine_number($('[name=amount]').val());
			if(amount > project_received_money)
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error('Expense amount must be less or equals to '+project_received_money, 'Amount Exceeded');
				return false;
			}
		}
	}
	if(formUnderProcess == 'bookings-form')
	{
		if($('#bookings-table-body .bookings-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some data to Proceed', 'Data Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'debit-credit-note-form')
	{
		if($('#debit-credit-note-table-body .debit-credit-note-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some data to Proceed', 'Data Not Found');
			return false;
		}

		pending = $('.debit-credit-note-totals-col .debit-credit-note-pending-cel input').val();
		pending = refine_number(pending);
		if(pending != 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Make sure pending amount is 0', 'Remaining Amount');
			return false;
		}
	}

	if(formUnderProcess == 'project-report-form')
	{
		// populate text from text editor to textarea
		report_content = $('#summernote').summernote('code');
		$('[name=content]').val(report_content);
	}

	if(formUnderProcess == 'project-form')
	{
		password = $('[name=password]').val();
		confirm_password = $('[name=confirm_password]').val();
		if(password != confirm_password)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Password and confirm password must match.', 'Password Mismatch');
			return false;
		}
	}

	if(formUnderProcess == 'lot-purchase-form')
	{
		lot_purchase_type = $('[name=purchase_type]:checked').val();
		$('[name=lot_purchase_type]').val(lot_purchase_type);

		if($('#lot-purchase-table-body .lot-purchase-table-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some data to Proceed', 'Data Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'b-to-b-transfer-form')
	{
		if($('#b-to-b-transfer-items-table-body .b-to-b-transfer-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some data to Proceed', 'Data Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'car-purchases-form')
	{
		if($('#car-purchases-table-body .car-purchase-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some cars to Proceed', 'Purchases Empty');
			return false;
		}
	}

	if(formUnderProcess == 'purchases-form')
	{
		if($('#purchases-table-body .purchase-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items to Proceed', 'Purchases Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'transfer-in-form')
	{
		if($('#transfer-in-table-body .transfer-in-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items to Proceed', 'Purchases Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'sales-form')
	{
		if($('#sales-items-table-body .sales-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items.', 'Items Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'transfer-out-form')
	{
		if($('#transfer-out-items-table-body .transfer-out-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items.', 'Items Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'services-form')
	{
		if($('#services-items-table-body .services-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items.', 'Items Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'services-quotation-form')
	{
		if($('#services-quotation-items-table-body .services-quotation-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items.', 'Items Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'quotations-form')
	{
		if($('#quotation-items-table-body .quotation-item-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some items.', 'Items Not Found');
			return false;
		}
	}

	if(formUnderProcess == 'transit-form')
	{
		if($('#transit-table-body .transit-row').length == 0)
		{
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Please add some in transit.', 'Transit Empty');
			return false;
		}
	}

	url = $(this).attr('action');
	$('body').addClass('inprocess');
	
	if(formUnderProcess == 'expenses-deductions-form')
	{
		ibox_obj = formDomObject.find('.ibox-content');
	}
	else
	{
		ibox_obj = formDomObject.closest('.ibox-content');
	}

	ibox_obj.addClass('sk-loading');

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: new FormData(this),
		contentType: false,
		processData: false,
		cache: false,
		success: function(data)
		{
			ibox_obj.removeClass('sk-loading');
			$('body').removeClass('inprocess');
			response = JSON.parse(data);

			if(response.status == "success")
			{
				if(response.mood == "new")
				{
					if(formUnderProcess == 'b-to-b-transfer-form')
					{
						$('#b-to-b-transfer-items-table-body').html('');
					}

					if(formUnderProcess == 'sets-form')
					{
						location.reload(true);
					}

					if(formUnderProcess == 'showroom-sales-form')
					{
						window.location.href = response.redirect_url;
						return false;
					}

					if(formUnderProcess == 'buy-cars-sales-form')
					{
						window.location.href = response.redirect_url;
						return false;
					}

					if(formUnderProcess == 'poeple-showroom-sales-form')
					{
						window.location.href = response.redirect_url;
						return false;
					}

					// reset form inputs
					$('#'+formUnderProcess).trigger("reset");

					if(formUnderProcess == 'purchases-cbm-weight-form')
					{
						$("#temp-purchases-form [name=temp_item] option[value='"+response.item+"']").attr('data-item-cbm-width',response.width);
						$("#temp-purchases-form [name=temp_item] option[value='"+response.item+"']").attr('data-item-cbm-height',response.height);
						$("#temp-purchases-form [name=temp_item] option[value='"+response.item+"']").attr('data-item-cbm-length',response.length);
						$("#temp-purchases-form [name=temp_item] option[value='"+response.item+"']").attr('data-item-cbm',response.cbm);
						$("#temp-purchases-form [name=temp_item] option[value='"+response.item+"']").attr('data-item-weight',response.weight);
						$('#purchaseCbmPopup').modal('hide');
					}

					if(formUnderProcess == 'accounts-form')
					{
						$('.shared-account-row').addClass('display-none');
						$('.accounts-form-expended-makups').addClass('display-none');
						$('.client-category-row-expand').addClass('display-none');
						$('[name=type]').html(response.account_type_options);
						$('[name=code]').val(response.code);
						$('#account-opening-balance-wrap').html('');
					}

					if(formUnderProcess == 'journal-form')
					{
						$('[name=receiving_amount]').removeClass('pointer-none').prop('readonly',false);
						$('[name=payment_amount]').removeClass('pointer-none').prop('readonly',false);
					}

					if(formUnderProcess == 'damage-stock-form')
					{
						$('[name=item] option.default-opt').prop('selected',true);
						$('[name=item] option.item-opt').prop('selected',false).addClass('display-none');
						$('[name=unit]').html('<option disabled="" selected="">-- Unit --</option>');
					}

					if(formUnderProcess == 'expenses-deductions-form')
					{
						$('[name=inv_unit]').html('<option disabled="" selected="">-- Unit --</option>');
						$('[name=inv_warehouse]').html('<option disabled="" selected="">-- Warehouse --</option>');
					}

					// re-initialise chosen selects
					$(".chosen-select").trigger('chosen:updated');

					if(formUnderProcess == 'user-form')
					{
						$('#rights-markups-area').removeClass('display-none');
						$('.branch-select-area').removeClass('pointer-none');
					}

					if(formUnderProcess == 'payslips-form')
					{
						$('#earnings-rows-wrapper').html('');
						$('#deductions-rows-wrapper').html('');
					}

					if(formUnderProcess == 'branches-form')
					{
						if(response.in_setup == 'yes')
						{
							window.location.href = response.redirect_url;
						}
					}

					if(formUnderProcess == 'items-form')
					{
						$('[name=item_id]').val(response.get_new_item_id);
						$('[name=warehouse] option').addClass('display-none');
						$('[name=warehouse] [data-opt-type=default]').removeClass('display-none').prop('selected',true);
						$('[name=warehouse]').trigger('chosen:updated');
					}

					if(formUnderProcess == 'lot-purchase-form')
					{
						$('#lot-purchase-table-body').html('');
						$('.purchases-totals-col .purchase-total-cel .cals-span').text('');
						$('.purchases-totals-col .purchase-total-cel .cals-input').val('');
						$('.fixed-fields-row').removeClass('pointer-none');
						$('#temp-lot-purchase-form').trigger("reset");
						$('#temp-lot-purchase-form .chosen-select').trigger('chosen:updated');
						
						$('#division-form-append-area').html('');
						$('#lot-purchase-division-table-body').html('');
						$('#lot-purchase-division-form').trigger('reset');
						// $('.non_iran_to_border').removeClass('display-none');
						// $('.iran_to_border').addClass('display-none');
						$('[name=div_cost]').val('');
						$('[name=pending_weight]').val(response.tankers_new_pending_weight);
						$('#pending-weight-span-elem').text(response.tankers_new_pending_weight);

						$('[name=temp_receipt]').val(response.receipt_num);
						
						// var win = window.open(response.invoice_url, '_blank');
						// win.focus();
					}

					if(formUnderProcess == 'purchases-form')
					{
						$('#purchases-table-body').html('');
						$('.purchases-totals-col .purchase-total-cel .cals-span').text('');
						$('.purchases-totals-col .purchase-total-cel .cals-input').val('');
						$('.fixed-fields-row').removeClass('pointer-none');
						$('#temp-purchases-form').trigger("reset");
						$('#temp-purchases-form .chosen-select').trigger('chosen:updated');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'transfer-in-form')
					{
						$('#transfer-in-table-body').html('');
						$('.transfer-in-totals-col .transfer-in-total-cel .cals-span').text('');
						$('.transfer-in-totals-col .transfer-in-total-cel .cals-input').val('');
						$('.fixed-fields-row').removeClass('pointer-none');
						$('#temp-transfer-in-form').trigger("reset");
						$('#temp-transfer-in-form .chosen-select').trigger('chosen:updated');
						$('[name=temp_invoice]').val(response.invoice_number);
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'debit-credit-note-form')
					{
						$('#debit-credit-note-table-body').html('');
						$('.debit-credit-note-totals-col .debit-credit-note-total-main-cel .cals-span').text('');
						$('.debit-credit-note-totals-col .debit-credit-note-total-main-cel .cals-input').val('');
						$('.debit-credit-note-totals-col .debit-credit-note-total-cel .cals-span').text('');
						$('.debit-credit-note-totals-col .debit-credit-note-total-cel .cals-input').val('');
						$('.debit-credit-note-totals-col .debit-credit-note-pending-cel .cals-span').text('');
						$('.debit-credit-note-totals-col .debit-credit-note-pending-cel .cals-input').val('');
						$('.fixed-fields-row').removeClass('pointer-none');
						$('#temp-debit-credit-form').trigger("reset");
						$('#temp-debit-credit-form .chosen-select').trigger('chosen:updated');
						// $("#temp-debit-credit-form radio[name=type][value=debit]").iCheck('check');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
						location.reload(true);
					}

					if(formUnderProcess == 'bookings-form')
					{
						$('#bookings-table-body').html('');
						$('.bookings-totals-col .bookings-total-amount-row .cals-span').text('');
						$('.bookings-totals-col .bookings-total-amount-row .cals-input').val('');
						$('.fixed-fields-row').removeClass('pointer-none');
						$('#temp-bookings-form').trigger("reset");
						$('#temp-bookings-form .chosen-select').trigger('chosen:updated');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'orders-process-form')
					{
						var win = window.open(response.invoice_url, '_self');
						win.focus();
					}

					if(formUnderProcess == 'car-purchases-form')
					{
						$('#car-purchases-table-body').html('');
						$('.car-purchases-totals-col .purchase-total-cel .cals-span').text('');
						$('.car-purchases-totals-col .purchase-total-cel .cals-input').val('');
						$('.fixed-fields-input').removeClass('pointer-none');
						$('#temp-car-purchases-form').trigger("reset");
						$('#temp-car-purchases-form .chosen-select').trigger('chosen:updated');
						$('[name=temp_invoice]').val(response.invoice_num);
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'fixing-expenses-form')
					{
						$('#fixing-expenses-table-body').html('');
						$('.fixing-expenses-totals-col .purchase-total-cel .cals-span').text('');
						$('.fixing-expenses-totals-col .purchase-total-cel .cals-input').val('');
						$('.fixed-fields-input').removeClass('pointer-none');
						$('#temp-fixing-expenses-form').trigger("reset");
						$('#temp-fixing-expenses-form .chosen-select').trigger('chosen:updated');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'cpurchases-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'sales-form')
					{
						$('#sales-items-table-body').html('');
						$('.sales-totals-box .items-calculations-row .cals-span').text('');
						$('.sales-totals-box .items-calculations-row .cals-input').val('');
						$('.sales-totals-box [name=expense_account]').prop('selectedIndex',0);
						$('.sales-totals-box [name=expense_account]').trigger('chosen:updated');
						$('.sales-fix-row').removeClass('pointer-none');
						$('#sales-items-temp-form').trigger("reset");
						$('#sales-items-temp-form .chosen-select').trigger('chosen:updated');

						$('[name=temp_m2]').val('');
						$('[name=temp_width]').val('').removeClass('pointer-none').prop('readonly',false);
						$('[name=temp_height]').val('').removeClass('pointer-none').prop('readonly',false);

						$('.sales-under-table-totals span').text('');
						$('.sales-under-table-totals input').val('');

						$('[name=temp_invoice]').val(response.invoice_number);

						window.open(response.deliver_note, '_blank');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'transfer-out-form')
					{
						$('#transfer-out-items-table-body').html('');
						$('.transfer-out-fix-row').removeClass('pointer-none');
						$('#transfer-out-items-temp-form').trigger("reset");
						$('#transfer-out-items-temp-form .chosen-select').trigger('chosen:updated');


						$('.transfer-out-under-table-totals span').text('');
						$('.transfer-out-under-table-totals input').val('');
						$('[name=temp_invoice]').val(response.invoice_number);
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'sales-return-form')
					{
						location.reload(true);
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'items-columns-form')
					{
						location.reload(true);
					}

					if(formUnderProcess == 'money-receipts-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}


					if(formUnderProcess == 'services-form')
					{
						$('#services-items-table-body').html('');
						$('.services-totals-box .items-calculations-row .cals-span').text('');
						$('.services-totals-box .items-calculations-row .cals-input').val('');
						$('.services-totals-box [name=cash_received_account]').prop('selectedIndex',0);
						$('.services-totals-box [name=cash_received_account]').trigger('chosen:updated');

						$('#services-form [name=temp_currency]').prop('selectedIndex',0);
						$('#services-form [name=temp_currency]').trigger('chosen:updated');

						$('#services-form [name=temp_currency]').prop('selectedIndex',0);
						$('#services-form [name=temp_currency]').trigger('chosen:updated');

						$('#services-form [name=memo]').val('');

						$('.services-fix-row').removeClass('pointer-none');
						$('#services-items-temp-form').trigger("reset");
						$('#services-items-temp-form .chosen-select').trigger('chosen:updated');

						$('.services-under-table-totals span').text('');
						$('.services-under-table-totals input').val('');

						$('[name=temp_invoice]').val(response.invoice_number);

						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'services-quotation-form')
					{
						$('#services-quotation-items-table-body').html('');
						$('.services-quotation-totals-box .items-calculations-row .cals-span').text('');
						$('.services-quotation-totals-box .items-calculations-row .cals-input').val('');
						$('.services-quotation-totals-box [name=cash_received_account]').prop('selectedIndex',0);
						$('.services-quotation-totals-box [name=cash_received_account]').trigger('chosen:updated');

						$('#services-quotation-form [name=temp_currency]').prop('selectedIndex',0);
						$('#services-quotation-form [name=temp_currency]').trigger('chosen:updated');

						$('#services-quotation-form [name=temp_currency]').prop('selectedIndex',0);
						$('#services-quotation-form [name=temp_currency]').trigger('chosen:updated');

						$('#services-quotation-form [name=memo]').val('');

						$('.services-quotation-fix-row').removeClass('pointer-none');
						$('#services-quotation-items-temp-form').trigger("reset");
						$('#services-quotation-items-temp-form .chosen-select').trigger('chosen:updated');

						$('.services-quotation-under-table-totals span').text('');
						$('.services-quotation-under-table-totals input').val('');

						$('[name=temp_invoice]').val(response.invoice_number);
					}

					if(formUnderProcess == 'quotations-form')
					{
						$('#quotation-items-table-body').html('');
						$('.quotation-fix-row').removeClass('pointer-none');
						$('#quotation-temp-form').trigger("reset");
						$('#quotation-temp-form .chosen-select').trigger('chosen:updated');

						$('[name=temp_m2]').val('');
						$('[name=temp_width]').val('').removeClass('pointer-none').prop('readonly',false);
						$('[name=temp_height]').val('').removeClass('pointer-none').prop('readonly',false);

						$('.quotation-under-table-totals span').text('');
						$('.quotation-under-table-totals input').val('');

						$('[name=temp_invoice]').val(response.invoice_number);

						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'transit-form')
					{
						$('#transit-table-body').html('');
						$('[name=total_amount_by_base_currency]').val('');
						$('[name=total_amount_by_base_currency]').siblings('span').text('0.00');
						$('#transit-temp-form').trigger("reset");
						$('.transit-static-row').removeClass('pointer-none');
						$('#transit-temp-form .chosen-select').trigger('chosen:updated');
						$('[name=temp_transit_serial_num]').val(response.serial_num);
					}

					if(formUnderProcess == 'lot-sale-form')
					{
						child_uid = $('[name=child_uid]').val();
						$('.lotitem'+child_uid).remove();
						$('#lot-sale-modal').modal('hide');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'lot-invoice-sale-form')
					{
						// remove all records of invoice
						tankers = response.tankers.split(',');
						tankers.forEach(function(tuid)
						{
						    $('.lotitem'+tuid).remove();
						});
						$('#lot-invoice-sale-modal').modal('hide');
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'lot-move-form')
					{
						child_uid = $('[name=_move_child_uid]').val();
						$('.lotitem'+child_uid).remove();
						$('#lot-move-modal').modal('hide');
					}

					if(formUnderProcess == 'branch-transfer-out-form')
					{
						// $('#branch-transfer-out-items').prop('selectedIndex',0);
						$('#branch-transfer-out-warehouse').html('<option selected="" disabled="">-- Warehouse --</option>');
						$('#branch-transfer-out-units').html('<option selected="" disabled="">-- Unit --</option>');
						$('#branch-transfer-out-to-warehouse option').addClass('display-none');
						$('#branch-transfer-out-to-warehouse option').first().removeClass('display-none').prop('selected',true);
						// $('#branch-transfer-out-to-warehouse').prop('selectedIndex',0);
						$('#branch-transfer-out-warehouse').trigger('chosen:updated');
						$('#branch-transfer-out-units').trigger('chosen:updated');
						$('#branch-transfer-out-to-warehouse').trigger('chosen:updated');
					}

					if(formUnderProcess == 'branch-transfer-in-form')
					{
						// $('#branch-transfer-out-items').prop('selectedIndex',0);
						$('#branch-transfer-in-to-warehouse option').addClass('display-none');
						$('#branch-transfer-in-to-warehouse option').first().removeClass('display-none').prop('selected',true);
						$('#branch-transfer-in-units').html('<option selected="" disabled="">-- Unit --</option>');
						$('#branch-transfer-in-from-warehouse option').addClass('display-none');
						$('#branch-transfer-in-from-warehouse option').first().removeClass('display-none').prop('selected',true);
						$('#branch-transfer-in-to-warehouse').trigger('chosen:updated');
						$('#branch-transfer-in-units').trigger('chosen:updated');
						$('#branch-transfer-in-from-warehouse').trigger('chosen:updated');
					}

					if(formUnderProcess == 'project-report-form')
					{
						// reset editor
						$('#summernote').summernote('reset');
					}

					if(formUnderProcess == 'ccontracts-form')
					{
						reset_ccontracts_form();
					}

					if(formUnderProcess == 'projects-assign-form')
					{
						reset_project_assign_form();
					}

					if(formUnderProcess == 'new-production-form' || formUnderProcess == 'new-production-formula-form' || formUnderProcess == 'production-form' || formUnderProcess == 'production-raw-form' || formUnderProcess == 'production-relation-form' || formUnderProcess == 'production-raw-relation-form')
					{
						location.reload();
					}
				}

				if(response.mood == "update")
				{
					if(formUnderProcess == 'language-form' || formUnderProcess == 'branches-form')
					{
						location.reload(true);
					}

					if(formUnderProcess == 'sales-out-form')
					{
						location.reload(true);
					}
					
					if(formUnderProcess == 'purchases-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'car-purchases-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'fixing-expenses-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'cpurchases-form')
					{
						var win = window.open(response.invoice_url, '_blank');
						win.focus();
					}

					if(formUnderProcess == 'lot-purchase-form')
					{
						// delete deleted inputs
						$('.is-lot-deleted-iput').remove();
						$('#division-form-append-area').html('');

						// var win = window.open(response.invoice_url, '_blank');
						// win.focus();
					}
				}

				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
				toastr.success(response.message_body, response.message_head);
			}

			if(response.status == "error")
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
				toastr.error(response.message_body, response.message_head);
			}
		},
		error: function(data)
		{
			ibox_obj.removeClass('sk-loading');
			$('body').removeClass('inprocess');
			displayLaravelResponseErrors(data.responseJSON.errors);
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
			toastr.error('System found unprocessable data.', 'Error');
		}
	});
});
// -------------------------------------------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------------------------------------------
// function to display errors sent by laravel validator
function displayLaravelResponseErrors(errors)
{
	$.each(errors, function (key, data)
	{
	    field_name = '[name='+key+']';
	    error_message = '<label id="first_name-error" class="error" for="first_name">'+data+'</label>';
	    $(field_name).addClass('error');
	    $(field_name).attr('aria-required','true');
	    $(field_name).attr('aria-invalid','true');
	    if($(field_name).siblings('label.error').length > 0)
	    {
	    	$(field_name).siblings('label.error').css('display','block').text(data);
	    }
	    else
	    {
	    	$(error_message).insertAfter($(field_name));
	    }
	});
}
// -------------------------------------------------------------------------------------------------------------------------------------




// -------------------------------------------------------------------------------------------------------------------------------------
// live search with enter

$(document).ready(function(e)
{
	var __ls_ajax;

	$(document).on('keyup','[name=_hp_live_search]',function(e)
	{
		// if enter pressed
		if(e.keyCode === 13)
		{
			// abort prev ajax
			if(__ls_ajax != null)
			{
				__ls_ajax.abort();
				console.warn('Ajax Aborted...');
			}

			// process ajax
			_run_search_procedure();
		}
	});

	function _get_url_parameter(name)
	{
	name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
	var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
	var results = regex.exec(location.search);
	final_result = results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
	if($.trim(final_result).length == 0){ final_result = false; }
	return final_result;
	}

	function _get_query_string(search_parammeters)
	{
		if($.trim(search_parammeters).length > 0)
		{
			search_parammeters = search_parammeters.split(',');
		}
		else
		{
			search_parammeters = [];
		}

		var query_vars = [];
		search_parammeters.forEach(function(name)
		{
			value = _get_url_parameter(name);
			if(value != false){ query_vars.push(name+'='+value); }
		});

		if(query_vars.length > 0)
		{
			return query_vars.join('&');
		}
		else
		{
			return false;
		}
	}

	function _run_search_procedure()
	{
		search_value = $('[name=_hp_live_search]').val();
		search_params = $('[name=_hp_live_search]').attr('data-params');
		search_url = $('[name=_hp_live_search]').attr('data-action');
		search_query_string = _get_query_string(search_params);
		ajax_url = search_url+'?_search='+search_value+'&search_type=live_search';
		if(search_query_string != false)
		{
			ajax_url = ajax_url+'&'+search_query_string;
		}

		$('.ibox-content').addClass('sk-loading');
		__ls_ajax = $.ajax(
		{
			url: ajax_url,
			success: function(response)
			{
				$('.ibox-content').removeClass('sk-loading');
				__ls_ajax = null;
				response = JSON.parse(response);
				$('#page-records-body').html(response.records);
				$('#pagination-stats').html(response.stats);
				$('#pagination-pages').html(response.pagination);
			}
		});
	}

});
// -------------------------------------------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------------------------------------------
// search handling functions
function get_query_string(url,iputs_array)
{
	var query_vars = [];
	iputs_array.forEach(function(name)
	{
	    value = $('[name='+name+']').val();
	    if($.trim(value).length > 0){ query_vars.push(name+'='+value); }
	});

	if(query_vars.length > 0)
	{
		query_string = query_vars.join('&');
		url = url+'?'+query_string;
	}

	return url;
}

$(document).on('submit','#turnover-add-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#refund-seach-invoice-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['client','invoice']);
	window.location.href = url;
});

$(document).on('submit','#buy-cars-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#shareholder-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency', 'shareholder','from','to']);
	window.location.href = url;
});

$(document).on('submit','#receipts-approval-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['account','currency']);
	window.location.href = url;
});

$(document).on('submit','#approval-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['module','type']);
	window.location.href = url;
});

$(document).on('submit','#main-approval-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['module']);
	window.location.href = url;
});

$(document).on('submit','#receipts-approvad-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['account','currency','convert_currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#activities-approvad-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['account','currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#my-sales-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#projects-assign-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#citems-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['name','from','to']);
	window.location.href = url;
});

$(document).on('submit','#ccontracts-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#cwarehouses-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['name','from','to']);
	window.location.href = url;
});

$(document).on('submit','#cpurchases-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#tokens-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['client','item']);
	window.location.href = url;
});

$(document).on('submit','#metu-purchases-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#metu-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['metu','from','to']);
	window.location.href = url;
});

$(document).on('submit','#metu-sales-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#accounts-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['root']);
	window.location.href = url;
});

$(document).on('submit','#money-receipts-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','status']);
	window.location.href = url;
});

$(document).on('submit','#activities-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','status']);
	window.location.href = url;
});

$(document).on('submit','#suggestions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['from','to']);
	window.location.href = url;
});

$(document).on('submit','#project-loans-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#showroom-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#fixing-expenses-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','agent','from','to']);
	window.location.href = url;
});

$(document).on('submit','#custom-charges-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','agent','from','to']);
	window.location.href = url;
});

$(document).on('submit','#custom-expenses-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','agent','from','to']);
	window.location.href = url;
});

$(document).on('submit','#load-deliveries-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','account','from','to']);
	window.location.href = url;
});

$(document).on('submit','#car-purchases-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','agent','from','to']);
	window.location.href = url;
});

$(document).on('submit','#leaves-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','user','from','to']);
	window.location.href = url;
});

$(document).on('submit','#projects-reports-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['project','from','to']);
	window.location.href = url;
});

$(document).on('submit','#completed-projects-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#process-details-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','supervisor','type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#approved-expenses-deductions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['expense_type','project_type','currency','project','user','details','from','to']);
	window.location.href = url;
});

$(document).on('submit','#expenses-deductions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['expense_type','project_type','currency','project','user','details','from','to']);
	window.location.href = url;
});

$(document).on('submit','#project-approved-expenses-deductions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','deduction_type','details','from','to']);
	window.location.href = url;
});

$(document).on('submit','#project-expenses-deductions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','deduction_type','details','from','to']);
	window.location.href = url;
});

$(document).on('submit','#payment-deductions-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','project','from','to']);
	window.location.href = url;
});

$(document).on('submit','#project-payments-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','project','from','to']);
	window.location.href = url;
});

$(document).on('submit','#projects-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','project','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#branch-transfer-out-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','warehouse','from','to']);
	window.location.href = url;
});

$(document).on('submit','#branch-transfer-in-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','warehouse','from','to']);
	window.location.href = url;
});

$(document).on('submit','#items-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','category','currency','unit']);
	window.location.href = url;
});

$(document).on('submit','#purchases-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['status','currency','convert_currency','supplier','from','to','user']);
	window.location.href = url;
});

$(document).on('submit','#transfer-in-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['status','currency','convert_currency','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#extra-income-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','type','convert_currency','account','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-available-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','supplier','type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#production-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','item','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','client','marketer','from','to','user','_search',]);
	window.location.href = url;
});

$(document).on('submit','#sales-return-view-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','client', 'marketer','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-return-report-view-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','client', 'marketer','from','to']);
	window.location.href = url;
});

$(document).on('submit','#services-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','client', 'marketer','from','to']);
	window.location.href = url;
});

$(document).on('submit','#expenses-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#all-accounts-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','currency','account','from','to','lot','ledger_type']);
	window.location.href = url;
});

$(document).on('submit','#day-closing-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','account','from','to']);
	window.location.href = url;
});

$(document).on('submit','#transfer-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','warehouse','from','to']);
	window.location.href = url;
});

$(document).on('submit','#journal-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['from','to','account']);
	window.location.href = url;
});

$(document).on('submit','#warehouses-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','unit','from','to']);
	window.location.href = url;
});
$(document).on('submit','#all-bonuses-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-man-recovery-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['from','to','currency','sales_man']);
	window.location.href = url;
});

$(document).on('submit','#damage-items-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','warehouse','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-items-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','item','marketer','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#services-items-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','service','client','from','to']);
	window.location.href = url;
});


$(document).on('submit','#sales-service-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#purchases-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#transfer-in-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-purchases-diff-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','source','currency','supplier','display','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-purchases-pending-fuel-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type','currency','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#purchases-items-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','item','type','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#client-items-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#production-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#warehouse-transfer-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','warehouse','from','to']);
	window.location.href = url;
});

$(document).on('submit','#items-ledger-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','item','unit','from','to']);
	window.location.href = url;
});

$(document).on('submit','#expenses-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#employees-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['division']);
	window.location.href = url;
});

$(document).on('submit','#share-capitals-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','type','from','to']);
	window.location.href = url;
});

$(document).on('submit','#financial-balance-sheet-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','limit_positive','limit_negative']);
	window.location.href = url;
});

$(document).on('submit','#financial-chart-of-accounts-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','limit_positive','limit_negative']);
	window.location.href = url;
});

$(document).on('submit','#financial-trial-balance-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency']);
	window.location.href = url;
});

$(document).on('submit','#financial-cash-flow-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','year']);
	window.location.href = url;
});

$(document).on('submit','#financial-income-statement-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#financial-balance-sheet-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency']);
	window.location.href = url;
});

$(document).on('submit','#incomes-vs-expenses-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#marketers-income-statement-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','from','to','marketer','expense']);
	window.location.href = url;
});

$(document).on('submit','#client-balance-summary-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['type_filter','filter_by','account','from','to','amount_type']);
	window.location.href = url;
});

$(document).on('submit','#assets-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#salary-yearly-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','year']);
	window.location.href = url;
});

$(document).on('submit','#salary-monthly-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','month','year','calander_db']);
	window.location.href = url;
});

$(document).on('submit','#warehouse-details-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['category','currency','unit']);
	window.location.href = url;
});

$(document).on('submit','#inventory-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','category','tpcp','from','to','marketer']);
	window.location.href = url;
});

$(document).on('submit','#audit-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['from','to']);
	window.location.href = url;
});

$(document).on('submit','#sale-stock-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','category','tpcp','from','to','marketer']);
	window.location.href = url;
});

$(document).on('submit','#sale-and-return-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#transit-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','company','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-sold-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['client','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-moved-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','supplier','from','to']);
	window.location.href = url;
});

$(document).on('submit','#lot-diff-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','supplier','display','from','to']);
	window.location.href = url;
});

$(document).on('submit','#projects-assign-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['project','employee','machinery','item','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-man-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to']);
	window.location.href = url;
});

$(document).on('submit','#sales-man-sales-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','convert_currency','client','from','to']);
	window.location.href = url;
});

$(document).on('submit','#debit-credit-note-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','status']);
	window.location.href = url;
});

$(document).on('submit','#debit-credit-voucher-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['currency','from','to','account','type']);
	window.location.href = url;
});

$(document).on('submit','#item-stock-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','from','to','source']);
	window.location.href = url;
});

$(document).on('submit','#stock-general-ledger-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['item','unit']);
	window.location.href = url;
});

$(document).on('submit','#items-by-warehouse-report-search-form',function(e)
{
	e.preventDefault();
	url = $(this).attr('action');
	url = get_query_string(url,['unit']);
	window.location.href = url;
});
// -------------------------------------------------------------------------------------------------------------------------------------





// -------------------------------------------------------------------------------------------------------------------------------------
// handle user role change
$(document).on('change','[name=role]',function(e)
{
	user_role = $('[name=role]').val();
	if(user_role == 'ADMIN')
	{
		$('#rights-markups-area').addClass('display-none');
		$('.branch-select-area').addClass('pointer-none');
	}
	else
	{
		$('#rights-markups-area').removeClass('display-none');
		$('.branch-select-area').removeClass('pointer-none');
	}
});

// handle accounts type change
$(document).on('change','#accounts-form [name=type]',function(e)
{
	account_type = $(this).val();
	if(account_type == 'root' || account_type == '')
	{
		$('.accounts-form-expended-makups').addClass('display-none');
	}
	else
	{
		$('.accounts-form-expended-makups').removeClass('display-none');
	}
	if(account_type == 'client')
	{
		$('.client-category-row-expand').removeClass('display-none');
		$('.customer-user-col-data').removeClass('display-none');
	}
	else
	{
		$('.client-category-row-expand').addClass('display-none');
		$('.customer-user-col-data').addClass('display-none');
	}

	if(account_type == 'cashbook' || account_type == 'client')
	{
		$('.shared-account-row').removeClass('display-none');
	}
	else
	{
		$('.shared-account-row').addClass('display-none');
	}
});


$(document).on('ifChecked','#accounts-form [type=radio][name=client_type]',function(e)
{
	type = $('input[name="client_type"]:checked').val();
	if(type == 'general')
	{
		$('.client-categories-select').addClass('display-none');
		$('.client-sales-man-select').addClass('display-none');
		$('.client-marketer-select').addClass('display-none');
	}

	if(type == 'category')
	{
		$('.client-categories-select').removeClass('display-none');
		$('.client-sales-man-select').addClass('display-none');
		$('.client-marketer-select').addClass('display-none');
	}

	if(type == 'sales_man')
	{
		$('.client-sales-man-select').removeClass('display-none');
		$('.client-categories-select').addClass('display-none');
		$('.client-marketer-select').addClass('display-none');
	}

	if(type == 'marketer')
	{
		$('.client-marketer-select').removeClass('display-none');
		$('.client-sales-man-select').addClass('display-none');
		$('.client-categories-select').addClass('display-none');
	}
});

$(document).on('ifChecked','#accounts-form [type=radio][name=is_user]',function(e)
{
	type = $('input[name="is_user"]:checked').val();
	if(type == 'yes')
	{
		$('#accounts-form input[name=username]').prop('readonly',false);
		$('#accounts-form input[name=password]').prop('readonly',false);
		$('#accounts-form input[name=update_password]').prop('readonly',false);
	}
	else
	{
		$('#accounts-form input[name=username]').val('');
		$('#accounts-form input[name=username]').prop('readonly',true);
		$('#accounts-form input[name=password]').val('');
		$('#accounts-form input[name=password]').prop('readonly',true);
		$('#accounts-form input[name=update_password]').val('');
		$('#accounts-form input[name=update_password]').prop('readonly',true);
	}
});
// -------------------------------------------------------------------------------------------------------------------------------------


$(document).on('change','#items-form [name=type]',function(e)
{
	item_type = $(this).val();
	if(item_type == 'sales')
	{
		$('[name=sale_price]').closest('.form-group').removeClass('display-none');
	}
	else
	{
		$('[name=sale_price]').closest('.form-group').addClass('display-none');
	}
});


// -------------------------------------------------------------------------------------------------------------------------------------
$(document).on('click','#opening-balance-add-trigger',function(e)
{

	// fetch lang
	amount_iput_lang = $(this).attr('data-lang-amount-iput');
	debit_iput_lang = $(this).attr('data-lang-debit-iput');
	credit_iput_lang = $(this).attr('data-lang-credit-iput');
	currency_iput_lang = $(this).attr('data-lang-currency-iput');

	num_rows = $('#account-opening-balance-wrap').find('.currency-row').length;
	num_rows = num_rows+1;
	row_class = 'currency-snippet-row-'+num_rows;
	currency_options = $('#currency-options-wrapper').html();
	html_snippet = '<div class="row extra-mar-botm currency-row '+row_class+'">';
        html_snippet += '<div class="col-md-11">';
            html_snippet += '<div class="row">';
                html_snippet += '<div class="col-md-4">';
                    html_snippet += '<div class="form-group">';
                        html_snippet += '<label>'+debit_iput_lang+'</label>';
                        html_snippet += '<input type="text" class="form-control" name="ob_debit[]" placeholder="'+amount_iput_lang+'">';
                    html_snippet += '</div>';
                html_snippet += '</div>';
                html_snippet += '<div class="col-md-4">';
                    html_snippet += '<div class="form-group">';
                        html_snippet += '<label>'+credit_iput_lang+'</label>';
                        html_snippet += '<input type="text" class="form-control" name="ob_credit[]" placeholder="'+amount_iput_lang+'">';
                    html_snippet += '</div>';
                html_snippet += '</div>';
                html_snippet += '<div class="col-md-4">';
                    html_snippet += '<div class="form-group">';
                        html_snippet += '<label>'+currency_iput_lang+'</label>';
                        html_snippet += '<select class="chosen-select form-control" name="currency[]">';
                        	html_snippet += '<option selected="" disabled="">-- '+currency_iput_lang+' --</option>';
                        	html_snippet += currency_options;
                        html_snippet += '</select>';
                    html_snippet += '</div>';
                html_snippet += '</div>';
            html_snippet += '</div>';
        html_snippet += '</div>';
        html_snippet += '<div class="col-md-1 text-right">';
            html_snippet += '<a href="javascript:void(0);" style="margin-top: 25px;" class="btn btn-outline btn-danger del-opening-balance-row"><i class="fa fa-trash"></i></a>';
        html_snippet += '</div>';
    html_snippet += '</div>';
    $('#account-opening-balance-wrap').append(html_snippet);
    // re-initialise chosen selects
    $("."+row_class+" .chosen-select").chosen({width: "100%"});
    // $("."+row_class+" .chosen-select").trigger('chosen:updated');
});

$(document).on('click','.del-opening-balance-row',function(e)
{
	$(this).closest('.currency-row').remove();
});
// -------------------------------------------------------------------------------------------------------------------------------------




// -------------------------------------------------------------------------------------------------------------------------------------
// journal currency conversion functions

$(document).on('change','#journal-form [name=receiving_currency], #journal-form [name=payment_currency]',function(e)
{
	handle_journal_amounts();
});

$(document).on('keyup','#journal-form [name=receiving_amount], #journal-form [name=rate]',function(e)
{
	handle_journal_amounts();
});
$(document).on('input','#journal-form [name=receiving_amount], #journal-form [name=rate]',function(e)
{
	handle_journal_amounts();
});
$(document).on('ifChecked','#journal-form [type=radio]',function(e)
{
	handle_journal_amounts();
});

function handle_journal_amounts()
{
	receiving_currency = $('[name=receiving_currency]').val();
	payment_currency = $('[name=payment_currency]').val();
	receiving_amount = $('[name=receiving_amount]').val();
	payment_amount = $('[name=payment_amount]').val();
	receiving_amount = refine_number(receiving_amount);
	payment_amount = refine_number(payment_amount);
	

	// apply conversion if we have both currencies
	if($.trim(receiving_currency).length > 0 && $.trim(payment_currency).length > 0)
	{
		// no conversion if both currencies are same
		if(receiving_currency == payment_currency)
		{
			$('[name=rate]').val(1);
			$('.journal-rate-row').addClass('pointer-none');
			$('.journal-rate-row').addClass('display-none');
			if($.trim(receiving_amount).length > 0)
			{
				$('[name=payment_amount]').val(receiving_amount);
				return false;
			}

			if($.trim(payment_amount).length > 0)
			{
				$('[name=receiving_amount]').val(payment_amount);
				return false;
			}
		}
		else
		{
			// detect which amount user entered
			$('.journal-rate-row').removeClass('pointer-none');
			$('.journal-rate-row').removeClass('display-none');
			calculation_type = $('input[name="calculation_type"]:checked').val();
			rate = $('[name=rate]').val();
			rate = refine_number(rate);

			if(calculation_type == 'divide')
			{
				payment_amount = receiving_amount / rate;
				$('[name=payment_amount]').val(payment_amount);
			}
			else
			{
				payment_amount = receiving_amount * rate;
				$('[name=payment_amount]').val(payment_amount);
			}
		}
	}
	else
	{
		$('.journal-rate-row').addClass('display-none');
		if($.trim(receiving_amount).length > 0)
		{
			$('[name=payment_amount]').val(receiving_amount);
			return false;
		}

		if($.trim(payment_amount).length > 0)
		{
			$('[name=receiving_amount]').val(payment_amount);
			return false;
		}
	}
	handle_extra_incomes_from_journal();
}

$(document).on('keyup','#journal-form [name=receiving_amount], #journal-form [name=payment_amount]',function(e)
{
	handle_extra_incomes_from_journal();
});

function handle_extra_incomes_from_journal()
{
	receiving_currency = $('#journal-form [name=receiving_currency] option:selected').val();
	payment_currency = $('#journal-form [name=payment_currency] option:selected').val();
	receiving_amount = refine_number($('#journal-form [name=receiving_amount]').val());
	payment_amount = refine_number($('#journal-form [name=payment_amount]').val());
	extra_income_amount = payment_amount - receiving_amount;
	console.log(payment_amount);
	console.log(receiving_amount);
	console.log(extra_income_amount);
	if($.trim(receiving_currency).length > 0 && $.trim(payment_currency).length > 0)
	{
		if(payment_currency == receiving_currency)
		{
			if(extra_income_amount > 0)
			{
				// now handle extra income functionality
				$('.extra-income-row').removeClass('display-none');
				$('#journal-form [name=extra_income_amount]').val(extra_income_amount);
			}
			else
			{
				$('.extra-income-row').addClass('display-none');
				$('#journal-form [name=extra_income_amount]').val('');
				$('#journal-form [name=extra_income_account]').val('').trigger('chosen:updated');
			}
		}
		else
		{
			$('.extra-income-row').addClass('display-none');
			$('#journal-form [name=extra_income_amount]').val('');
			$('#journal-form [name=extra_income_account]').val('').trigger('chosen:updated');
		}
	}
	else
	{
		$('.extra-income-row').addClass('display-none');
		$('#journal-form [name=extra_income_amount]').val('');
		$('#journal-form [name=extra_income_account]').val('').trigger('chosen:updated');
	}
}


// function handle_journal_amounts()
// {
// 	receiving_currency = $('[name=receiving_currency]').val();
// 	payment_currency = $('[name=payment_currency]').val();
// 	receiving_amount = $('[name=receiving_amount]').val();
// 	payment_amount = $('[name=payment_amount]').val();
// 	receiving_usd_equalance = $('[name=receiving_currency] option:selected').attr('data-rate');
// 	payment_usd_equalance = $('[name=payment_currency] option:selected').attr('data-rate');

// 	// apply conversion if we have both currencies
// 	if($.trim(receiving_currency).length > 0 && $.trim(payment_currency).length > 0)
// 	{
// 		// no conversion if both currencies are same
// 		if(receiving_currency == payment_currency)
// 		{
// 			if($.trim(receiving_amount).length > 0)
// 			{
// 				$('[name=payment_amount]').val(receiving_amount);
// 				return false;
// 			}

// 			if($.trim(payment_amount).length > 0)
// 			{
// 				$('[name=receiving_amount]').val(payment_amount);
// 				return false;
// 			}
// 		}
// 		else
// 		{
// 			// detect which amount user entered
// 			if($('[name=payment_amount]').hasClass('pointer-none'))
// 			{
// 				if($.trim(receiving_amount).length > 0)
// 				{
// 					payment_amount = amount_conversion(receiving_amount, receiving_usd_equalance, payment_usd_equalance);
// 					$('[name=payment_amount]').val(payment_amount);
// 					return false;
// 				}
// 			}

// 			// detect which amount user entered
// 			if($('[name=receiving_amount]').hasClass('pointer-none'))
// 			{
// 				if($.trim(payment_amount).length > 0)
// 				{
// 					receiving_amount = amount_conversion(payment_amount, payment_usd_equalance, receiving_usd_equalance);
// 					$('[name=receiving_amount]').val(receiving_amount);
// 					return false;
// 				}
// 			}
// 		}
// 	}
// 	else
// 	{
// 		if($.trim(receiving_amount).length > 0)
// 		{
// 			$('[name=payment_amount]').val(receiving_amount);
// 			return false;
// 		}

// 		if($.trim(payment_amount).length > 0)
// 		{
// 			$('[name=receiving_amount]').val(payment_amount);
// 			return false;
// 		}
// 	}
// }
// -------------------------------------------------------------------------------------------------------------------------------------




// -------------------------------------------------------------------------------------------------------------------------------------
// setter functions
function round_decimels(amount)
{
	const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, });
	return formatter.format(amount);
}

function round_decimels_3(amount)
{
	const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3, });
	return formatter.format(amount);
}

function round_numbers_3(amount)
{
	amount = parseFloat(amount);
	return amount.toFixed(3);
}

function refine_number(amount)
{
	if($.trim(amount).length == 0){ amount = 0; }
	return parseFloat(amount);
}

function amount_conversion(amount_to_convert, amount_usd_equalance, conversion_usd_equalance)
{
	// amount to convert... Amount which we want to convert according to main currency
	// amount usd eq.. usd equalance of amount currency which we want to convert in main currency
	// coversion usd eq... main currency usd equalance..

	amount_to_convert = parseFloat(amount_to_convert);
	amount_usd_equalance = parseFloat(amount_usd_equalance);
	conversion_usd_equalance = parseFloat(conversion_usd_equalance);

	if(amount_usd_equalance <= 0){ amount_usd_equalance = 1; }
	if(conversion_usd_equalance <= 0){ conversion_usd_equalance = 1; }

	amount_to_usd = amount_to_convert / amount_usd_equalance;
	conversion_amount = amount_to_usd * conversion_usd_equalance;
	return conversion_amount;
}
// -------------------------------------------------------------------------------------------------------------------------------------






// -------------------------------------------------------------------------------------------------------------------------------------
$(document).on('change','#items-form [name=type]',function(e)
{
	item_type = $(this).val();
	// reset
	$('.opening-stock-warehouse [data-opt-type=default]').prop('selected',true);
	$('.opening-stock-warehouse').trigger('chosen:updated');
	// update
	$('.opening-stock-warehouse option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('.opening-stock-warehouse').trigger('chosen:updated');
	$('.opening-stock-rows').html('');
});

$(document).on('click','.opening-stock-trigger-elm',function(e)
{
	e.preventDefault();
	warehouse = $('.opening-stock-warehouse option:selected').val();
	warehouse_name = $('.opening-stock-warehouse option:selected').text();
	qty = $('.opening-stock-qty').val();
	qty = refine_number(qty);

	warehouse_missing_error = $('#langs-span').attr('data-opening-stock-warehouse-missing-error');
	warehouse_missing_error_message = $('#langs-span').attr('data-opening-stock-warehouse-missing-message');
	warehouse_qty_missing_error = $('#langs-span').attr('data-opening-stock-qty-missing-error');
	warehouse_qty_missing_error_message = $('#langs-span').attr('data-opening-stock-qty-missing-message');

	if($.trim(warehouse).length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error(warehouse_missing_error_message, warehouse_missing_error);
		return false;
	}

	if($.trim(qty).length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error(warehouse_qty_missing_error_message, warehouse_qty_missing_error);
		return false;
	}

	html_snippet = '<div class="row extra-mar-botm opening-stock-multiple-row">';

		html_snippet += '<div class="col-md-5">'
			html_snippet += '<input type="hidden" class="form-control" name="warehouse[]" value="'+warehouse+'">';
			html_snippet += '<input type="text" class="form-control" value="'+warehouse_name+'" readonly>';
		html_snippet += '</div>';

		html_snippet += '<div class="col-md-5">'
			html_snippet += '<input type="text" class="form-control" name="opening_stock[]" value="'+qty+'">';
		html_snippet += '</div>';

		html_snippet += '<div class="col-md-2">'
			html_snippet += '<a class="btn btn-danger opening-stock-del-elm" href="javascript:void(0);"><i class="fa fa-trash" style="margin: 0px 8px;"></i></a>';
		html_snippet += '</div>';

	html_snippet += '</div>';

	$('.opening-stock-rows').append(html_snippet);
	$('.opening-stock-warehouse').val('').trigger('chosen:updated');
	$('.opening-stock-qty').val('');
});

$(document).on('click','.opening-stock-del-elm',function()
{
	$(this).closest('.opening-stock-multiple-row').remove();
});
// -------------------------------------------------------------------------------------------------------------------------------------















// -------------------------------------------------------------------------------------------------------------------------------------
// branch transfer functions

$(document).on('change','#branch-transfer-out-branch',function(e)
{
	branch = $(this).val();
	opt_count = 1;
	$('#branch-transfer-out-to-warehouse option').each(function(e)
	{
		if(opt_count == 1)
		{
			$(this).prop('selected',true);
		}
		else
		{
			($(this).attr('data-branch') == branch) ? $(this).removeClass('display-none') : $(this).addClass('display-none');
		}
		opt_count = opt_count+1;
	});
	$('#branch-transfer-out-to-warehouse').trigger('chosen:updated');
});

$(document).on('change','#branch-transfer-in-branch',function(e)
{
	branch = $(this).val();
	opt_count = 1;
	$('#branch-transfer-in-from-warehouse option').each(function(e)
	{
		if(opt_count == 1)
		{
			$(this).prop('selected',true);
		}
		else
		{
			($(this).attr('data-branch') == branch) ? $(this).removeClass('display-none') : $(this).addClass('display-none');
		}
		opt_count = opt_count+1;
	});
	$('#branch-transfer-in-from-warehouse').trigger('chosen:updated');
});

$(document).on('change','#branch-transfer-out-items',function(e)
{
	populate_item_units('#branch-transfer-out-items','#branch-transfer-out-units');
	populate_item_warehouses('#branch-transfer-out-items','#branch-transfer-out-warehouse');
	populate_branch_transfer_out_batch();
});

function populate_branch_transfer_out_batch()
{
	item = $("#branch-transfer-out-form select[name=item] option:selected").val();
	warehouse = $("#branch-transfer-out-form select[name=item] option:selected").attr('data-warehouse');
	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#branch-transfer-out-form [name=batch]').html(response);
			$('#branch-transfer-out-form [name=batch]').trigger('chosen:updated');
		}
	});
}

$(document).on('change','#branch-transfer-in-items',function(e)
{
	populate_item_units('#branch-transfer-in-items','#branch-transfer-in-units');
	display_item_type_warehouses('#branch-transfer-in-items','#branch-transfer-in-to-warehouse');
});

function display_item_type_warehouses(item_input_id,warehouse_input_id)
{
	selected_item_type = $(item_input_id+' option:selected').attr('data-type');
	opt_count = 1;
	$(warehouse_input_id).find('option').each(function(e)
	{
		if(opt_count == 1)
		{
			$(this).prop('selected',true);
		}
		else
		{
			($(this).attr('data-type') == selected_item_type) ? $(this).removeClass('display-none') : $(this).addClass('display-none');
		}
		opt_count = opt_count+1;
	});

	$(warehouse_input_id).trigger('chosen:updated');
}

function populate_item_warehouses(item_input_id,warehouse_input_id)
{
	selected_item_uid = $(item_input_id).val();
	options_snippet = '<option disabled="">-- Warehouse --</option>';
	$(item_input_id).find('option').each(function(e)
	{
		if($(this).attr('value') == selected_item_uid)
		{
			warehouse_uid = $(this).attr('data-warehouse');
			warehouse_name = $(this).attr('data-warehouse-name');
			options_snippet += '<option value="'+warehouse_uid+'">'+warehouse_name+'</option>';
		}
	});

	$(warehouse_input_id).html(options_snippet);
	$(warehouse_input_id).trigger('chosen:updated');
}

function populate_item_units(item_input_id,units_input_id)
{
	purchase_unit = $(item_input_id).find('option:selected').attr('data-purchase-unit');
	sale_unit = $(item_input_id).find('option:selected').attr('data-sale-unit');
	production_unit = $(item_input_id).find('option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $(item_input_id).find('option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $(item_input_id).find('option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $(item_input_id).find('option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit){ options_snippet += '<option value="sale">'+sale_unit+'</option>'; }
	if(production_unit != sale_unit && production_unit != purchase_unit){ options_snippet += '<option value="production">'+production_unit+'</option>'; }

	$(units_input_id).html(options_snippet);
	$(units_input_id).trigger('chosen:updated');
}
// -------------------------------------------------------------------------------------------------------------------------------------












// ------------------------------------------------------------------------------------------------------------------
// purchases functions


$(document).on('click','.purchase-pending-item',function(e)
{
	e.preventDefault();
	$(this).addClass('display-none').siblings('.purchase-passed-item').removeClass('display-none');
	url = $(this).attr('data-url');
	$.ajax({ url: url });
});


$(document).on('change','#temp-purchases-form [name=temp_currency]',function(e)
{
	currency = $(this).val();
	$('[name=temp_expense] option').each(function(e)
	{
		if($(this).hasClass('purchase-exp-first-opt'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			opt_currency = $(this).attr('data-currency');
			if(opt_currency == currency)
			{
				$(this).removeClass('display-none').prop('selected',false);
			}
			else
			{
				$(this).addClass('display-none').prop('selected',false);
			}
		}
	});
	$('[name=temp_expense]').trigger('chosen:updated');
});

$(document).on('keyup','#temp-purchases-form .purchase-item-qty-iput',function(e)
{
	item_qty = $(this).val();
	if($.trim(item_qty).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_qty = refine_number(item_qty);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		total_m2 = m2 * item_qty;

		$('.purchase-item-m2-iput').val(total_m2).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.purchase-item-m2-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('change','#temp-purchases-form [name=temp_pdate]',function(e)
{
	pdate = $(this).val();
	$('.purchase-date-input').val(pdate);
});

$(document).on('keyup','#temp-purchases-form .purchase-item-m2-iput',function(e)
{
	item_m2 = $(this).val();
	if($.trim(item_m2).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_m2 = refine_number(item_m2);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		if(m2 == 0){ m2 = 1; }
		total_qty = item_m2 / m2;

		$('.purchase-item-qty-iput').val(total_qty).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.purchase-item-qty-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('change','#temp-purchases-form [name=temp_item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	item_last_profit = $(this).find('option:selected').attr('data-last-profit');
	item_last_tp = $(this).find('option:selected').attr('data-tp');
	
	item_width = $(this).find('option:selected').attr('data-width');
	item_height = $(this).find('option:selected').attr('data-height');
	qty = $('[name=temp_qty]').val();

	item_width = refine_number(item_width);
	item_height = refine_number(item_height);
	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }

	m2 = item_width * item_height;
	total_m2 = m2 * qty;

	$('[name=temp_width]').val(item_width);
	$('[name=temp_height]').val(item_height);
	$('[name=temp_qty]').val(qty);
	$('[name=temp_m2]').val(total_m2);
	$('[name=temp_cost]').val(item_last_cost);
	$('[name=temp_profit]').val(item_last_profit);
	$('[name=temp_tp]').val(item_last_tp);

	// reset
	$('[name=temp_warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=temp_warehouse]').trigger('chosen:updated');
	// update
	$('[name=temp_warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=temp_warehouse]').trigger('chosen:updated');
	re_populate_punits();
});

function re_populate_punits()
{
	purchase_unit = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#temp-purchases-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#temp-purchases-form [name=temp_unit]').html(options_snippet);
	$('#temp-purchases-form [name=temp_unit]').trigger('chosen:updated');
}

$(document).on('submit','#temp-purchases-form',function(e)
{
	e.preventDefault();

	item_token_status = $('#purchases-form input[name=system_item_token]').val();
	bundle_toop_status = $('#purchases-form input[name=system_bundle_toop]').val();
	distribution_status = $('#purchases-form input[name=system_distribution]').val();
	currency = $('[name=temp_currency]').val();
	pdate = $('[name=temp_pdate]').val();
	supplier = $('[name=temp_supplier]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	item = $('[name=temp_item]').val();
	item_name = $('[name=temp_item] option:selected').text();
	warehouse = $('[name=temp_warehouse]').val();
	warehouse_name = $('[name=temp_warehouse] option:selected').text();
	batch = $('[name=temp_batch]').val();
	mfg = $('[name=temp_mfg]').val();
	expiry = $('[name=temp_expiry]').val();
	cost = $('[name=temp_cost]').val();
	unit = $('[name=temp_unit]').val();
	discount = $('[name=temp_discount]').val();
	profit = $('[name=temp_profit]').val();
	tp = $('[name=temp_tp]').val();
	bonus = $('[name=temp_bonus]').val();
	transport_expense = $('[name=temp_transport_expense]').val();
	expense = $('[name=temp_expense]').val();
	qty = $('[name=temp_qty]').val();
	m2 = $('[name=temp_m2]').val();
	width = $('[name=temp_width]').val();
	height = $('[name=temp_height]').val();

	unit_name = null;
	if(unit == 'purchase'){ unit_name = $('[name=temp_item] option:selected').attr('data-purchase-unit'); }
	if(unit == 'sale'){ unit_name = $('[name=temp_item] option:selected').attr('data-sale-unit'); }
	if(unit == 'production'){ unit_name = $('[name=temp_item] option:selected').attr('data-production-unit'); }

	cost = refine_number(cost);
	qty = refine_number(qty);
	profit = refine_number(profit);
	tp = refine_number(tp);
	transport_expense = refine_number(transport_expense);

	// handle expenses
	if(transport_expense > 0) // if there is expense amount
	{
		// not expense amount allowed without expense account selected
		if($.trim(expense).length == 0){ transport_expense = 0; }else
		{
			transit_pending = $('[name=temp_expense] option:selected').attr('data-pending');
			transit_pending = refine_number(transit_pending);

			// expense amount must be less than transit pending
			if(transport_expense > transit_pending)
			{
				// error
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.error('Expense amount must be less than transit pending amount.', "Amount Exceeded");
				return false;
			}
			else
			{
				// update transit pending amount
				new_transit_pending = transit_pending - transport_expense;
				currency_serial = $('[name=temp_expense] option:selected').attr('data-serial');
				currency_symbol = $('[name=temp_expense] option:selected').attr('data-symbol');
				$('[name=temp_expense] option:selected').text('TS# '+currency_serial+' - '+currency_symbol+round_decimels(new_transit_pending));
				$('[name=temp_expense] option:selected').attr('data-pending',new_transit_pending);
			}
		}
	}

	// calculations
	trans_exp_per_item = parseFloat(transport_expense) / parseFloat(qty);
	real_cost = parseFloat(cost) + trans_exp_per_item;
	sale_price = real_cost + parseFloat(profit);

	if($('[name=temp_width]').length > 0 && $('[name=temp_height]').length > 0)
	{
		total_amount = parseFloat(m2) * parseFloat(cost);
	}
	else
	{
		total_amount = parseFloat(qty) * parseFloat(cost);
	}

	// populate data
	html_snippet = '<tr class="text-center purchase-item-row">';
	    html_snippet += '<td>';
	        html_snippet += item_name;
	        html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
	        html_snippet += '<input type="hidden" class="purchase-date-input" name="pdate[]" value="'+pdate+'">';
	        html_snippet += '<input type="hidden" class="supplier_edit_input" name="supplier[]" value="'+supplier+'">';
	        html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
	        html_snippet += '<input type="hidden" class="memo_p_edit_input" name="memo[]" value="'+memo+'">';
	        html_snippet += '<input type="hidden" name="expense[]" class="expense-transit" value="'+expense+'">';
	        html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
	        html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
	        html_snippet += '<input type="hidden" name="expiry[]" value="'+expiry+'">';
	        html_snippet += '<input type="hidden" name="mfg[]" value="'+mfg+'">';
	        html_snippet += '<input type="hidden" name="item[]" value="'+item+'">';
	        html_snippet += '<input type="hidden" name="bonus[]" value="'+bonus+'">';
	        html_snippet += '<input type="hidden" name="m2[]" value="'+m2+'" class="item-m2-iput">';
	        html_snippet += '<input type="hidden" name="width[]" value="'+width+'" class="item-width-iput">';
	        html_snippet += '<input type="hidden" name="height[]" value="'+height+'" class="item-height-iput">';
	    html_snippet += '</td>';
	    html_snippet += '<td>'+unit_name+' <input type="hidden" name="unit[]" value="'+unit+'"></td>';
	    html_snippet += '<td class="cost-col"><input type="text" class="purchses-editable-iputs" name="cost[]" value="'+cost+'"></td>';
        if(item_token_status == 'enable'){
    	    html_snippet += '<td class="token-rate-col"><input type="text" class="purchses-editable-iputs" name="token_rate[]"></td>';
    	}
	    html_snippet += '<td class="real-cost-col"><span>'+round_decimels(real_cost)+'</span> <input type="hidden" name="real_cost[]" value="'+real_cost+'"></td>';

	    html_snippet += '<td class="qty-col"><input type="text" class="purchses-editable-iputs" name="qty[]" value="'+qty+'"></td>';
        
        if(item_token_status == 'enable'){
    	    html_snippet += '<td><input type="text" name="item_token[]" style="width: 60px;"></td>';
    	}

	    html_snippet += '<td class="profit-col"><input type="text" class="purchses-editable-iputs" name="profit[]" value="'+profit+'"></td>';
	    html_snippet += '<td class="discount-col"><input type="text" class="purchses-editable-iputs" name="discount[]" value="'+discount+'"></td>';
	    html_snippet += '<td class="sale-price-col"><span>'+round_decimels(sale_price)+'</span> <input type="hidden" name="sale_price[]" value="'+sale_price+'"></td>';
	    if(distribution_status == 'enable'){
		    html_snippet += '<td class="tp-col p-tp-col"><input type="text" class="purchses-editable-iputs" name="tp[]" value="'+tp+'"></td>';
		}
	    
	    if(bundle_toop_status == 'enable'){
		    html_snippet += '<td><input type="text" name="bundle[]" style="width: 60px;"></td>';
		    html_snippet += '<td><input type="text" name="toop[]" style="width: 60px;"></td>';
		}

	    html_snippet += '<td class="transport-expense-col"><span>'+round_decimels(transport_expense)+'</span> <input type="hidden" name="transport_expense[]" value="'+transport_expense+'"></td>';
	    html_snippet += '<td class="total-amount-col"><span>'+round_decimels(total_amount)+'</span> <input type="hidden" name="total[]" value="'+total_amount+'"></td>';
	    html_snippet += '<td style="width: 40px;"><a class="btn btn-danger btn-sm purchase-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a></td>';
	html_snippet += '</tr>';

	$('#purchases-table-body').append(html_snippet);

	// reset form inputs
	$('#temp-purchases-form').trigger("reset");

	// populate main fields values
	$('[name=temp_currency] option[value='+currency+']').prop('selected',true);
	$('[name=temp_supplier] option[value='+supplier+']').prop('selected',true);
	$('[name=temp_invoice]').val(invoice);
	$('[name=temp_memo]').val(memo);

	// make main fields readonly
	$('.fixed-fields-row').addClass('pointer-none');

	$('[name=temp_qty]').removeClass('pointer-none').prop('readonly',false);
	$('[name=temp_m2]').removeClass('pointer-none').prop('readonly',false);

	options_snippet = '<option disabled="" selected="">-- Unit --</option>';
	$('[name=temp_unit]').html(options_snippet);

	// update transit dropdown
	$('[name=temp_expense]').prop('selectedIndex',0);

	// re-initialise chosen selects
	$(".chosen-select").trigger('chosen:updated');

	$('[name=temp_warehouse] option').addClass('display-none');
	$('[name=temp_warehouse] [data-opt-type=default]').removeClass('display-none').prop('selected',true);
	$('[name=temp_warehouse]').trigger('chosen:updated');

	handle_purchases_totals();
});

// delete purchase item
$(document).on('click','.purchase-item-del-trigger',function(e)
{
	e.preventDefault();

	// add expense amount to its related transit account
	expense_transit = $(this).closest('.purchase-item-row').find('.expense-transit').val();
	expense_amount = $(this).closest('.purchase-item-row').find('.transport-expense-col').find('input').val();
	if($.trim(expense_transit).length > 0)
	{
		$('[name=temp_expense] option').each(function(e)
		{
			value = $(this).attr('value');
			if(value == expense_transit)
			{
				expense_amount = refine_number(expense_amount);
				transit_pending = $(this).attr('data-pending');
				transit_pending = refine_number(transit_pending);
				new_transit_pending = transit_pending + expense_amount;
				currency_serial = $(this).attr('data-serial');
				currency_symbol = $(this).attr('data-symbol');
				$(this).text('TS# '+currency_serial+' - '+currency_symbol+round_decimels(new_transit_pending));
				$(this).attr('data-pending',new_transit_pending);
			}
		});
	}

	$('[name=temp_expense]').prop('selectedIndex',0);
	$('[name=temp_expense]').trigger('chosen:updated');
	
	$(this).closest('.purchase-item-row').remove();
	handle_purchases_totals();
});


// change purchase item table
$(document).on('keyup','.purchses-editable-iputs',function(e){ handle_purchase_row_alteration($(this)); });
$(document).on('input','.purchses-editable-iputs',function(e){ handle_purchase_row_alteration($(this)); });

function handle_purchase_row_alteration(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.purchase-item-row');

	cost = pointer_parent.find('.cost-col').find('input').val();
	token_rate = pointer_parent.find('.token-rate-col').find('input').val();
	profit = pointer_parent.find('.profit-col').find('input').val();
	transport_expense = pointer_parent.find('.transport-expense-col').find('input').val();
	qty = pointer_parent.find('.qty-col').find('input').val();
	m2 = pointer_parent.find('.item-m2-iput').val();
	width = pointer_parent.find('.item-width-iput').val();
	height = pointer_parent.find('.item-height-iput').val();

	cost = refine_number(cost);
	token_rate = refine_number(token_rate);
	profit = refine_number(profit);
	transport_expense = refine_number(transport_expense);
	qty = refine_number(qty);
	width = refine_number(width);
	height = refine_number(height);

	// calculations
	trans_exp_per_item = transport_expense / qty;
	real_cost = cost + token_rate + trans_exp_per_item;
	sale_price = real_cost + profit;

	if($('[name=temp_width]').length > 0 && $('[name=temp_height]').length > 0)
	{
		m2 = width * height;
		total_m2 = m2 * qty;
		total_amount = total_m2 * cost;
		pointer_parent.find('.item-m2-iput').val(total_m2);
	}
	else
	{
		total_amount = qty * (cost + token_rate);
	}

	pointer_parent.find('.real-cost-col').find('span').text(real_cost);
	pointer_parent.find('.real-cost-col').find('input').val(real_cost);
	pointer_parent.find('.sale-price-col').find('span').text(sale_price);
	pointer_parent.find('.sale-price-col').find('input').val(sale_price);
	pointer_parent.find('.total-amount-col').find('span').text(total_amount);
	pointer_parent.find('.total-amount-col').find('input').val(total_amount);

	handle_purchases_totals();
}


// handle purchases totals after alteration
function handle_purchases_totals()
{
	total_amounts = 0;
	discount_amounts = 0;
	trans_exp_amounts = 0;

	if($('#purchases-table-body .purchase-item-row').length > 0)
	{
		$('#purchases-table-body .purchase-item-row').each(function(e)
		{
			item_total_amount = $(this).find('.total-amount-col').find('input').val();
			item_discount_percent = $(this).find('.discount-col').find('input').val();
			item_trans_exp = $(this).find('.transport-expense-col').find('input').val();
			item_total_amount = refine_number(item_total_amount);
			item_discount_percent = refine_number(item_discount_percent);
			item_trans_exp = refine_number(item_trans_exp);

			item_discount_amount = (item_total_amount * item_discount_percent) / 100;

			total_amounts += item_total_amount;
			discount_amounts += item_discount_amount;
			trans_exp_amounts += item_trans_exp;
		});
	}

	$('.purchases-totals-col .purchases-total-amount-row span').text(round_decimels(total_amounts));
	$('.purchases-totals-col .purchases-total-amount-row input').val(total_amounts);

	$('.purchases-totals-col .purchases-trans-expense-row span').text(round_decimels(trans_exp_amounts));
	$('.purchases-totals-col .purchases-trans-expense-row input').val(trans_exp_amounts);

	$('.purchases-totals-col .purchases-discount-amount-row span').text(round_decimels(discount_amounts));
	$('.purchases-totals-col .purchases-discount-amount-row input').val(discount_amounts);

	sub_total_amount = total_amounts - discount_amounts;
	$('.purchases-totals-col .purchases-sub-total-row span').text(round_decimels(sub_total_amount));
	$('.purchases-totals-col .purchases-sub-total-row input').val(sub_total_amount);

	paid_amount = $('.purchases-totals-col .purchases-paid-amount-row input').val();
	paid_amount = refine_number(paid_amount);
	pending_amount = sub_total_amount - paid_amount;
	$('.purchases-totals-col .purchases-remaining-amount-row span').text(round_decimels(pending_amount));
	$('.purchases-totals-col .purchases-remaining-amount-row input').val(pending_amount);
}


$(document).on('keyup','.purchases-totals-col [name=paid_amount]',function(e){ handle_purchases_totals(); });
$(document).on('input','.purchases-totals-col [name=paid_amount]',function(e){ handle_purchases_totals(); });

// -------------------------------------------------------------------------------------------------------------------------------------



function unit_based_conversion(unit_equalance,unit,convert_amount)
{
	unit_equalance = refine_number(unit_equalance);
    if(unit == 'production')
    {
        convert_amount = convert_amount * unit_equalance;
    }

    if(unit == 'sale')
    {
        convert_amount = convert_amount * unit_equalance;
    }

    return convert_amount;
}

function amount_unit_based_conversion(unit_equalance,unit,convert_amount)
{
	unit_equalance = refine_number(unit_equalance);
    if(unit == 'production')
    {
        convert_amount = convert_amount / unit_equalance;
    }

    if(unit == 'sale')
    {
        convert_amount = convert_amount / unit_equalance;
    }

    return convert_amount;
}



// -------------------------------------------------------------------------------------------------------------------------------------
// production module function

$(document).on('change','.production-currency',function()
{
	currency = $(this).find('option:selected').val();
	currency_usd_equalance = $(this).find('option:selected').attr('data-currency-usd-equalance');

	item_currency = $('#production-raw-items-form [name=temp_raw_item]').find('option:selected').attr('data-currency');
	item_currency_usd_equalance = $('#production-raw-items-form [name=temp_raw_item]').find('option:selected').attr('data-currency-usd-equalance');
	cost = $('[name=temp_raw_item]').find('option:selected').attr('data-cost');
	cost = refine_number(cost);

	if($.trim(currency).length > 0)
	{
		if(currency != item_currency)
		{
			cost = amount_conversion(cost, item_currency_usd_equalance, currency_usd_equalance);
		}
	}

	// $('[name=temp_raw_avail_qty]').attr('data-item-cost',cost);

});

$(document).on('change','.temp_raw_item',function(e)
{
	item = $(this).val();
	item_avail_units = $(this).find('option:selected').attr('data-avail-units');
	item_avg_cost = $(this).find('option:selected').attr('data-cost');
	item_first_cost = $(this).find('option:selected').attr('data-first-cost');

	item_warehouse = $(this).find('option:selected').attr('data-warehouse');

	production_currency = $('.production-currency').val();
	production_currency_usd_equalance = $('.production-currency option:selected').attr('data-currency-usd-equalance');
	item_currency = $(this).find('option:selected').attr('data-currency');
	item_currency_usd_equalance = $(this).find('option:selected').attr('data-currency-usd-equalance');

	// apply conversion if currency selected
	if($.trim(production_currency).length > 0)
	{
		if(production_currency != item_currency)
		{
			item_avg_cost = amount_conversion(item_avg_cost, item_currency_usd_equalance, production_currency_usd_equalance);
			item_first_cost = amount_conversion(item_first_cost, item_currency_usd_equalance, production_currency_usd_equalance);
		}
	}

	// handle currency conversion here
	$('[name=temp_raw_avail_qty]').val(item_avail_units).attr('data-item-cost',item_avg_cost);

	purchase_unit = $('[name=temp_raw_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('[name=temp_raw_item] option:selected').attr('data-sale-unit');
	production_unit = $('[name=temp_raw_item] option:selected').attr('data-production-unit');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch-json',
		data: {item:item,warehouse:item_warehouse},
		success: function(response)
		{
			data = JSON.parse(response);
			console.log(data.options_snippet);
			$('.temp_raw_batch').html(data.options_snippet);
			$('.temp_raw_batch').trigger('chosen:updated');
		}
	});

	$('[name=temp_raw_unit]').html(options_snippet);
	$('[name=temp_raw_unit]').trigger('chosen:updated');

	$('[name=temp_raw_warehouse] option[value='+item_warehouse+']').prop('selected',true);
	$(".chosen-select").trigger('chosen:updated');
});

$(document).on('submit','#production-raw-items-form',function(e)
{
	e.preventDefault();
	currency = $('.production-currency option:selected').val();
	currency_usd_equalance = $('.production-currency option:selected').attr('data-currency-usd-equalance');

	item = $('#production-raw-items-form [name=temp_raw_item] option:selected').val();
	item_name = $('#production-raw-items-form [name=temp_raw_item] option:selected').attr('data-name');
	cost = $('#production-raw-items-form [name=temp_raw_item] option:selected').attr('data-cost');
	item_currency = $('#production-raw-items-form [name=temp_raw_item] option:selected').attr('data-currency');
	item_currency_usd_equalance = $('#production-raw-items-form [name=temp_raw_item] option:selected').attr('data-currency-usd-equalance');
	warehouse = $('#production-raw-items-form [name=temp_raw_warehouse] option:selected').val();
	warehouse_name = $('#production-raw-items-form [name=temp_raw_warehouse] option:selected').text();
	batch = $('#production-raw-items-form [name=temp_raw_batch] option:selected').val();
	ava_qty = $('#production-raw-items-form [name=temp_raw_avail_qty]').val();
	used_qty = $('#production-raw-items-form [name=temp_raw_used_qty]').val();
	damage_qty = $('#production-raw-items-form [name=temp_raw_damage_qty]').val();
	unit = $('#production-raw-items-form [name=temp_raw_unit] option:selected').val();
	unit_name = $('#production-raw-items-form [name=temp_raw_unit] option:selected').text();
	expenses = $('#production-raw-items-form [name=temp_raw_expenses]').val();
	expense_account = $('#production-raw-items-form [name=temp_raw_expense_account] option:selected').val();

	ava_qty = refine_number(ava_qty);
	used_qty = refine_number(used_qty);
	damage_qty = refine_number(damage_qty);
	expenses = refine_number(expenses);

	currency_usd_equalance = refine_number(currency_usd_equalance);
	item_currency_usd_equalance = refine_number(item_currency_usd_equalance);
	// apply conversion if currency selected
	if($.trim(currency).length > 0)
	{
		if(currency != item_currency)
		{
			cost = amount_conversion(cost, item_currency_usd_equalance, currency_usd_equalance);
		}
	}

	real_cost = parseFloat(cost) + parseFloat(expenses);

	total = real_cost * parseFloat(used_qty);
	damage_amount = 0;
	if(damage_qty > 0)
	{
		damage_amount = (total * damage_qty) / 100;
	}

	// populate data
	html_snippet = '<tr class="text-center production-raw-item-row">';
        html_snippet += '<td class="raw-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="raw_item[]" value="'+item+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="expense_account[]" value="'+expense_account+'">';
            html_snippet += '<input type="hidden" name="raw_warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="raw_batch[]" value="'+batch+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-warehouse">';
            html_snippet += '<span>'+unit_name+'</span>';
            html_snippet += '<input type="hidden" name="raw_unit[]" value="'+unit+'">';
            html_snippet += '<input type="hidden" name="raw_ava_qty[]" value="'+ava_qty+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-cost">';
        	html_snippet += '<span>'+round_decimels(cost)+'</span>';
            html_snippet += '<input type="hidden" name="raw_cost[]" value="'+cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-used-qty">';
            html_snippet += '<input type="text" name="raw_qty[]" value="'+used_qty+'" class="production-raw-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-damage-qty">';
            html_snippet += '<input type="text" name="raw_damage[]" value="'+damage_qty+'" class="production-raw-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-expenses">';
            html_snippet += '<input type="text" name="expenses[]" value="'+expenses+'" class="production-raw-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="raw-item-total">';
            html_snippet += '<span>'+round_decimels(total)+'</span>';
            html_snippet += '<input type="hidden" name="raw_total[]" value="'+total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm production-raw-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';


    $('#production-raw-items-table-body').append(html_snippet);
    $('.production-currency-col').addClass('pointer-none');

    // reset form inputs
    $('#production-raw-items-form').trigger("reset");

    options_snippet = '<option disabled="" selected="">-- Select --</option>';
    $('[name=temp_raw_unit]').html(options_snippet);
    $('[name=temp_raw_batch]').html(options_snippet);

    // re-initialise chosen selects
    $("#production-raw-items-form .chosen-select").trigger('chosen:updated');
    handle_production_raw_items_totals();
});


$(document).on('keyup','.production-raw-editable-iputs',function(e)
{
	handle_production_raw_items_row_totals($(this));
});


function handle_production_raw_items_row_totals(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.production-raw-item-row');

	cost = refine_number(pointer_parent.find('.raw-item-cost').find('input').val());
	qty = refine_number(pointer_parent.find('.raw-item-used-qty').find('input').val());
	damage = refine_number(pointer_parent.find('.raw-item-damage-qty').find('input').val());
	expenses = refine_number(pointer_parent.find('.raw-item-expenses').find('input').val());

	real_cost = parseFloat(expenses) + parseFloat(cost);
	total = real_cost * qty;
	damage_amount = 0;
	if(damage > 0)
	{
		damage_amount = (total * damage) / 100;
	}

	total = total + damage_amount;

	pointer_parent.find('.raw-item-total').find('span').text(round_decimels(total));
	pointer_parent.find('.raw-item-total').find('input').val(total);
	handle_production_raw_items_totals();

}

function handle_production_raw_items_totals()
{
	total_damage_cost = 0;
	total_item_cost = 0;
	total_expenses = 0;
	total_raw_cost = 0;
	total_raw_real_cost = 0;
	grand_total_raw = 0;

	if($('#production-raw-items-table-body .production-raw-item-row').length > 0)
	{
		$('#production-raw-items-table-body .production-raw-item-row').each(function(e)
		{
			expenses = refine_number($(this).find('.raw-item-expenses').find('input').val());
			cost = refine_number($(this).find('.raw-item-cost').find('input').val());
			qty = refine_number($(this).find('.raw-item-used-qty').find('input').val());
			damage = refine_number($(this).find('.raw-item-damage-qty').find('input').val());
			total = refine_number($(this).find('.raw-item-total').find('input').val());
			
			real_cost = parseFloat(expenses) + parseFloat(cost);
			total = real_cost * qty;
			expense_total = expenses * qty;
			damage_amount = 0;
			if(damage > 0)
			{
				damage_amount = (total * damage) / 100;
			}
			total = total - damage_amount;
			total_amount = total + damage_amount;

			total_damage_cost += damage_amount;
			total_item_cost += total;
			total_expenses += expense_total;
			total_raw_cost += total_amount;
		});
	}

	$('[name=total_damage]').val(round_numbers_3(total_damage_cost));
	$('[name=total_item_cost]').val(round_numbers_3(total_item_cost));
	$('[name=total_expenses]').val(round_numbers_3(total_expenses));
	$('[name=total_raw_cost]').val(round_numbers_3(total_raw_cost));
}

$(document).on('click','.production-raw-item-del-trigger',function(e)
{
	e.preventDefault();	
	$(this).closest('.production-raw-item-row').remove();
	handle_production_raw_items_totals();
	handle_production_currency_effect();
});

function handle_production_currency_effect()
{
	raw_items_found = false;
	produced_items_found = false;
	if($('#production-raw-items-table-body .production-raw-item-row').length > 0){ raw_items_found = true; }
	if($('#production-produced-items-table-body .production-produced-item-row').length > 0){ produced_items_found = true; }

	if(raw_items_found == false && produced_items_found == false)
	{
		$('.production-currency-col').removeClass('pointer-none');
	}
}






$(document).on('change','#production-produced-items-form [name=temp_produced_item]',function(e)
{
	item = $('#production-produced-items-form [name=temp_produced_item] option:selected').val();
	item_type = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-opt-type');

	purchase_unit = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-sale-unit');
	production_unit = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-production-unit');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('[name=temp_produced_unit]').html(options_snippet);
	$('[name=temp_produced_unit]').trigger('chosen:updated');

	// reset
	$('[name=temp_produced_warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=temp_produced_warehouse]').trigger('chosen:updated');
	// update
	$('[name=temp_produced_warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=temp_produced_warehouse]').val('').trigger('chosen:updated');
});

$(document).on('change','#production-produced-items-form [name=temp_produced_item], #production-produced-items-form [name=temp_produced_warehouse],#production-produced-items-form [name=temp_produced_unit]',function()
{
	handle_produced_item_ava_qty();
});

$(document).on('keyup','#production-produced-items-form [name=temp_produced_batch]',function()
{
	handle_produced_item_ava_qty();
});

function handle_produced_item_ava_qty()
{
	item = $('#production-produced-items-form [name=temp_produced_item] option:selected').val();
	warehouse = $('#production-produced-items-form [name=temp_produced_warehouse] option:selected').val();
	unit = $('#production-produced-items-form [name=temp_produced_unit] option:selected').val();
	batch = $('#production-produced-items-form [name=temp_produced_batch]').val();

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/production/get-produced-item-ava-qty',
		data: {item:item,warehouse:warehouse,batch:batch,unit:unit},
		success: function(response)
		{
			data = JSON.parse(response);
			$('.produced_item_ava_qty').val(data.qty);
		}
	});
}

$(document).on('submit','#production-produced-items-form',function(e)
{
	e.preventDefault();
	if($('#production-raw-items-table-body .production-raw-item-row').length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please add raw items to proceed.', "Raw Item Not Found");
		return false;
	}

	currency = $('#production-raw-items-form [name=currency] option:selected').val();
	currency_usd_equalance = $('#production-raw-items-form [name=currency] option:selected').attr('data-currency-usd-equalance');

	item = $('#production-produced-items-form [name=temp_produced_item] option:selected').val();
	item_name = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-name');
	item_currency = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-currency');
	item_currency_usd_equalance = $('#production-produced-items-form [name=temp_produced_item] option:selected').attr('data-currency-usd-equalance');
	warehouse = $('#production-produced-items-form [name=temp_produced_warehouse] option:selected').val();
	warehouse_name = $('#production-produced-items-form [name=temp_produced_warehouse] option:selected').text();

	unit = $('#production-produced-items-form [name=temp_produced_unit] option:selected').val();
	unit_name = $('#production-produced-items-form [name=temp_produced_unit] option:selected').text();

	batch = $('#production-produced-items-form [name=temp_produced_batch]').val();
	qty = $('#production-produced-items-form [name=temp_produced_qty]').val();
	ava_qty = $('#production-produced-items-form [name=produced_item_ava_qty]').val();

	produced_item_qty = refine_number($('#production-form input[name=total_qty]').val());
	raw_items_cost = refine_number($('#production-form input[name=total_raw_cost]').val());
	qty = refine_number(qty);
	ava_qty = refine_number(ava_qty);

	produced_item_qty_total = produced_item_qty + qty;
	cost = raw_items_cost / produced_item_qty_total;
	profit = 0;

	total = parseFloat(cost) * parseFloat(qty);
	total_profit = parseFloat(profit) * parseFloat(qty);
	$('.produced-item-cost').find('input').val(cost);
	
	// populate data
	html_snippet = '<tr class="text-center production-produced-item-row">';
        html_snippet += '<td class="produced-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="produced_item[]" value="'+item+'">';
            html_snippet += '<input type="hidden" name="produced_currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="produced_warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="produced_batch[]" value="'+batch+'">';
            html_snippet += '<input type="hidden" name="produced_ava_qty[]" value="'+ava_qty+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="produced-item-unit">';
            html_snippet += '<span>'+unit_name+'</span>';
            html_snippet += '<input type="hidden" name="produced_unit[]" value="'+unit+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="produced-item-qty">';
            html_snippet += '<input type="text" name="produced_qty[]" value="'+qty+'" class="production-produced-editable-iputs" style="width: 70px;">';
        html_snippet += '</td>';

        html_snippet += '<td class="ready-item-qty">';
            html_snippet += '<input type="text" name="produced_ready_qty[]" class="production-produced-editable-iputs" style="width: 70px;">';
        html_snippet += '</td>';

        html_snippet += '<td class="produced-item-cost">';
            html_snippet += '<input type="text" name="produced_cost[]" value="'+cost+'" class="production-produced-editable-cost-iputs" style="width: 70px;">';
        html_snippet += '</td>';
        
        html_snippet += '<td class="produced-item-profit">';
            html_snippet += '<input type="text" name="produced_profit[]" value="'+profit+'" class="production-produced-editable-iputs" style="width: 70px;">';
        html_snippet += '</td>';

        html_snippet += '<td class="produced-item-total">';
            html_snippet += '<span>'+round_decimels(total)+'</span>';
            html_snippet += '<input type="hidden" name="produced_total[]" value="'+total+'">';
        html_snippet += '</td>';

        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm production-produced-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';


    $('#production-produced-items-table-body').append(html_snippet);
    $('.production-currency-col').addClass('pointer-none');

    // reset form inputs
    $('#production-produced-items-form').trigger("reset");

    options_snippet = '<option disabled="" selected="">-- Select --</option>';
    $('#production-produced-items-form [name=temp_produced_unit]').html(options_snippet);

    // re-initialise chosen selects
    $("#production-produced-items-form .chosen-select").trigger('chosen:updated');
    handle_production_produced_items_totals();
    handle_produced_items_total_rows();
});

$(document).on('keyup','.production-produced-editable-iputs',function(e)
{
	handle_production_produced_items_row_totals($(this));
});

$(document).on('keyup','.production-produced-editable-cost-iputs',function(e)
{
	handle_production_produced_items_row_totals_cost($(this));
});


function handle_production_produced_items_row_totals(pointer_obj)
{
	handle_produced_items_total_rows();
	// pointer_parent = pointer_obj.closest('.production-produced-item-row');

	// cost = refine_number(pointer_parent.find('.produced-item-cost').find('input').val());
	// qty = refine_number(pointer_parent.find('.produced-item-qty').find('input').val());
	// profit = refine_number(pointer_parent.find('.produced-item-profit').find('input').val());

	// total = parseFloat(cost) * parseFloat(qty);
	// total_profit = parseFloat(profit) * parseFloat(qty);

	// pointer_parent.find('.produced-item-total').find('span').text(round_decimels(total));
	// pointer_parent.find('.produced-item-total').find('input').val(total);

	handle_production_produced_items_totals();

}

function handle_production_produced_items_row_totals_cost(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.production-produced-item-row');

	cost = refine_number(pointer_parent.find('.produced-item-cost').find('input').val());
	qty = refine_number(pointer_parent.find('.produced-item-qty').find('input').val());
	profit = refine_number(pointer_parent.find('.produced-item-profit').find('input').val());

	total = parseFloat(cost) * parseFloat(qty);
	total_profit = parseFloat(profit) * parseFloat(qty);

	pointer_parent.find('.produced-item-total').find('span').text(round_decimels(total));
	pointer_parent.find('.produced-item-total').find('input').val(total);

	handle_production_produced_items_totals();

}


function handle_produced_items_total_rows()
{
	produced_item_qty_total = 0;
	if($('#production-produced-items-table-body .production-produced-item-row').length > 0)
	{
		$('#production-produced-items-table-body .production-produced-item-row').each(function(e)
		{
			all_qty = refine_number($(this).find('.produced-item-qty').find('input').val());
			produced_item_qty_total += all_qty;
		});
	}

	raw_items_cost = refine_number($('#production-form input[name=total_raw_cost]').val());
	cost = raw_items_cost / produced_item_qty_total;
	$('.produced-item-cost').find('input').val(cost);

	if($('#production-produced-items-table-body .production-produced-item-row').length > 0)
	{
		$('#production-produced-items-table-body .production-produced-item-row').each(function(e)
		{
			profit = refine_number($(this).find('.produced-item-profit').find('input').val());
			row_qty = refine_number($(this).find('.produced-item-qty').find('input').val());
			row_total = row_qty * cost;
			$(this).find('.produced-item-total').find('span').text(round_decimels(row_total));
			$(this).find('.produced-item-total').find('input').val(row_total);
		});
	}
}

function handle_production_produced_items_totals()
{
	total_qty = 0;
	total_ready = 0;
	total_pending = 0;
	total_cost = 0;
	total_profit = 0;

	if($('#production-produced-items-table-body .production-produced-item-row').length > 0)
	{
		$('#production-produced-items-table-body .production-produced-item-row').each(function(e)
		{
			total = refine_number($(this).find('.produced-item-total').find('input').val());
			profit = refine_number($(this).find('.produced-item-profit').find('input').val());
			qty = refine_number($(this).find('.produced-item-qty').find('input').val());
			// damage = refine_number($(this).find('.').find('input').val());
			ready_qty = refine_number($(this).find('.ready-item-qty').find('input').val());
			pending_qty = qty - ready_qty;

			total_qty += qty;
			total_ready += ready_qty;
			total_pending += pending_qty;
			total_cost += total;
			total_profit += parseFloat(profit) * parseFloat(qty);
		});
	}

	$('[name=total_qty]').val(total_qty);
	$('[name=ready_qty]').val(total_ready);
	$('[name=pending_qty]').val(total_pending);
	$('[name=total_produced_cost]').val(total_cost);
	$('[name=total_profit]').val(total_profit);
}

$(document).on('click','.production-produced-item-del-trigger',function(e)
{
	e.preventDefault();	
	$(this).closest('.production-produced-item-row').remove();
	handle_produced_items_total_rows();
	handle_production_produced_items_totals();
	handle_production_currency_effect();
});
// -------------------------------------------------------------------------------------------------------------------------------------




// -------------------------------------------------------------------------------------------------------------------------------------
// quotation functions

$(document).on('change','#quotation-temp-form [name=temp_item]',function(e)
{
	item_width = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-width');
	item_height = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-height');
	item_width = refine_number(item_width);
	item_height = refine_number(item_height);

	purchase_unit = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#quotation-temp-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#quotation-temp-form [name=temp_unit]').html(options_snippet);
	$('#quotation-temp-form [name=temp_unit]').trigger('chosen:updated');

	$('#quotation-temp-form [name=temp_width]').val(item_width);
	$('#quotation-temp-form [name=temp_height]').val(item_height);
});

$(document).on('keyup','#quotation-temp-form .sale-item-qty-iput',function(e)
{
	item_qty = $(this).val();
	if($.trim(item_qty).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_qty = refine_number(item_qty);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		total_m2 = m2 * item_qty;

		$('.sale-item-m2-iput').val(total_m2).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.sale-item-m2-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('keyup','#quotation-temp-form .sale-item-m2-iput',function(e)
{
	item_m2 = $(this).val();
	if($.trim(item_m2).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_m2 = refine_number(item_m2);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		if(m2 == 0){ m2 = 1; }
		total_qty = item_m2 / m2;

		$('.sale-item-qty-iput').val(total_qty).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.sale-item-qty-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('submit','#quotation-temp-form',function(e)
{
	e.preventDefault();

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency]').val();
	client_name = $('[name=temp_client] option:selected').text();
	client = $('[name=temp_client]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	batch_name = $('[name=temp_batch] option:selected').text();
	batch = $('[name=temp_batch]').val();
	qty = $('[name=temp_qty]').val();
	narration = $('[name=temp_narration]').val();

	item = $('[name=temp_item]').val();
	item_name = $('[name=temp_item] option:selected').attr('data-item-name');
	item_currency_usd_equalance = $('[name=temp_item] option:selected').attr('data-usd-equalance');
	warehouse = $('[name=temp_item] option:selected').attr('data-warehouse');
	warehouse_name = $('[name=temp_item] option:selected').attr('data-warehouse-name');
	profit = $('[name=temp_item] option:selected').attr('data-profit');
	avg_cost = $('[name=temp_item] option:selected').attr('data-cost');
	avail_units = $('[name=temp_item] option:selected').attr('data-avail-units');
	option_reference = $('[name=temp_item] option:selected').attr('data-opt-ref');

	item_width = $('[name=temp_item] option:selected').attr('data-width');
	item_height = $('[name=temp_item] option:selected').attr('data-height');
	item_m2 = $('[name=temp_m2]').val();

	cash_client_name = $('[name=temp_client_name]').val();
	cash_client_mob = $('[name=temp_client_mobile]').val();
	
	item_width = refine_number(item_width);
	item_height = refine_number(item_height);
	item_m2 = refine_number(item_m2);

	avail_units = refine_number(avail_units);
	avg_cost = refine_number(avg_cost);
	profit = refine_number(profit);
	qty = refine_number(qty);

	// apply unit based conversion
	unit = $('[name=temp_unit]').val();
	unit_name = null;
	unit_equalance = 1;
	if(unit == 'purchase')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-purchase-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-purchase-unit-equalance');
	}

	if(unit == 'sale')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-sale-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-sale-unit-equalance');
	}

	if(unit == 'production')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-production-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-production-unit-equalance');
	}

	avail_units = unit_based_conversion(unit_equalance,unit,avail_units);
	avg_cost = amount_unit_based_conversion(unit_equalance,unit,avg_cost);
	profit = amount_unit_based_conversion(unit_equalance,unit,profit);

	// check if used qty is within avail limit
	if(qty > avail_units)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Item do not have sufficient quantity to sale.', "Insufficient Quantity");
		return false;
	}

	// convert avg cost according to sale currency
	avg_cost = amount_conversion(avg_cost, item_currency_usd_equalance, currency_usd_equalance);
	profit = amount_conversion(profit, item_currency_usd_equalance, currency_usd_equalance);

	sale_price = avg_cost + profit;

	// if measurement enable
	if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
	{
		item_total = sale_price * item_m2;
	}
	else
	{
		item_total = sale_price * qty;
	}

	// populate data
	html_snippet = '<tr class="text-center quotation-item-row">';
        html_snippet += '<td class="quotation-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="item[]" value="'+item+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" class="client_edit_input_q" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" class="memo_edit_input_q" name="memo[]" value="'+memo+'">';
            html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
            html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="narration[]" value="'+narration+'">';
            html_snippet += '<input type="hidden" name="m2[]" value="'+item_m2+'" class="item-m2-iput">';
            html_snippet += '<input type="hidden" name="width[]" value="'+item_width+'" class="item-width-iput">';
            html_snippet += '<input type="hidden" name="height[]" value="'+item_height+'" class="item-height-iput">';
            html_snippet += '<input type="hidden" class="cash_client_name_input_q" name="cash_client_name[]" value="'+cash_client_name+'">';
            html_snippet += '<input type="hidden" class="cash_client_mobile_input_q" name="cash_client_mobile[]" value="'+cash_client_mob+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-warehouse">';
            html_snippet += '<span>'+unit_name+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-cost">';
            html_snippet += '<span>'+round_decimels(avg_cost)+'</span>';
            html_snippet += '<input type="hidden" name="cost[]" value="'+avg_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-sale-price">';
            html_snippet += '<input type="text" name="sale_price[]" value="'+sale_price+'" class="quotation-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-qty">';
            html_snippet += '<input type="text" name="qty[]" value="'+qty+'" class="quotation-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-discount">';
            html_snippet += '<input type="text" name="discount[]" value="" class="quotation-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-profit">';
            html_snippet += '<span>'+round_decimels(profit)+'</span>';
            html_snippet += '<input type="hidden" name="profit[]" value="'+profit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="quotation-item-total">';
            html_snippet += '<span>'+round_decimels(item_total)+'</span>';
            html_snippet += '<input type="hidden" name="item_total[]" value="'+item_total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm quotation-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';
        

	$('#quotation-items-table-body').append(html_snippet);

	$('.quotation-fix-row').addClass('pointer-none');
	$('[name=temp_item]').prop('selectedIndex',0);
	$('[name=temp_item]').trigger('chosen:updated');
	$('[name=temp_batch]').prop('selectedIndex',0);
	$('[name=temp_batch]').trigger('chosen:updated');
	$('[name=temp_qty]').val('');
	$('[name=temp_m2]').val('');
	$('[name=temp_width]').val('').removeClass('pointer-none').prop('readonly',false);
	$('[name=temp_height]').val('').removeClass('pointer-none').prop('readonly',false);
	$('[name=temp_narration]').val('');

	handle_quotation_items_totals_calculation();
});

// delete purchase item
$(document).on('click','.quotation-item-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.quotation-item-row').remove();
	handle_quotation_items_totals_calculation();
});

$(document).on('keyup','.quotation-item-sale-price input, .quotation-item-qty input, .quotation-item-discount input',function(e){ handle_quotation_items_row_alterations($(this)); });
$(document).on('input','.quotation-item-sale-price input, .quotation-item-qty input, .quotation-item-discount input',function(e){ handle_quotation_items_row_alterations($(this)); });

function handle_quotation_items_row_alterations(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.quotation-item-row');
	sale_price = pointer_parent.find('.quotation-item-sale-price').find('input').val();
	cost = pointer_parent.find('.quotation-item-cost').find('input').val();
	qty = pointer_parent.find('.quotation-item-qty').find('input').val();
	discount = pointer_parent.find('.quotation-item-discount').find('input').val();

	sale_price = refine_number(sale_price);
	cost = refine_number(cost);
	qty = refine_number(qty);
	discount = refine_number(discount);

	discount_amount = (sale_price * discount) / 100;
	sale_price = sale_price - discount_amount;
	profit = sale_price - cost;

	if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
	{
		item_width = pointer_parent.find('.item-width-iput').val();
		item_height = pointer_parent.find('.item-height-iput').val();
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);
		m2 = item_width * item_height;
		total_m2 = m2 * qty;
		item_total = sale_price * total_m2;
		pointer_parent.find('.item-m2-iput').val(total_m2);
	}
	else
	{
		item_total = sale_price * qty;
	}

	// populate profit
	pointer_parent.find('.quotation-item-profit').find('input').val(profit);
	pointer_parent.find('.quotation-item-profit').find('span').text(round_decimels(profit));
	// populate item total
	pointer_parent.find('.quotation-item-total').find('input').val(item_total);
	pointer_parent.find('.quotation-item-total').find('span').text(round_decimels(item_total));

	handle_quotation_items_totals_calculation();
}

$(document).on('keyup','.quotation-totals-box .quotation-trans-exp-row input, .quotation-totals-box .quotation-cash-received-row input',function(e){ handle_quotation_items_totals_calculation(); });
$(document).on('input','.quotation-totals-box .quotation-trans-exp-row input, .quotation-totals-box .quotation-cash-received-row input',function(e){ handle_quotation_items_totals_calculation(); });

function handle_quotation_items_totals_calculation()
{
	sales_total = 0;

	total_items_sale_amount = 0;
	total_items_discount_amount = 0;
	total_items_profit_amount = 0;

	if($('#quotation-items-table-body .quotation-item-row').length > 0)
	{
		$('#quotation-items-table-body .quotation-item-row').each(function(e)
		{
			// --------------------------------
			sale_price = $(this).find('.quotation-item-sale-price').find('input').val();
			cost = $(this).find('.quotation-item-cost').find('input').val();
			qty = $(this).find('.quotation-item-qty').find('input').val();
			discount = $(this).find('.quotation-item-discount').find('input').val();

			sale_price = refine_number(sale_price);
			cost = refine_number(cost);
			qty = refine_number(qty);
			discount = refine_number(discount);

			discount_amount = (sale_price * discount) / 100;
			// sale_price = sale_price - discount_amount;
			tb_sale_price = sale_price - discount_amount;
			profit = tb_sale_price - cost;

			if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
			{
				item_width = $(this).find('.item-width-iput').val();
				item_height = $(this).find('.item-height-iput').val();
				item_width = refine_number(item_width);
				item_height = refine_number(item_height);
				m2 = item_width * item_height;
				total_m2 = m2 * qty;
				real_qty = total_m2;
			}
			else
			{
				real_qty = qty;
			}

			item_total_sale_amount = sale_price * real_qty;
			item_total_discount_amount = discount_amount * real_qty;
			item_total_profit_amount = profit * real_qty;

			total_items_sale_amount += item_total_sale_amount;
			total_items_discount_amount += item_total_discount_amount;
			total_items_profit_amount += item_total_profit_amount;
			// --------------------------------

			// --------------------------------
			row_item_total = $(this).find('.quotation-item-total').find('input').val();
			row_item_total = refine_number(row_item_total);
			sales_total += row_item_total;
			// --------------------------------
		});
	}

	// under table row totals
	sale_gross_total_amount = total_items_sale_amount - total_items_discount_amount;

	$('.quotation-under-table-totals .total-sales-cel span').text(round_decimels(total_items_sale_amount));
	$('.quotation-under-table-totals .total-sales-cel input').val(total_items_sale_amount);
	$('.quotation-under-table-totals .total-diss-cel span').text(round_decimels(total_items_discount_amount));
	$('.quotation-under-table-totals .total-diss-cel input').val(total_items_discount_amount);
	$('.quotation-under-table-totals .gross-total-cel span').text(round_decimels(sale_gross_total_amount));
	$('.quotation-under-table-totals .gross-total-cel input').val(sale_gross_total_amount);
	$('.quotation-under-table-totals .total-profit-cel span').text(round_decimels(total_items_profit_amount));
	$('.quotation-under-table-totals .total-profit-cel input').val(total_items_profit_amount);
}
// -------------------------------------------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------------------------------------------
// sales functions

$(document).on('change','#sales-items-temp-form [name=temp_currency], #sales-items-temp-form [name=temp_client]',function()
{
	currency = $('#sales-items-temp-form select[name=temp_currency] option:selected').val();
	client = $('#sales-items-temp-form select[name=temp_client] option:selected').val();
	address = $('#sales-items-temp-form select[name=temp_client] option:selected').attr("data-address");

	$('.customer-address-span-text').text(address);

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/money-receipts/get-client-balance',
		data: {currency:currency,client:client},
		success: function(response)
		{
			$('#sales-client-balance-span').text(response);
		}
	});
});


$(document).on('change','#sales-items-temp-form [name=temp_item]',function(e)
{
	item = $('#sales-items-temp-form [name=temp_item] option:selected').val();
	warehouse = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-warehouse');
	item_width = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-width');
	item_height = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-height');
	item_width = refine_number(item_width);
	item_height = refine_number(item_height);

	purchase_unit = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#sales-items-temp-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#sales-items-temp-form [name=temp_batch]').html(response);
			$('#sales-items-temp-form [name=temp_batch]').trigger('chosen:updated');
		}
	});

	$('#sales-items-temp-form [name=temp_unit]').html(options_snippet);
	$('#sales-items-temp-form [name=temp_unit]').trigger('chosen:updated');

	$('#sales-items-temp-form [name=temp_width]').val(item_width);
	$('#sales-items-temp-form [name=temp_height]').val(item_height);
});

$(document).on('keyup','#sales-items-temp-form .sale-item-qty-iput',function(e)
{
	item_qty = $(this).val();
	if($.trim(item_qty).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_qty = refine_number(item_qty);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		total_m2 = m2 * item_qty;

		$('.sale-item-m2-iput').val(total_m2).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.sale-item-m2-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('keyup','#sales-items-temp-form .sale-item-m2-iput',function(e)
{
	item_m2 = $(this).val();
	if($.trim(item_m2).length > 0)
	{
		item_width = $('[name=temp_width]').val();
		item_height = $('[name=temp_height]').val();

		item_m2 = refine_number(item_m2);
		item_width = refine_number(item_width);
		item_height = refine_number(item_height);

		m2 = item_width * item_height;
		if(m2 == 0){ m2 = 1; }
		total_qty = item_m2 / m2;

		$('.sale-item-qty-iput').val(total_qty).addClass('pointer-none').prop('readonly',true);
	}
	else
	{
		$('.sale-item-qty-iput').val('').removeClass('pointer-none').prop('readonly',false);
	}
});

$(document).on('change','#sales-items-temp-form [name=temp_sdate]', function()
{
	value = $(this).val();
	$('.sales_cr_date').val(value);
});

$(document).on('submit','#sales-items-temp-form',function(e)
{
	e.preventDefault();

	item_token_status = $('#sales-form input[name=system_item_token]').val();
	bundle_toop_status = $('#sales-form input[name=system_bundle_toop]').val();
	distribution_status = $('#sales-form input[name=system_distribution]').val();
	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency]').val();
	sdate = $('[name=temp_sdate]').val();
	client_name = $('[name=temp_client] option:selected').text();
	client = $('[name=temp_client]').val();
	marketer = $('[name=temp_marketer]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	batch_name = $('[name=temp_batch] option:selected').text();
	batch = $('[name=temp_batch]').val();
	bonus = $('[name=temp_bonus]').val();
	qty = $('[name=temp_qty]').val();
	narration = $('[name=temp_narration]').val();
	agent = $('[name=temp_agent]').val();
	plate_num = $('[name=temp_plate_num]').val();

	item = $('[name=temp_item]').val();
	// item unique id for return calculations
	item_uqid = uniqIdGetItem();
	item_name = $('[name=temp_item] option:selected').attr('data-item-name');
	item_currency = $('[name=temp_item] option:selected').attr('data-item-currency');
	item_currency_usd_equalance = $('[name=temp_item] option:selected').attr('data-usd-equalance');
	warehouse = $('[name=temp_item] option:selected').attr('data-warehouse');
	warehouse_name = $('[name=temp_item] option:selected').attr('data-warehouse-name');
	// profit = $('[name=temp_item] option:selected').attr('data-profit');
	profit = $('[name=temp_batch] option:selected').attr('data-profit');
	sale_price = $('[name=temp_batch] option:selected').attr('data-sale-price');
	mfg = $('[name=temp_batch] option:selected').attr('data-mfg');
	expiry = $('[name=temp_batch] option:selected').attr('data-expiry');
	avg_cost = $('[name=temp_item] option:selected').attr('data-cost');
	last_cost = $('[name=temp_item] option:selected').attr('data-last-cost');
	last_profit = $('[name=temp_item] option:selected').attr('data-last-profit');
	// avail_units = $('[name=temp_item] option:selected').attr('data-avail-units');
	avail_units = $('[name=temp_batch] option:selected').attr('data-ava-units');
	option_reference = $('[name=temp_item] option:selected').attr('data-opt-ref');

	item_width = $('[name=temp_item] option:selected').attr('data-width');
	item_height = $('[name=temp_item] option:selected').attr('data-height');
	item_m2 = $('[name=temp_m2]').val();

	cash_client_name = $('[name=temp_client_name]').val();
	cash_client_mob = $('[name=temp_client_mobile]').val();
	
	item_width = refine_number(item_width);
	item_height = refine_number(item_height);
	item_m2 = refine_number(item_m2);

	avail_units = refine_number(avail_units);
	avg_cost = refine_number(avg_cost);
	last_cost = refine_number(last_cost);
	last_profit = refine_number(last_profit);
	profit = refine_number(profit);
	sale_price = refine_number(sale_price);
	qty = refine_number(qty);

	// apply unit based conversion
	unit = $('[name=temp_unit]').val();
	unit_name = null;
	unit_equalance = 1;
	if(unit == 'purchase')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-purchase-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-purchase-unit-equalance');
	}

	if(unit == 'sale')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-sale-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-sale-unit-equalance');
	}

	if(unit == 'production')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-production-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-production-unit-equalance');
	}

	avail_units = unit_based_conversion(unit_equalance,unit,avail_units);
	avg_cost = amount_unit_based_conversion(unit_equalance,unit,avg_cost);
	last_cost = amount_unit_based_conversion(unit_equalance,unit,last_cost);
	last_profit = amount_unit_based_conversion(unit_equalance,unit,last_profit);
	profit = amount_unit_based_conversion(unit_equalance,unit,profit);
	sale_price = amount_unit_based_conversion(unit_equalance,unit,sale_price);
	
	// if item qty is 0 than no avg cost. last cost will be avg cost
	if(avail_units <= 0)
	{
		avg_cost = last_cost;
		profit = last_profit;
		sale_price = avg_cost + profit;
	}

	// check if used qty is within avail limit
	// if(qty > avail_units)
	// {
	// 	toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
	// 	toastr.error('Item do not have sufficient quantity to sale.', "Insufficient Quantity");
	// 	return false;
	// }

	console.log(currency);
	console.log(item_currency);
	console.log(currency_usd_equalance);
	console.log(item_currency_usd_equalance);
	if(currency == item_currency)
	{
		currency_usd_equalance = item_currency_usd_equalance;
	}
	// convert avg cost according to sale currency
	avg_cost = amount_conversion(avg_cost, item_currency_usd_equalance, currency_usd_equalance);
	profit = amount_conversion(profit, item_currency_usd_equalance, currency_usd_equalance);
	sale_price = amount_conversion(sale_price, item_currency_usd_equalance, currency_usd_equalance);
	profit = sale_price - avg_cost;
	// sale_price = avg_cost + profit;

	// if user has no right for system profit than show cost and profit 0
	system_profit = $("#system_profit").val();
	if(system_profit == 'yes')
	{
		system_profit_val = profit;
		system_profit_cost = avg_cost;
	}
	else
	{
		system_profit_val = 0;
		system_profit_cost = 0;
	}

	// if measurement enable
	if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
	{
		item_total = sale_price * item_m2;
	}
	else
	{
		item_total = sale_price * qty;
	}

	

	// populate data
	html_snippet = '<tr class="text-center sales-item-row">';
        html_snippet += '<td class="sales-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="item[]" class="sale-form-item-name" value="'+item+'">';
            html_snippet += '<input type="hidden" name="item_uqid[]" value="'+item_uqid+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="sdate[]" value="'+sdate+'">';
            html_snippet += '<input type="hidden" class="client_edit_input" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" class="marketer_edit_input" name="marketer[]" value="'+marketer+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" class="memo_edit_input" name="memo[]" value="'+memo+'">';
            html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
            html_snippet += '<input type="hidden" name="mfg[]" value="'+mfg+'">';
            html_snippet += '<input type="hidden" name="expiry[]" value="'+expiry+'">';
            html_snippet += '<input type="hidden" name="bonus[]" value="'+bonus+'">';
            html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="narration[]" value="'+narration+'">';
            html_snippet += '<input type="hidden" name="agent[]" value="'+agent+'">';
            html_snippet += '<input type="hidden" name="plate[]" value="'+plate_num+'">';
            html_snippet += '<input type="hidden" name="m2[]" value="'+item_m2+'" class="item-m2-iput">';
            html_snippet += '<input type="hidden" name="width[]" value="'+item_width+'" class="item-width-iput">';
            html_snippet += '<input type="hidden" name="height[]" value="'+item_height+'" class="item-height-iput">';
            html_snippet += '<input type="hidden" class="cash_client_name_input" name="cash_client_name[]" value="'+cash_client_name+'">';
            html_snippet += '<input type="hidden" class="cash_client_mobile_input" name="cash_client_mobile[]" value="'+cash_client_mob+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-warehouse">';
            html_snippet += '<span>'+unit_name+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-cost">';
            html_snippet += '<span>'+round_decimels(system_profit_cost)+'</span>';
            html_snippet += '<input type="hidden" name="cost[]" value="'+avg_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-sale-price">';
            html_snippet += '<input type="text" name="sale_price[]" value="'+sale_price+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-qty">';
            html_snippet += '<input type="text" name="qty[]" value="'+qty+'" class="sales-editable-iputs">';
            html_snippet += '<input type="hidden" name="out_qty[]" value="0">';
            html_snippet += '<input type="hidden" name="out[]" value="0">';
        html_snippet += '</td>';

        html_snippet += '<td class="sales-item-discount">';
            html_snippet += '<input type="text" name="discount[]" value="" class="sales-editable-iputs">';
        html_snippet += '</td>';

        if(distribution_status == 'enable'){
	        html_snippet += '<td class="sales-item-discount-2">';
	            html_snippet += '<input type="text" name="discount_2[]" value="" class="sales-editable-iputs">';
	        html_snippet += '</td>';
	    }

        html_snippet += '<td class="sales-item-profit">';
            html_snippet += '<span>'+round_decimels(system_profit_val)+'</span>';
            html_snippet += '<input type="hidden" name="profit[]" value="'+profit+'">';
        html_snippet += '</td>';
        if(bundle_toop_status == 'enable'){
	        html_snippet += '<td><input type="text" name="bundle[]" style="width: 60px;"></td>';
	        html_snippet += '<td><input type="text" name="toop[]" style="width: 60px;"></td>';
	    }
        if(item_token_status == 'enable'){
	        html_snippet += '<td><input type="text" name="item_token[]" style="width: 60px;"></td>';
	    }
        html_snippet += '<td class="sales-item-total">';
            html_snippet += '<span>'+round_decimels(item_total)+'</span>';
            html_snippet += '<input type="hidden" name="item_total[]" value="'+item_total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm sales-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';
    
    if(avail_units <= 0 || avail_units < qty)
    {
    	swal(
    	{
    	    title: 'Are you sure?',
    	    text: 'Item qty is 0 or less than entered qty!',
    	    html: true,
    	    type: false,
    	    showCancelButton: true,
    	    cancelButtonText: 'Cancel',
    	    confirmButtonColor: "#1ab394",
    	    confirmButtonText: 'Continue',
    	    closeOnConfirm: true
    	},
    	function()
    	{
    		$('#sales-items-table-body').append(html_snippet);

    		$('.sales-fix-row').addClass('pointer-none');
    		$('[name=temp_item]').prop('selectedIndex',0);
    		$('[name=temp_item]').trigger('chosen:updated');
    		$('[name=temp_batch]').prop('selectedIndex',0);
    		$('[name=temp_batch]').trigger('chosen:updated');
    		$('[name=temp_qty]').val('');
    		$('[name=temp_m2]').val('');
    		$('[name=temp_width]').val('').removeClass('pointer-none').prop('readonly',false);
    		$('[name=temp_height]').val('').removeClass('pointer-none').prop('readonly',false);
    		$('[name=temp_narration]').val('');

    		handle_sales_items_totals_calculation();
    	});
    }
    else
    {
    	$('#sales-items-table-body').append(html_snippet);

    	$('.sales-fix-row').addClass('pointer-none');
    	$('[name=temp_item]').prop('selectedIndex',0);
    	$('[name=temp_item]').trigger('chosen:updated');
    	$('[name=temp_batch]').prop('selectedIndex',0);
    	$('[name=temp_batch]').trigger('chosen:updated');
    	$('[name=temp_qty]').val('');
    	$('[name=temp_m2]').val('');
    	$('[name=temp_width]').val('').removeClass('pointer-none').prop('readonly',false);
    	$('[name=temp_height]').val('').removeClass('pointer-none').prop('readonly',false);
    	$('[name=temp_narration]').val('');

    	handle_sales_items_totals_calculation();
    }

	
});


// EXTRA SERVICE FORM
$(document).on('submit','#sales-service-items-temp-form',function(e)
{
	e.preventDefault();

	bundle_toop_status = $('#sales-form input[name=system_bundle_toop]').val();
	distribution_status = $('#sales-form input[name=system_distribution]').val();
	currency = '';
	sdate = '';
	client = '';
	marketer = '';
	invoice = $('[name=temp_invoice]').val();
	memo = '';
	batch = '';
	warehouse = '';
	narration = '';
	item_m2 = '';
	item_width = '';
	item_height = '';
	cash_client_name = '';
	cash_client_mob = '';
	mfg = '';
	expiry = '';
	bonus = '';

	item_name = $('[name=item_description]').val();
	// item unique id for return calculations
	item_uqid = uniqIdGetItem();
	item_val = 'MITNAME_'+item_name;
	unit = $('[name=service_unit]').val();
	qty = $('[name=service_qty]').val();
	cost = $('[name=service_cost]').val();
	sale_price = $('[name=service_sale_price]').val();
	profit = $('[name=service_profit]').val();
	item_name = $('[name=item_description]').val();
	item_total = sale_price * qty;

	// if user has no right for system profit than show cost and profit 0
	system_profit = $("#system_profit").val();
	if(system_profit == 'yes')
	{
		system_profit_val = profit;
		system_profit_cost = cost;
	}
	else
	{
		system_profit_val = 0;
		system_profit_cost = 0;
	}

	// populate data
	html_snippet = '<tr class="text-center sales-item-row">';
        html_snippet += '<td class="sales-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="item[]" class="sale-form-item-name" value="'+item_val+'">';
            html_snippet += '<input type="hidden" name="item_uqid[]" value="'+item_uqid+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="sdate[]" value="'+sdate+'">';
            html_snippet += '<input type="hidden" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" name="marketer[]" value="'+marketer+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" name="memo[]" value="'+memo+'">';
            html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
            html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="narration[]" value="'+narration+'">';
            html_snippet += '<input type="hidden" name="agent[]" value="">';
            html_snippet += '<input type="hidden" name="plate[]" value="">';
            html_snippet += '<input type="hidden" name="mfg[]" value="">';
            html_snippet += '<input type="hidden" name="expiry[]" value="">';
            html_snippet += '<input type="hidden" name="bonus[]" value="">';
            html_snippet += '<input type="hidden" name="m2[]" value="'+item_m2+'" class="item-m2-iput">';
            html_snippet += '<input type="hidden" name="width[]" value="'+item_width+'" class="item-width-iput">';
            html_snippet += '<input type="hidden" name="height[]" value="'+item_height+'" class="item-height-iput">';
            html_snippet += '<input type="hidden" name="cash_client_name[]" value="'+cash_client_name+'">';
            html_snippet += '<input type="hidden" name="cash_client_mobile[]" value="'+cash_client_mob+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-warehouse">';
            html_snippet += '<span>'+unit+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-cost">';
            html_snippet += '<span>'+round_decimels(system_profit_cost)+'</span>';
            html_snippet += '<input type="hidden" name="cost[]" value="'+cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-sale-price">';
            html_snippet += '<input type="text" name="sale_price[]" value="'+sale_price+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-qty">';
            html_snippet += '<input type="text" name="qty[]" value="'+qty+'" class="sales-editable-iputs">';
            html_snippet += '<input type="hidden" name="out_qty[]" value="0">';
            html_snippet += '<input type="hidden" name="out[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="sales-item-discount">';
            html_snippet += '<input type="text" name="discount[]" value="" class="sales-editable-iputs">';
        html_snippet += '</td>';

        if(distribution_status == 'enable'){
	        html_snippet += '<td class="sales-item-discount-2">';
	            html_snippet += '<input type="text" name="discount_2[]" value="" class="sales-editable-iputs">';
	        html_snippet += '</td>';
	    }

	    
        html_snippet += '<td class="sales-item-profit">';
            html_snippet += '<span>'+round_decimels(system_profit_val)+'</span>';
            html_snippet += '<input type="hidden" name="profit[]" value="'+profit+'">';
        html_snippet += '</td>';

        if(bundle_toop_status == 'enable'){
	        html_snippet += '<td><input type="text" name="bundle[]" style="width: 60px;"></td>';
	        html_snippet += '<td><input type="text" name="toop[]" style="width: 60px;"></td>';
	    }
        html_snippet += '<td class="sales-item-total">';
            html_snippet += '<span>'+round_decimels(item_total)+'</span>';
            html_snippet += '<input type="hidden" name="item_total[]" value="'+item_total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm sales-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';
        

	$('#sales-items-table-body').append(html_snippet);
	$('#sales-service-items-temp-form').trigger("reset");
	toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
	toastr.success('Service added to sales.', "Service Added");

	handle_sales_items_totals_calculation();
});

// sales sets form btn
$(document).on('click','.sets-modal-btn',function(e)
{
	e.preventDefault();
	currency = $('#sales-items-temp-form [name=temp_currency] option:selected').val();
	client = $('#sales-items-temp-form [name=temp_client] option:selected').val();
	console.log(currency);
	if(is_empty(currency) == true || is_empty(client) == true)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
		toastr.error('Please select currency and account first to proceed', "No Selection");
		return false;
	}
	$('#sets-modal').modal('show');
});

$(document).on('submit','#sales-sets-form',function(e)
{
	e.preventDefault();
	set_value = $('#sales-sets-form select[name=set_select] option:selected').val();
	currency = $('#sales-items-temp-form [name=temp_currency] option:selected').val();
	currency_usd_equalance = $('#sales-items-temp-form [name=temp_currency] option:selected').attr('data-usd-equalance');
	sdate = $('#sales-items-temp-form [name=temp_sdate]').val();
	client = $('#sales-items-temp-form [name=temp_client] option:selected').val();
	client_name = $('#sales-items-temp-form [name=temp_client] option:selected').text();
	marketer = $('#sales-items-temp-form [name=temp_marketer] option:selected').val();
	invoice = $('#sales-items-temp-form [name=temp_invoice]').val();
	memo = $('#sales-items-temp-form [name=temp_memo]').val();
	cash_client_name = $('#sales-items-temp-form [name=temp_client_name]').val();
	cash_client_mob = $('#sales-items-temp-form [name=temp_client_mobile]').val();

	$('.ibox-content').addClass('sk-loading');
	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-sets-appended-data',
		data: {set_value:set_value,currency:currency,currency_usd_equalance:currency_usd_equalance,sdate:sdate,client:client,client_name:client_name,marketer:marketer,invoice:invoice,memo:memo,cash_client_name:cash_client_name,cash_client_mob:cash_client_mob},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.sales-fix-row').addClass('pointer-none');
			$('#sales-items-table-body').append(response.html);
			$('#sales-sets-form').trigger("reset");
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
			toastr.success('Set added to sales.', "Set Added");
			$('.ibox-content').removeClass('sk-loading');
			handle_sales_items_totals_calculation();
		}
	});
});

// delete purchase item
$(document).on('click','.sales-item-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.sales-item-row').remove();
	handle_sales_items_totals_calculation();
});

$(document).on('keyup','.sales-item-sale-price input, .sales-item-qty input, .sales-item-discount input, .sales-item-discount-2 input ',function(e){ handle_sales_items_row_alterations($(this)); });
$(document).on('input','.sales-item-sale-price input, .sales-item-qty input, .sales-item-discount input, .sales-item-discount-2 input ',function(e){ handle_sales_items_row_alterations($(this)); });

function handle_sales_items_row_alterations(pointer_obj)
{
	console.log('yes');
	pointer_parent = pointer_obj.closest('.sales-item-row');
	sale_price = pointer_parent.find('.sales-item-sale-price').find('input').val();
	cost = pointer_parent.find('.sales-item-cost').find('input').val();
	qty = pointer_parent.find('.sales-item-qty').find('input').val();
	discount = pointer_parent.find('.sales-item-discount').find('input').val();
	discount_2 = pointer_parent.find('.sales-item-discount-2').find('input').val();

	sale_price = refine_number(sale_price);
	cost = refine_number(cost);
	qty = refine_number(qty);
	discount = refine_number(discount);
	discount_2 = refine_number(discount_2);

	discount_amount = (sale_price * discount) / 100;
	discount_2_amount = ((sale_price - discount_amount) * discount_2) / 100;
	sale_price = sale_price - discount_amount;
	profit = sale_price - cost;

	sale_price = sale_price - discount_2_amount;

	if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
	{
		item_width = pointer_parent.find('.item-width-iput').val();
		item_height = pointer_parent.find('.item-height-iput').val();
		item_name = pointer_parent.find('.sale-form-item-name').val();

		// IF SALE ITEM ADDED FROM MODAL
		if(item_name.indexOf('MITNAME_') != -1)
		{
			item_total = sale_price * qty;
		}
		else
		{
			item_width = refine_number(item_width);
			item_height = refine_number(item_height);
			m2 = item_width * item_height;
			total_m2 = m2 * qty;
			item_total = sale_price * total_m2;
			pointer_parent.find('.item-m2-iput').val(total_m2);
		}
	}
	else
	{
		item_total = sale_price * qty;
	}
	// item_total = item_total - discount_2_amount;

	// if user has no right for system profit than show cost and profit 0
	system_profit = $("#system_profit").val();
	if(system_profit == 'yes')
	{
		system_profit_val = profit;
		system_profit_cost = cost;
	}
	else
	{
		system_profit_val = 0;
		system_profit_cost = 0;
	}

	// populate profit
	pointer_parent.find('.sales-item-profit').find('input').val(profit);
	pointer_parent.find('.sales-item-profit').find('span').text(round_decimels(system_profit_val));
	// populate item total
	pointer_parent.find('.sales-item-total').find('input').val(item_total);
	pointer_parent.find('.sales-item-total').find('span').text(round_decimels(item_total));

	handle_sales_items_totals_calculation();
}

$(document).on('keyup','.sales-totals-box .sales-trans-exp-row input, .sales-totals-box .sales-cash-received-row input',function(e){ handle_sales_items_totals_calculation(); });
$(document).on('input','.sales-totals-box .sales-trans-exp-row input, .sales-totals-box .sales-cash-received-row input',function(e){ handle_sales_items_totals_calculation(); });

function handle_sales_items_totals_calculation()
{
	sales_total = 0;

	total_items_sale_amount = 0;
	total_items_discount_amount = 0;
	total_items_discount_2_amount = 0;
	total_items_profit_amount = 0;

	if($('#sales-items-table-body .sales-item-row').length > 0)
	{
		$('#sales-items-table-body .sales-item-row').each(function(e)
		{
			// --------------------------------
			sale_price = $(this).find('.sales-item-sale-price').find('input').val();
			cost = $(this).find('.sales-item-cost').find('input').val();
			qty = $(this).find('.sales-item-qty').find('input').val();
			discount = $(this).find('.sales-item-discount').find('input').val();
			discount_2 = $(this).find('.sales-item-discount-2').find('input').val();

			sale_price = refine_number(sale_price);
			cost = refine_number(cost);
			qty = refine_number(qty);
			discount = refine_number(discount);
			discount_2 = refine_number(discount_2);

			discount_amount = (sale_price * discount) / 100;
			discount_amount_2 = ((sale_price - discount_amount) * discount_2) / 100;
			// sale_price = sale_price - discount_amount;
			tb_sale_price = sale_price - discount_amount;
			profit = tb_sale_price - cost;

			if($('[name=temp_height]').length > 0 && $('[name=temp_width]').length > 0)
			{
				item_width = $(this).find('.item-width-iput').val();
				item_height = $(this).find('.item-height-iput').val();
				item_name = $(this).find('.sale-form-item-name').val();

				// IF SALE ITEM ADDED FROM MODAL
				if(item_name.indexOf('MITNAME_') != -1)
				{
					real_qty = qty;
				}
				else
				{
					item_width = refine_number(item_width);
					item_height = refine_number(item_height);
					m2 = item_width * item_height;
					total_m2 = m2 * qty;
					real_qty = total_m2;
				}
			}
			else
			{
				real_qty = qty;
			}

			item_total_sale_amount = sale_price * real_qty;
			item_total_discount_amount = discount_amount * real_qty;
			item_total_discount_amount_2 = discount_amount_2 * real_qty;
			item_total_profit_amount = profit * real_qty;

			total_items_sale_amount += item_total_sale_amount;
			total_items_discount_amount += item_total_discount_amount;
			total_items_discount_2_amount += item_total_discount_amount_2;
			total_items_profit_amount += item_total_profit_amount;
			// --------------------------------

			// --------------------------------
			row_item_total = $(this).find('.sales-item-total').find('input').val();
			row_item_total = refine_number(row_item_total);
			sales_total += row_item_total;
			// --------------------------------
		});
	}

	// if user has no right for system profit than show cost and profit 0
	system_profit = $("#system_profit").val();
	if(system_profit == 'yes')
	{
		system_profit_val = total_items_profit_amount;
	}
	else
	{
		system_profit_val = 0;
	}

	// under table row totals
	sale_gross_total_amount = total_items_sale_amount - total_items_discount_amount - total_items_discount_2_amount;

	$('.sales-under-table-totals .total-sales-cel span').text(round_decimels(total_items_sale_amount));
	$('.sales-under-table-totals .total-sales-cel input').val(total_items_sale_amount);
	$('.sales-under-table-totals .total-diss-cel span').text(round_decimels(total_items_discount_amount + total_items_discount_2_amount));
	$('.sales-under-table-totals .total-diss-cel input').val(total_items_discount_amount + total_items_discount_2_amount);
	$('.sales-discount-amount-1').val(total_items_discount_amount);
	$('.sales-discount-amount-2').val(total_items_discount_2_amount);
	$('.sales-under-table-totals .gross-total-cel span').text(round_decimels(sale_gross_total_amount));
	$('.sales-under-table-totals .gross-total-cel input').val(sale_gross_total_amount);
	$('.sales-under-table-totals .total-profit-cel span').text(round_decimels(system_profit_val));
	$('.sales-under-table-totals .total-profit-cel input').val(total_items_profit_amount);

	// side table totals
	transport_expenses = $('.sales-totals-box .sales-trans-exp-row input').val();
	cash_received = $('.sales-totals-box .sales-cash-received-row input').val();

	transport_expenses = refine_number(transport_expenses);
	cash_received = refine_number(cash_received);

	sales_sub_total = sales_total + transport_expenses;
	pending_amount = sales_sub_total - cash_received;

	$('.sales-totals-box .sales-total-amount-row input').val(sales_total);
	$('.sales-totals-box .sales-total-amount-row span').text(round_decimels(sales_total));

	$('.sales-totals-box .sales-sub-total-row input').val(sales_sub_total);
	$('.sales-totals-box .sales-sub-total-row span').text(round_decimels(sales_sub_total));

	$('.sales-totals-box .sales-remaining-amount-row input').val(pending_amount);
	$('.sales-totals-box .sales-remaining-amount-row span').text(round_decimels(pending_amount));
}


function uniqIdGetItem(){
  id = 'RTIREM'+Math.round(new Date().getTime() + (Math.random() * 100));
  return id;
}
// -------------------------------------------------------------------------------------------------------------------------------------

$(document).on('keyup','.return-qty-bns-input', function()
{
	pointer_obj = $(this);
	pointer_parent = pointer_obj.closest('.sales-item-row');
	refund_qty = $(this).val();
	qty = $(this).attr('data-bonus');

	refund_qty = refine_number(refund_qty);
	qty = refine_number(qty);
	if(refund_qty > qty)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
		toastr.error('Refund bonus qty must be equal or less than bonus qty', "Qty Exceeded");
		$(this).val(qty);
		return false;
	}
});

$(document).on('keyup','.return-qty-input', function()
{
	pointer_obj = $(this);
	pointer_parent = pointer_obj.closest('.sales-item-row');
	refund_qty = $(this).val();
	sale_price = $(this).attr('data-sale-price');
	qty = $(this).attr('data-qty');
	discount = $(this).attr('data-discount');
	discount_2 = $(this).attr('data-discount-2');

	refund_qty = refine_number(refund_qty);
	sale_price = refine_number(sale_price);
	qty = refine_number(qty);
	discount = refine_number(discount);
	discount_2 = refine_number(discount_2);

	discount_amount = (sale_price * discount) / 100;
	discount_amount_2 = ((sale_price - discount_amount) * discount_2) / 100;
	sale_price = sale_price - discount_amount - discount_amount_2;

	if(refund_qty > qty)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
		toastr.error('Refund qty must be equal or less than sale qty', "Qty Exceeded");
		$(this).val(qty);
		refund_amount = qty * sale_price;
		pointer_parent.find('.return_row_amount').val(refund_amount);
		handle_sales_items_refund_totals_calculation();
		return false;
	}

	refund_amount = refund_qty * sale_price;
	console.log(refund_amount);
	pointer_parent.find('.return_row_amount').val(refund_amount);
	handle_sales_items_refund_totals_calculation();
});


function handle_sales_items_refund_totals_calculation()
{
	refund = 0;
	refund_total = 0;

	if($('#sales-items-table-body .sales-item-row').length > 0)
	{
		$('#sales-items-table-body .sales-item-row').each(function(e)
		{
			// --------------------------------
			refund = $(this).find('.return_row_amount').val();
			refund = refine_number(refund);

			refund_total += refund;
			// --------------------------------
		});
	}

	$('.sales-under-table-totals .total-refund-amount-cel span').text(round_decimels(refund_total));
	$('.sales-under-table-totals .total-sales-cel input[name=total_refund_amount]').val(refund_total);

	$('.sales-totals-box .sales-total-refund-amount-row input').val(refund_total);
	$('.sales-totals-box .sales-total-refund-amount-row span').text(round_decimels(refund_total));
}




// -------------------------------------------------------------------------------------------------------------------------------------
// damage stock functions

$(document).on('change','#damage-stock-form [name=warehouse]',function(e)
{
	warehouse = $(this).val();
	$('#damage-stock-form [name=item] option.default-opt').prop('selected',true);

	// display all items related to this warehouse
	$('#damage-stock-form [name=item] option').each(function(e)
	{
		if($(this).hasClass('item-opt'))
		{
			warehouse_related = $(this).attr("data-warehouse");
			if(warehouse_related === warehouse)
			{
				$(this).removeClass('display-none');
			}
			else
			{
				$(this).addClass('display-none');
			}
		}
	});

	$('#damage-stock-form [name=item]').trigger('chosen:updated');
	$('#damage-stock-form [name=batch]').html('');
	$('#damage-stock-form [name=batch]').trigger('chosen:updated');
	$('#damage-stock-form [name=unit]').html('');
	$('#damage-stock-form [name=unit]').trigger('chosen:updated');
});


$(document).on('change','#damage-stock-form [name=item]',function(e)
{
	purchase_unit = $('#damage-stock-form [name=item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#damage-stock-form [name=item] option:selected').attr('data-sale-unit');
	production_unit = $('#damage-stock-form [name=item] option:selected').attr('data-production-unit');
	purchase_unit_equalance = $('#damage-stock-form [name=item] option:selected').attr('data-purchase-unit-equalance');
	sale_unit_equalance = $('#damage-stock-form [name=item] option:selected').attr('data-sale-unit-equalance');
	production_unit_equalance = $('#damage-stock-form [name=item] option:selected').attr('data-production-unit-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit){
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}
	if(production_unit != sale_unit && production_unit != purchase_unit){
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#damage-stock-form [name=unit]').html(options_snippet);
	$('#damage-stock-form [name=unit]').trigger('chosen:updated');
});

// -------------------------------------------------------------------------------------------------------------------------------------










// -------------------------------------------------------------------------------------------------------------------------------------
// employee functions

$(document).on('click','.today-date-form-trigger',function(e)
{
	e.preventDefault();
	today_date = $(this).attr('data-date');
	$(this).closest('form').find('[name=from]').val(today_date);
	$(this).closest('form').find('[name=to]').val(today_date);
	$(this).closest('form').submit();
});

$(document).on('click','.purchases-status-trigger',function(e)
{
	e.preventDefault();
	status = $(this).attr('data-status');
	$(this).closest('form').find('[name=status]').val(status);
	$(this).closest('form').submit();
});

$(document).on('change','#increments-form [name=employee]',function(e)
{
	father_name = $(this).find('option:selected').attr('data-father-name');
	salary = $(this).find('option:selected').attr('data-salary');

	$('[name=father_name]').val(father_name);
	$('[name=current_salary]').val(salary);
});

$(document).on('change','#advances-form [name=employee]',function(e)
{
	father_name = $(this).find('option:selected').attr('data-father-name');
	previous_advance = $(this).find('option:selected').attr('data-advance');

	$('[name=father_name]').val(father_name);
	$('[name=previous_advance]').val(previous_advance);
	$('[name=new_advance]').trigger('keyup');
});

$(document).on('keyup','#advances-form [name=new_advance]',function(e)
{
	previous_advance = $('[name=previous_advance]').val();
	new_advance = $('[name=new_advance]').val();

	new_advance = refine_number(new_advance);
	previous_advance = refine_number(previous_advance);
	total_advance = new_advance + previous_advance;

	$('[name=total_advance]').val(total_advance);
});

$(document).on('change','#payslips-form [name=employee], #payslips-form [name=pay_date]',function(e)
{
	salary_date = $("#payslips-form [name=pay_date]").val();
	if(salary_date == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
		toastr.error('Please Select Pay Date', "Pay Date Error");
		$("#payslips-form [name=employee]").trigger('chosen:updated');
		$("#payslips-form [name=employee]").val('').trigger('chosen:updated');
		return false;
	}
	father_name = $('#payslips-form [name=employee]').find('option:selected').attr('data-father-name');
	salary = $('#payslips-form [name=employee]').find('option:selected').attr('data-salary');
	advance = $('#payslips-form [name=employee]').find('option:selected').attr('data-advance');
	employee = $('#payslips-form [name=employee]').find('option:selected').val();

	if(employee == ''){return false;}

	$('body').addClass('inprocess');
	url = app_url()+'/payslips/get-holidays-deductions';

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: {employee:employee, salary_date:salary_date, salary:salary},
		success: function(response)
		{
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('[name=father_name]').val(father_name);
				$('[name=basic_salary]').val(salary);
				$('[name=advance_amount]').val(advance);
				$('[name=total_month_days]').val(response.total_days);
				$('[name=total_absents]').val(response.total_absent);
				$('[name=total_deduction_absents]').val(response.total_deduction);
				calculate_payslip_totals();
			}
			if(response.status == 'error')
			{
				$("#payslips-form [name=employee]").trigger('chosen:updated');
				$("#payslips-form [name=employee]").val('').trigger('chosen:updated');
				$('[name=father_name]').val('');
				$('[name=basic_salary]').val('');
				$('[name=advance_amount]').val('');
				$('[name=total_month_days]').val('');
				$('[name=total_absents]').val('');
				$('[name=total_deduction_absents]').val('');
				calculate_payslip_totals();
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error(response.message, 'Error');
			}
		},
		error: function(response)
		{
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});

// add earning inputs
$(document).on('click','#payslips-form #add-earning-trigger',function(e)
{
	lang_earning_name = $('#langs-span').attr('data-earning-name');
	lang_earning_amount = $('#langs-span').attr('data-earning-amount');

	html_snippet = '<div class="row earning-row">';
        html_snippet += '<div class="col-md-5">';
            html_snippet += '<div class="form-group">';
                html_snippet += '<input type="text" class="form-control earning-name" name="earning_name[]" placeholder="'+lang_earning_name+'">';
            html_snippet += '</div>';
        html_snippet += '</div>';
        html_snippet += '<div class="col-md-5">';
            html_snippet += '<div class="form-group">';
                html_snippet += '<input type="text" class="form-control earning-amount" name="earning_amount[]" placeholder="'+lang_earning_amount+'">';
            html_snippet += '</div>';
        html_snippet += '</div>';
        html_snippet += '<div class="col-md-2">';
            html_snippet += '<a href="javascript:void(0);" class="btn btn-danger del-earning-trigger"><i class="fa fa-trash"></i></a>';
        html_snippet += '</div>';
    html_snippet += '</div>';

    $('#earnings-rows-wrapper').append(html_snippet);
});

// add deduction rows
$(document).on('click','#payslips-form #add-deduction-trigger',function(e)
{
	lang_deduction_name = $('#langs-span').attr('data-deduction-name');
	lang_deduction_amount = $('#langs-span').attr('data-deduction-amount');

	html_snippet = '<div class="row deduction-row">';
        html_snippet += '<div class="col-md-5">';
            html_snippet += '<div class="form-group">';
                html_snippet += '<input type="text" class="form-control deduction-name" name="deduction_name[]" placeholder="'+lang_deduction_name+'">';
            html_snippet += '</div>';
        html_snippet += '</div>';
        html_snippet += '<div class="col-md-5">';
            html_snippet += '<div class="form-group">';
                html_snippet += '<input type="text" class="form-control deduction-amount" name="deduction_amount[]" placeholder="'+lang_deduction_amount+'">';
            html_snippet += '</div>';
        html_snippet += '</div>';
        html_snippet += '<div class="col-md-2">';
            html_snippet += '<a href="javascript:void(0);" class="btn btn-danger del-deduction-trigger"><i class="fa fa-trash"></i></a>';
        html_snippet += '</div>';
    html_snippet += '</div>';

    $('#deductions-rows-wrapper').append(html_snippet);
});

// delete earning inputs
$(document).on('click','#payslips-form .del-earning-trigger, #payslips-form .del-deduction-trigger',function(e)
{
	e.preventDefault();
    $(this).closest('.row').remove();
    calculate_payslip_totals();
});

$(document).on('keyup','#payslips-form .earning-amount, #payslips-form .deduction-amount',function(e)
{
    calculate_payslip_totals();
});

function calculate_payslip_totals()
{
	// earnings
	basic_salary = $('[name=basic_salary]').val();
	basic_salary = refine_number(basic_salary);
	earnings = basic_salary;
	$('#earnings-rows-wrapper .earning-row').each(function(e)
	{
		earning_amount = $(this).find('.earning-amount').val();
		earning_amount = refine_number(earning_amount);
		earnings += earning_amount;
	});

	// deductions
	advance_amount = $('[name=advance_amount]').val();
	advance_amount = refine_number(advance_amount);

	total_deduction = $('[name=total_deduction_absents]').val();
	total_deduction = refine_number(total_deduction);
	deductions = advance_amount + total_deduction;
	$('#deductions-rows-wrapper .deduction-row').each(function(e)
	{
		deduction_amount = $(this).find('.deduction-amount').val();
		deduction_amount = refine_number(deduction_amount);
		deductions += deduction_amount;
	});

	$('[name=total_earning]').val(earnings);
	$('[name=total_deduction]').val(deductions);
	$('[name=net_salary]').val(earnings - deductions);

}

// -------------------------------------------------------------------------------------------------------------------------------------





// -------------------------------------------------------------------------------------------------------------------------------------
// transit functions

$(document).on('submit','#transit-temp-form',function(e)
{
	e.preventDefault();

	base_currency = $('[name=temp_base_currency]').val();
	base_currency_usd_equalance = $('[name=temp_base_currency] option:selected').attr('data-usd-equalance');
	transit_date = $('[name=temp_transit_date]').val();
	serial_num = $('[name=temp_transit_serial_num]').val();
	builty_num = $('[name=temp_builty_num]').val();
	company = $('[name=temp_transit_company]').val();

	account = $('[name=temp_account]').val();
	account_name = $('[name=temp_account] option:selected').text();
	currency = $('[name=temp_currency]').val();
	currency_name = $('[name=temp_currency] option:selected').attr('data-name');
	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	amount = $('[name=temp_amount]').val();
	expense_narration = $('[name=temp_expense_narration]').val();

	// amount_by_base_currency
	amount = refine_number(amount);
	currency_usd_equalance = refine_number(currency_usd_equalance);
	amount_by_base_currency = amount / currency_usd_equalance;

	// fetch row count
	if($('#transit-table-body .transit-row').length > 0)
	{
		last_row_name = $('#transit-table-body .transit-row').last().find('.transit-currency-rate').find('.first-opt').find('input').attr('name');
		transit_row_count = refine_number(last_row_name);
	}
	else
	{
		transit_row_count = $('#transit-table-body .transit-row').length;
	}
	transit_row_count = transit_row_count+1;


	html_snippet = '<tr class="text-center transit-row">';
        html_snippet += '<td class="transit-expense-narration">';
            html_snippet += '<span>'+expense_narration+'</span>';
            html_snippet += '<input type="hidden" name="expense_narration[]" value="'+expense_narration+'">';
            html_snippet += '<input type="hidden" name="base_currency[]" value="'+base_currency+'">';
            html_snippet += '<input type="hidden" name="base_currency_usd_equalance[]" value="'+base_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="transit_date[]" value="'+transit_date+'">';
            html_snippet += '<input type="hidden" name="serial_num[]" value="'+serial_num+'">';
            html_snippet += '<input type="hidden" name="builty_num[]" value="'+builty_num+'">';
            html_snippet += '<input type="hidden" name="company[]" value="'+company+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="transit-account">';
            html_snippet += '<span>'+account_name+'</span>';
            html_snippet += '<input type="hidden" name="account[]" value="'+account+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="transit-currency">';
            html_snippet += '<span>'+currency_name+'</span>';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="transit-currency-rate">';
            // html_snippet += '<span>'+round_decimels(currency_usd_equalance)+'</span>&nbsp;&nbsp;';
            html_snippet += '<input type="text" name="rate[]" value="'+currency_usd_equalance+'" class="rate-amount transit-editable-iput" style="margin-right:10px;">';
            html_snippet += '<label class="checkbox-inline i-checks first-opt"><input type="radio" name="'+transit_row_count+'" value="multiply">&nbsp;<span style="font-size: 23px;display: inline-block;vertical-align: middle;line-height: 22px;">×</span></label>';
            html_snippet += '<label class="checkbox-inline i-checks second-opt"><input type="radio" name="'+transit_row_count+'" value="divide" checked="checked">&nbsp;<span style="font-size: 23px;display: inline-block;vertical-align: middle;line-height: 22px;">÷</span></label>';
            // html_snippet += '<input type="hidden" name="rate[]" class="rate-amount" value="'+currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="rate_type[]" class="rate-type" value="divide">';
        html_snippet += '</td>';
        html_snippet += '<td class="transit-amount">';
            html_snippet += '<input type="text" name="amount[]" value="'+amount+'" class="transit-editable-iput">';
        html_snippet += '</td>';
        html_snippet += '<td class="transit-by-base-currency">';
            html_snippet += '<span>'+round_decimels(amount_by_base_currency)+'</span>';
            html_snippet += '<input type="hidden" name="by_base_currency[]" value="'+amount_by_base_currency+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm transit-row-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';

    $('#transit-table-body').append(html_snippet);

    // re-initialise i-checks
    $('#transit-table-body .i-checks').iCheck({checkboxClass: 'icheckbox_square-green',radioClass: 'iradio_square-green'});

    // after settings
    $('.transit-static-row').addClass('pointer-none');
    $('[name=temp_account]').prop('selectedIndex',0);
    $('[name=temp_account]').trigger('chosen:updated');
    $('[name=temp_currency]').prop('selectedIndex',0);
    $('[name=temp_currency]').trigger('chosen:updated');
    $('[name=temp_amount]').val('');
    $('[name=temp_expense_narration]').val('');

    handle_transit_total_exp_amount();
});

$(document).on('ifChecked','.transit-row [type=radio]',function(e)
{
	name = $(this).attr('name');
	rate_type = $('[name='+name+']:checked').attr('value');
	$(this).closest('td').find('.rate-type').val(rate_type);
	handle_transit_row_alteration($(this).closest('.transit-row'));
});

$(document).on('keyup input','.transit-row .transit-editable-iput',function(e){ handle_transit_row_alteration($(this).closest('.transit-row')); });

function handle_transit_row_alteration(parent_obj)
{
	amount = parent_obj.find('.transit-amount').find('input').val();
	currency_rate = parent_obj.find('.transit-currency-rate').find('.rate-amount').val();
	currency_rate_type = parent_obj.find('.transit-currency-rate').find('.rate-type').val();

	amount = refine_number(amount);
	currency_rate = refine_number(currency_rate);

	if(currency_rate_type == 'multiply')
	{
		amount_by_base_currency = amount * currency_rate;
	}
	else
	{
		amount_by_base_currency = amount / currency_rate;
	}

	parent_obj.find('.transit-by-base-currency').find('span').text(round_decimels(amount_by_base_currency));
	parent_obj.find('.transit-by-base-currency').find('input').val(amount_by_base_currency);
	handle_transit_total_exp_amount();
}

function handle_transit_total_exp_amount()
{
	total_amount_by_base_currency = 0;
	$('#transit-table-body .transit-row').each(function(e)
	{
		amount_by_base_currency = $(this).find('.transit-by-base-currency').find('input').val();
		amount_by_base_currency = refine_number(amount_by_base_currency);
		total_amount_by_base_currency += amount_by_base_currency;
	});
	$('[name=total_amount_by_base_currency]').val(total_amount_by_base_currency);
	$('[name=total_amount_by_base_currency]').siblings('span').text(round_decimels(total_amount_by_base_currency));
}

$(document).on('click','.transit-row-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.transit-row').remove();
	handle_transit_total_exp_amount();
});
// -----------------------------------------------------------------------------------------------------------------------

// SALES CASSH SALE CLIENT
$(document).on("change","#sales-add-client-dropdown, #quotation-add-client-dropdown",function()
{
	client_id = $(this).val();
	cash_sale = 'CASHSALE';
	// CHECK IF VALUE HAS STRING CASHSALE
	if(client_id.indexOf(cash_sale) != -1)
	{
		$("#cash-sale-client-info-row").css("display","block");
	}
	else
	{
		$("#cash-sale-client-info-row").css("display","none");
	}
});
$(document).on('keyup input','#service_cost, #service_sale_price', function()
{
	calculate_extra_profit();
});
function calculate_extra_profit()
{
	cost = $("#service_cost").val();
	sale_price = $("#service_sale_price").val();
	if($.trim(cost).length == 0){ cost = 0; }
	if($.trim(sale_price).length == 0){ sale_price = 0; }
	profit = parseFloat(sale_price) - parseFloat(cost);
	$("#service_profit").val(profit);
}

$(document).on("change",".temp_client_edit, .temp_marketer_edit",function(){update_sale_client();});
$(document).on("keyup input",".temp_memo_edit, .temp_client_name_edit, .temp_client_mobile_edit",function(){update_sale_client();});

function update_sale_client()
{
	client = $(".temp_client_edit").find(":selected").val();
	marketer = $(".temp_marketer_edit").find(":selected").val();
	memo = $(".temp_memo_edit").val();
	name = $(".temp_client_name_edit").val();
	mob = $(".temp_client_mobile_edit").val();
	$('.client_edit_input').val(client);
	$('.marketer_edit_input').val(marketer);
	$('.memo_edit_input').val(memo);
	$('.cash_client_name_input').val(name);
	$('.cash_client_mobile_input').val(mob);
}

$(document).on("change",".temp_client_edit_q",function(){update_quotation();});
$(document).on("keyup input",".temp_memo_edit_q, .temp_client_name_edit_q, .temp_client_mobile_edit_q",function(){update_quotation();});

function update_quotation()
{
	client = $(".temp_client_edit_q").find(":selected").val();
	memo = $(".temp_memo_edit_q").val();
	name = $(".temp_client_name_edit_q").val();
	mob = $(".temp_client_mobile_edit_q").val();
	$('.client_edit_input_q').val(client);
	$('.memo_edit_input_q').val(memo);
	$('.cash_client_name_input_q').val(name);
	$('.cash_client_mobile_input_q').val(mob);
}

$(document).on("change",".temp_supplier_edit",function(){update_purchase_supplier();});
$(document).on("keyup input",".temp_p_memo_edit",function(){update_purchase_supplier();});

function update_purchase_supplier()
{
	client = $(".temp_supplier_edit").find(":selected").val();
	memo = $(".temp_p_memo_edit").val();
	$('.supplier_edit_input').val(client);
	$('.memo_p_edit_input').val(memo);
}





// CHECK ALL RIGHTS
$(document).on('change','#check-all-rights',function(e)
{
	if($(this).is(':checked'))
	{
		$('.rights-row').find('td').find('[type=checkbox]').prop('checked',true);
	}
	else
	{
		$('.rights-row').find('td').find('[type=checkbox]').prop('checked',false);
	}
});

// check all module rights
$(document).on('change','.all-module-checker',function(e)
{
	if($(this).is(':checked'))
	{
		$(this).closest('tr').siblings('tr').find('[type=checkbox]').prop('checked',true);
	}
	else
	{
		$(this).closest('tr').siblings('tr').find('[type=checkbox]').prop('checked',false);
	}
});














// -----------------------------------------------------------------------------------------------------------------------
// lot module scripting


// trigger attach file in lot purchase
$(document).on('click','#email-attachment-file-trigger',function(e)
{
	$('#email-attachment-file-iput').trigger('click');
});

// lot purchase type handling
$(document).on('ifChecked','#lot-purchase-type-btns [type=radio]',function(e)
{
	type = $('#lot-purchase-type-btns [type=radio]:checked').val();
	if(type == 'iran_to_border')
	{
		$('.non_iran_to_border').addClass('display-none');
		$('.iran_to_border').removeClass('display-none');
	}
	else
	{
		$('.non_iran_to_border').removeClass('display-none');
		$('.iran_to_border').addClass('display-none');
	}
	clear_lot_purchase_relations();
	clear_division_relations();
});

function clear_lot_purchase_relations()
{
	$('#lot-purchase-table-body').html('');
	$('.purchases-totals-col .purchase-total-cel .cals-span').text('');
	$('.purchases-totals-col .purchase-total-cel .cals-input').val('');
}

function clear_division_relations()
{
	$('#lot-purchase-division-table-body').html('');
	$('.purchases-totals-col .purchase-total-cel .cals-span').text('');
	$('.purchases-totals-col .purchase-total-cel .cals-input').val('');
	$('[name=div_cost]').val('');
}




// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// calculate real and total cost in lot purchase
$(document).on('keyup input','#temp-lot-purchase-form .clratc',function(e){ calculate_lot_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form [name=temp_currency]',function(e){ calculate_lot_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form [name=temp_rent_currency]',function(e){ calculate_lot_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form [name=temp_expenses_currency]',function(e){ calculate_lot_real_and_total_costs(); });
function calculate_lot_real_and_total_costs()
{
	base_currency = $('[name=temp_currency]').val();
	base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	weight = $('[name=temp_weight]').val();
	cost = $('[name=temp_cost]').val();
	rent = $('[name=temp_rent]').val();
	rent_currency = $('[name=temp_rent_currency]').val();
	rent_currency_usd_equalance = $('[name=temp_rent_currency] option:selected').attr('data-usd-equalance');
	expenses = $('[name=temp_expenses]').val();
	expenses_currency = $('[name=temp_expenses_currency]').val();
	expenses_currency_usd_equalance = $('[name=temp_expenses_currency] option:selected').attr('data-usd-equalance');

	base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
	rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
	expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);
	weight = refine_number(weight);
	cost = refine_number(cost);
	rent = refine_number(rent);
	expenses = refine_number(expenses);

	// convert rent if currency not same
	if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
	{
		if(base_currency != rent_currency)
		{
			rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	// convert expenses if currency not same
	if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
	{
		if(base_currency != expenses_currency)
		{
			expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	real_cost = cost + rent + expenses;
	total_cost = real_cost * weight;

	$('[name=temp_real_cost]').val(real_cost);
	$('[name=temp_total_cost]').val(total_cost);
}
// --------------------------------------------------------------------------------------------

// submit lot temp form
$(document).on('submit','#temp-lot-purchase-form',function(e)
{
	e.preventDefault();

	var rowCount = $('#lot-purchase-table tr').length;
	lot_purchase_type = $('[name=purchase_type]:checked').val();
	expenses_readonly = '';
	if(lot_purchase_type == 'iran_to_border')
	{
		expenses_readonly = 'readonly="readonly"';
	}

	temp_currency = $('[name=temp_currency]').val();
	temp_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	temp_supplier = $('[name=temp_supplier]').val();
	temp_date = $('[name=temp_date]').val();
	temp_receipt = $('[name=temp_receipt]').val();
	temp_transit_account = $('[name=temp_transit_account]').val();
	temp_expense_account = $('[name=temp_expense_account]').val();
	temp_fuel_type = $('[name=temp_fuel_type]').val();
	temp_driver = $('[name=temp_driver]').val();
	temp_mobile = $('[name=temp_mobile]').val();
	temp_plate_num = $('[name=temp_plate_num]').val();
	temp_cmr = $('[name=temp_cmr]').val();
	temp_weight = $('[name=temp_weight]').val();
	temp_cost = $('[name=temp_cost]').val();
	temp_rent = $('[name=temp_rent]').val();
	temp_rent_currency = $('[name=temp_rent_currency]').val();
	temp_rent_currency_usd_equalance = $('[name=temp_rent_currency] option:selected').attr('data-usd-equalance');
	temp_expenses = $('[name=temp_expenses]').val();
	temp_expenses_currency = $('[name=temp_expenses_currency]').val();
	temp_expenses_currency_usd_equalance = $('[name=temp_expenses_currency] option:selected').attr('data-usd-equalance');
	temp_real_cost = $('[name=temp_real_cost]').val();
	temp_total_cost = $('[name=temp_total_cost]').val();

	if($.trim(temp_rent_currency).length == 0)
	{
		temp_rent_currency = temp_currency;
		temp_rent_currency_usd_equalance = temp_currency_usd_equalance;
	}

	if($.trim(temp_expenses_currency).length == 0)
	{
		temp_expenses_currency = temp_currency;
		temp_expenses_currency_usd_equalance = temp_currency_usd_equalance;
	}

	// html snippet
	html_snippet = '<tr class="text-center lot-purchase-table-row">';
		html_snippet += '<td>'+rowCount+'</td>'
        html_snippet += '<td class="lot-row-fuel-type">';
            html_snippet += '<span>'+temp_fuel_type+'</span> ';
            html_snippet += '<input type="hidden" name="fuel_type[]" value="'+temp_fuel_type+'">';
            html_snippet += '<input type="hidden" name="uid[]" value="">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+temp_currency+'">';
            html_snippet += '<input type="hidden" name="currency_usd_equalance[]" value="'+temp_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="supplier[]" value="'+temp_supplier+'">';
            html_snippet += '<input type="hidden" name="date[]" value="'+temp_date+'">';
            html_snippet += '<input type="hidden" name="receipt[]" value="'+temp_receipt+'">';
            html_snippet += '<input type="hidden" name="transit_account[]" value="'+temp_transit_account+'">';
            html_snippet += '<input type="hidden" name="expense_account[]" value="'+temp_expense_account+'">';
            html_snippet += '<input type="hidden" name="rent_currency[]" class="rent-currency-iput-hidden" value="'+temp_rent_currency+'">';
            html_snippet += '<input type="hidden" name="rent_currency_usd_equalance[]" class="rent-currency-usde-iput-hidden" value="'+temp_rent_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="expenses_currency[]" class="expenses-currency-iput-hidden" value="'+temp_expenses_currency+'">';
            html_snippet += '<input type="hidden" name="expenses_currency_usd_equalance[]" class="expenses-currency-usde-iput-hidden" value="'+temp_expenses_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="mobile[]" value="'+temp_mobile+'">';

        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-driver">';
            html_snippet += '<span>'+temp_driver+'</span> ';
            html_snippet += '<input type="hidden" name="driver[]" value="'+temp_driver+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-cmr">';
            html_snippet += '<span>'+temp_cmr+'</span> ';
            html_snippet += '<input type="hidden" name="cmr[]" value="'+temp_cmr+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-plate">';
            html_snippet += '<span>'+temp_plate_num+'</span> ';
            html_snippet += '<input type="hidden" name="plate[]" value="'+temp_plate_num+'">';
        html_snippet += '</td>';
        
        html_snippet += '<td class="lot-row-weight">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="weight[]" value="'+temp_weight+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-plus">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="weight_plus[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-minus">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="weight_minus[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-lose">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="weight_lose[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-gross-weight">';
	        html_snippet += '<span>'+temp_weight+'</span> ';
	        html_snippet += '<input type="hidden" name="gross_weight[]" value="'+temp_weight+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="lot-row-cost">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="cost[]" value="'+temp_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-rent">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="rent[]" value="'+temp_rent+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-expenses">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="expenses[]" value="'+temp_expenses+'" '+expenses_readonly+'>';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-real-cost">';
            html_snippet += '<span>'+round_decimels_3(temp_real_cost)+'</span> ';
            html_snippet += '<input type="hidden" name="real_cost[]" value="'+temp_real_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-total-cost">';
            html_snippet += '<span>'+round_decimels_3(temp_total_cost)+'</span> ';
            html_snippet += '<input type="hidden" name="total_cost[]" value="'+temp_total_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td style="width: 40px;">';
            html_snippet += '<a class="btn btn-danger btn-sm lot-purchase-row-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';

    $('#lot-purchase-table-body').append(html_snippet);
    $('.fixed-fields-row').addClass('pointer-none');

    $('#temp-lot-purchase-form [name=temp_transit_account]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form [name=temp_transit_account]').trigger('chosen:updated');
    $('#temp-lot-purchase-form [name=temp_expense_account]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form [name=temp_expense_account]').trigger('chosen:updated');
    $('#temp-lot-purchase-form [name=temp_rent_currency]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form [name=temp_rent_currency]').trigger('chosen:updated');
    $('#temp-lot-purchase-form [name=temp_expenses_currency]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form [name=temp_expenses_currency]').trigger('chosen:updated');

    $('#temp-lot-purchase-form [name=temp_fuel_type]').val('');
    $('#temp-lot-purchase-form [name=temp_driver]').val('');
    $('#temp-lot-purchase-form [name=temp_mobile]').val('');
    $('#temp-lot-purchase-form [name=temp_plate_num]').val('');
    $('#temp-lot-purchase-form [name=temp_cmr]').val('');
    $('#temp-lot-purchase-form [name=temp_weight]').val('');
    $('#temp-lot-purchase-form [name=temp_cost]').val('');
    $('#temp-lot-purchase-form [name=temp_rent]').val('');
    $('#temp-lot-purchase-form [name=temp_expenses]').val('');
    $('#temp-lot-purchase-form [name=temp_real_cost]').val('');
    $('#temp-lot-purchase-form [name=temp_total_cost]').val('');

    clear_division_relations();
    calculate_lot_division_avg_cost();
    calculate_lot_purchase_totals();
});
// --------------------------------------------------------------------------------------------

// delete lot purchase row
$(document).on('click','.lot-purchase-row-del-trigger',function(e)
{
	e.preventDefault();

	// if existing row then save uid in deleted input
	if($(this).hasClass('lot-existing-row'))
	{
		pointer_obj = $(this);
		sub_title = $('#langs-span').attr('data-delete-popup-lot-note');
		main_title = $('#langs-span').attr('data-delete-main-title');
		confirm_btn_text = $('#langs-span').attr('data-delete-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-delete-cancel-btn-text');

		swal(
		{
		    title: main_title,
		    text: sub_title,
		    html: true,
		    type: false,
		    showCancelButton: true,
		    cancelButtonText: cancel_btn_text,
		    confirmButtonColor: "#1ab394",
		    confirmButtonText: confirm_btn_text,
		    closeOnConfirm: true
		},
		function()
		{
			// append deleted item input
			uid = pointer_obj.attr('data-uid');
			pointer_obj.closest('form').prepend('<input type="hidden" class="is-lot-deleted-iput" name="deleted[]" value="'+uid+'">');
			pointer_obj.closest('.lot-purchase-table-row').remove();
			clear_division_relations();
			calculate_lot_division_avg_cost();
			calculate_lot_purchase_totals();
		});
	}
	else
	{
		$(this).closest('.lot-purchase-table-row').remove();
		clear_division_relations();
		calculate_lot_division_avg_cost();
		calculate_lot_purchase_totals();
	}
});
// --------------------------------------------------------------------------------------------

// handle lot purchase row alterations
$(document).on('keyup input','.lot-purchase-table-row .lot-purchses-editable-iputs',function(e)
{
	handle_lot_row_editable_alterations($(this).closest('.lot-purchase-table-row'));
});
function handle_lot_row_editable_alterations(pointer_parent_obj)
{
	base_currency = $('[name=temp_currency]').val();
	base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	rent_currency = pointer_parent_obj.find('.rent-currency-iput-hidden').val();
	rent_currency_usd_equalance = pointer_parent_obj.find('.rent-currency-usde-iput-hidden').val();
	expenses_currency = pointer_parent_obj.find('.expenses-currency-iput-hidden').val();
	expenses_currency_usd_equalance = pointer_parent_obj.find('.expenses-currency-usde-iput-hidden').val();

	weight = pointer_parent_obj.find('.lot-row-weight').find('input').val();
	weight_plus = pointer_parent_obj.find('.lot-row-weight-plus').find('input').val();
	weight_minus = pointer_parent_obj.find('.lot-row-weight-minus').find('input').val();
	weight_lose = pointer_parent_obj.find('.lot-row-weight-lose').find('input').val();

	cost = pointer_parent_obj.find('.lot-row-cost').find('input').val();
	rent = pointer_parent_obj.find('.lot-row-rent').find('input').val();
	expenses = pointer_parent_obj.find('.lot-row-expenses').find('input').val();

	base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
	rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
	expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);

	weight = refine_number(weight);
	weight_plus = refine_number(weight_plus);
	weight_minus = refine_number(weight_minus);
	weight_lose = refine_number(weight_lose);
	gross_weight = (weight+weight_plus) - weight_minus;
	gross_weight = gross_weight - weight_lose;

	cost = refine_number(cost);
	rent = refine_number(rent);
	expenses = refine_number(expenses);

	// convert rent if currency not same
	if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
	{
		if(base_currency != rent_currency)
		{
			rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	// convert expenses if currency not same
	if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
	{
		if(base_currency != expenses_currency)
		{
			expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	real_cost = cost + rent + expenses;
	// total_cost = real_cost * weight;
	total_cost = real_cost * gross_weight;

	pointer_parent_obj.find('.lot-row-gross-weight').find('span').text(gross_weight);
	pointer_parent_obj.find('.lot-row-gross-weight').find('input').val(gross_weight);

	pointer_parent_obj.find('.lot-row-real-cost').find('span').text(round_decimels_3(real_cost));
	pointer_parent_obj.find('.lot-row-real-cost').find('input').val(real_cost);
	pointer_parent_obj.find('.lot-row-total-cost').find('span').text(round_decimels_3(total_cost));
	pointer_parent_obj.find('.lot-row-total-cost').find('input').val(total_cost);

	calculate_lot_division_avg_cost();
	calculate_lot_purchase_totals();
}
// --------------------------------------------------------------------------------------------

function calculate_lot_purchase_totals()
{
	total_weight = 0;
	total_gross_weight = 0;
	total_cost = 0;
	total_rent = 0;
	total_expenses = 0;
	total_real_cost = 0;

	// loop rows
	$('#lot-purchase-table-body .lot-purchase-table-row').each(function(e)
	{
		base_currency = $('[name=temp_currency]').val();
		base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
		rent_currency = $(this).find('.rent-currency-iput-hidden').val();
		rent_currency_usd_equalance = $(this).find('.rent-currency-usde-iput-hidden').val();
		expenses_currency = $(this).find('.expenses-currency-iput-hidden').val();
		expenses_currency_usd_equalance = $(this).find('.expenses-currency-usde-iput-hidden').val();

		cost = $(this).find('.lot-row-cost').find('input').val();
		weight = $(this).find('.lot-row-weight').find('input').val();
		gross_weight = $(this).find('.lot-row-gross-weight').find('input').val();
		rent = $(this).find('.lot-row-rent').find('input').val();
		expenses = $(this).find('.lot-row-expenses').find('input').val();
		real_cost = $(this).find('.lot-row-real-cost').find('input').val();

		base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
		rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
		expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);

		cost = refine_number(cost);
		weight = refine_number(weight);
		gross_weight = refine_number(gross_weight);
		rent = refine_number(rent);
		expenses = refine_number(expenses);
		real_cost = refine_number(real_cost);

		// convert rent if currency not same
		if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
		{
			if(base_currency != rent_currency)
			{
				rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
			}
		}

		// convert expenses if currency not same
		if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
		{
			if(base_currency != expenses_currency)
			{
				expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
			}
		}

		// total_weight += weight;
		// total_cost += cost * weight;
		// total_rent += rent * weight;
		// total_expenses += expenses * weight;
		// total_real_cost += real_cost * weight;

		total_weight += weight;
		total_gross_weight += gross_weight;
		total_cost += cost * gross_weight;
		total_rent += rent * gross_weight;
		total_expenses += expenses * gross_weight;
		total_real_cost += real_cost * gross_weight;
	});

	$('.lot-purchase-total-weight-row span').text(round_decimels_3(total_weight));
	$('.lot-purchase-total-weight-row input').val(round_decimels_3(total_weight));

	$('.lot-purchase-total-gross-weight-row span').text(round_decimels_3(total_gross_weight));
	$('.lot-purchase-total-gross-weight-row input').val(round_decimels_3(total_gross_weight));

	$('.lot-purchase-total-cost-row span').text(round_decimels_3(total_cost));
	$('.lot-purchase-total-cost-row input').val(total_cost);

	$('.lot-purchase-total-rent-row span').text(round_decimels_3(total_rent));
	$('.lot-purchase-total-rent-row input').val(total_rent);

	$('.lot-purchase-total-expenses-row span').text(round_decimels_3(total_expenses));
	$('.lot-purchase-total-expenses-row input').val(total_expenses);

	$('.lot-purchase-total-real-cost-row span').text(round_decimels_3(total_real_cost));
	$('.lot-purchase-total-real-cost-row input').val(total_real_cost);
}
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------










// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// lot division functions

function calculate_weight_for_iran_to_border()
{
	pending_weight = $('[name=pending_weight]').val();
	pending_weight = refine_number(pending_weight);
	total_weight = pending_weight;

	// loop rows
	$('#lot-purchase-table-body .lot-purchase-table-row').each(function(e)
	{
		weight = $(this).find('.lot-row-gross-weight').find('input').val();
		weight = refine_number(weight);
		total_weight += weight;
	});

	return total_weight;
}
// --------------------------------------------------------------------------------------------
function check_weight_limit(new_weight)
{
	total_weight_for_consume = calculate_weight_for_iran_to_border();
	new_weight = refine_number(new_weight);
	total_weight_consumed = new_weight;

	// loop rows
	$('#lot-purchase-division-table-body .lot-purchase-division-table-row').each(function(e)
	{
		weight = $(this).find('.lot-row-weight').find('input').val();
		weight = refine_number(weight);
		total_weight_consumed += weight;
	});

	if(total_weight_consumed > total_weight_for_consume)
	{
		return false;
	}
	else
	{
		return true;
	}
}
// --------------------------------------------------------------------------------------------
// calculate real and total real cost in lot purchase division
$(document).on('keyup input','#temp-lot-purchase-form-division .clratc-div',function(e){ calculate_lot_division_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form [name=temp_currency]',function(e){ calculate_lot_division_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form-division [name=div_rent_currency]',function(e){ calculate_lot_division_real_and_total_costs(); });
$(document).on('change','#temp-lot-purchase-form-division [name=div_expenses_currency]',function(e){ calculate_lot_division_real_and_total_costs(); });
function calculate_lot_division_real_and_total_costs()
{
	base_currency = $('[name=temp_currency]').val();
	base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');

	weight = $('[name=div_weight]').val();
	cost = $('[name=div_cost]').val();

	rent = $('[name=div_rent]').val();
	rent_currency = $('[name=div_rent_currency]').val();
	rent_currency_usd_equalance = $('[name=div_rent_currency] option:selected').attr('data-usd-equalance');

	expenses = $('[name=div_expenses]').val();
	expenses_currency = $('[name=div_expenses_currency]').val();
	expenses_currency_usd_equalance = $('[name=div_expenses_currency] option:selected').attr('data-usd-equalance');

	base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
	rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
	expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);
	weight = refine_number(weight);
	cost = refine_number(cost);
	rent = refine_number(rent);
	expenses = refine_number(expenses);

	// convert rent if currency not same
	if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
	{
		if(base_currency != rent_currency)
		{
			rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	// convert expenses if currency not same
	if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
	{
		if(base_currency != expenses_currency)
		{
			expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	real_cost = cost + rent + expenses;
	total_cost = real_cost * weight;

	$('[name=div_real_cost]').val(real_cost);
	$('[name=div_total_cost]').val(total_cost);
}
// --------------------------------------------------------------------------------------------
// avg cost for lot division
function calculate_lot_division_avg_cost()
{
	tankers_count = 0;
	tankers_total_real_cost = 0;
	$('#lot-purchase-table-body .lot-purchase-table-row').each(function(e)
	{
		real_cost = $(this).find('.lot-row-real-cost').find('input').val();
		real_cost = refine_number(real_cost);
		tankers_total_real_cost = tankers_total_real_cost + real_cost;
		tankers_count = tankers_count + 1;
	});

	avg_real_cost = tankers_total_real_cost / tankers_count;
	if(tankers_count < 1 && tankers_count < 1){ avg_real_cost = null; }
	$('[name=div_cost]').val(avg_real_cost);
}
// --------------------------------------------------------------------------------------------
// submit lot division form
$(document).on('submit','#temp-lot-purchase-form-division',function(e)
{
	e.preventDefault();
	var rowCount = $('#lot-fuel-division-table tr').length;
	temp_weight = $('[name=div_weight]').val();
	if(check_weight_limit(temp_weight) == false)
	{
		// error here
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
		toastr.error("You don't have enough weight to consume.", 'Insufficient Weight');
		return false;
	}

	temp_currency = $('[name=temp_currency]').val();
	temp_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	temp_transit_account = $('[name=div_transit_account]').val();
	temp_expense_account = $('[name=div_expense_account]').val();
	temp_driver = $('[name=div_driver]').val();
	temp_mobile = $('[name=div_mobile]').val();
	temp_plate_num = $('[name=div_plate_num]').val();
	temp_cmr = $('[name=div_cmr]').val();
	temp_weight = $('[name=div_weight]').val();
	temp_cost = $('[name=div_cost]').val();
	temp_rent = $('[name=div_rent]').val();
	temp_rent_currency = $('[name=div_rent_currency]').val();
	temp_rent_currency_usd_equalance = $('[name=div_rent_currency] option:selected').attr('data-usd-equalance');
	temp_expenses = $('[name=div_expenses]').val();
	temp_expenses_currency = $('[name=div_expenses_currency]').val();
	temp_expenses_currency_usd_equalance = $('[name=div_expenses_currency] option:selected').attr('data-usd-equalance');
	temp_real_cost = $('[name=div_real_cost]').val();
	temp_total_cost = $('[name=div_total_cost]').val();

	if($.trim(temp_rent_currency).length == 0)
	{
		temp_rent_currency = temp_currency;
		temp_rent_currency_usd_equalance = temp_currency_usd_equalance;
	}

	if($.trim(temp_expenses_currency).length == 0)
	{
		temp_expenses_currency = temp_currency;
		temp_expenses_currency_usd_equalance = temp_currency_usd_equalance;
	}

	// html snippet
	html_snippet = '<tr class="text-center lot-purchase-division-table-row">';
		html_snippet += '<td>'+rowCount+'</td>';
        html_snippet += '<td class="lot-row-driver">';
            html_snippet += '<span>'+temp_driver+'</span> ';
            html_snippet += '<input type="hidden" name="div_driver[]" value="'+temp_driver+'">';
            html_snippet += '<input type="hidden" name="div_uid[]" value="">';
            html_snippet += '<input type="hidden" name="div_currency[]" value="'+temp_currency+'">';
            html_snippet += '<input type="hidden" name="div_currency_usd_equalance[]" value="'+temp_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="div_transit_account[]" value="'+temp_transit_account+'">';
            html_snippet += '<input type="hidden" name="div_expense_account[]" value="'+temp_expense_account+'">';
            html_snippet += '<input type="hidden" name="div_rent_currency[]" class="rent-currency-iput-hidden" value="'+temp_rent_currency+'">';
            html_snippet += '<input type="hidden" name="div_rent_currency_usd_equalance[]" class="rent-currency-usde-iput-hidden" value="'+temp_rent_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="div_expenses_currency[]" class="expenses-currency-iput-hidden" value="'+temp_expenses_currency+'">';
            html_snippet += '<input type="hidden" name="div_expenses_currency_usd_equalance[]" class="expenses-currency-usde-iput-hidden" value="'+temp_expenses_currency_usd_equalance+'">';
            html_snippet += '<input type="hidden" name="div_mobile[]" value="'+temp_mobile+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-cmr">';
            html_snippet += '<span>'+temp_cmr+'</span> ';
            html_snippet += '<input type="hidden" name="div_cmr[]" value="'+temp_cmr+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-plate">';
            html_snippet += '<span>'+temp_plate_num+'</span> ';
            html_snippet += '<input type="hidden" name="div_plate[]" value="'+temp_plate_num+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="lot-row-weight">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_weight[]" value="'+temp_weight+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-plus">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_weight_plus[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-minus">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_weight_minus[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-weight-lose">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_weight_lose[]" value="0">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-gross-weight">';
            html_snippet += '<span>'+temp_weight+'</span> ';
            html_snippet += '<input type="hidden" name="div_gross_weight[]" value="'+temp_weight+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="lot-row-cost">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_cost[]" value="'+temp_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-rent">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_rent[]" value="'+temp_rent+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-expenses">';
            html_snippet += '<input type="text" class="lot-purchses-editable-iputs" name="div_expenses[]" value="'+temp_expenses+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-real-cost">';
            html_snippet += '<span>'+round_decimels_3(temp_real_cost)+'</span> ';
            html_snippet += '<input type="hidden" name="div_real_cost[]" value="'+temp_real_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="lot-row-total-cost">';
            html_snippet += '<span>'+round_decimels_3(temp_total_cost)+'</span> ';
            html_snippet += '<input type="hidden" name="div_total_cost[]" value="'+temp_total_cost+'">';
        html_snippet += '</td>';
        html_snippet += '<td style="width: 40px;">';
            html_snippet += '<a class="btn btn-danger btn-sm lot-purchase-division-row-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';

    $('#lot-purchase-division-table-body').append(html_snippet);

    $('#temp-lot-purchase-form-division [name=div_transit_account]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form-division [name=div_transit_account]').trigger('chosen:updated');
    $('#temp-lot-purchase-form-division [name=div_expense_account]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form-division [name=div_expense_account]').trigger('chosen:updated');
    $('#temp-lot-purchase-form-division [name=div_rent_currency]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form-division [name=div_rent_currency]').trigger('chosen:updated');
    $('#temp-lot-purchase-form-division [name=div_expenses_currency]').prop('selectedIndex',0);
    $('#temp-lot-purchase-form-division [name=div_expenses_currency]').trigger('chosen:updated');

    $('#temp-lot-purchase-form-division [name=div_driver]').val('');
    $('#temp-lot-purchase-form-division [name=div_mobile]').val('');
    $('#temp-lot-purchase-form-division [name=div_plate_num]').val('');
    $('#temp-lot-purchase-form-division [name=div_cmr]').val('');
    $('#temp-lot-purchase-form-division [name=div_weight]').val('');
    $('#temp-lot-purchase-form-division [name=div_cost]').val(temp_cost);
    $('#temp-lot-purchase-form-division [name=div_rent]').val('');
    $('#temp-lot-purchase-form-division [name=div_expenses]').val('');
    $('#temp-lot-purchase-form-division [name=div_real_cost]').val('');
    $('#temp-lot-purchase-form-division [name=div_total_cost]').val('');

    calculate_lot_purchase_division_totals();
});
// --------------------------------------------------------------------------------------------

// delete lot purchase row
$(document).on('click','.lot-purchase-division-row-del-trigger',function(e)
{
	e.preventDefault();

	// if existing row then save uid in deleted input
	if($(this).hasClass('lot-existing-row'))
	{
		pointer_obj = $(this);
		sub_title = $('#langs-span').attr('data-delete-popup-lot-note');
		main_title = $('#langs-span').attr('data-delete-main-title');
		confirm_btn_text = $('#langs-span').attr('data-delete-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-delete-cancel-btn-text');

		swal(
		{
		    title: main_title,
		    text: sub_title,
		    html: true,
		    type: false,
		    showCancelButton: true,
		    cancelButtonText: cancel_btn_text,
		    confirmButtonColor: "#1ab394",
		    confirmButtonText: confirm_btn_text,
		    closeOnConfirm: true
		},
		function()
		{
			// append deleted item input
			uid = pointer_obj.attr('data-uid');
			pointer_obj.closest('form').prepend('<input type="hidden" class="is-lot-deleted-iput" name="div_deleted[]" value="'+uid+'">');
			pointer_obj.closest('.lot-purchase-division-table-row').remove();
			calculate_lot_purchase_division_totals();
		});
	}
	else
	{
		$(this).closest('.lot-purchase-division-table-row').remove();
		calculate_lot_purchase_division_totals();
	}
});
// --------------------------------------------------------------------------------------------

// submit populated form
$(document).on('click','#iran-to-border-submit',function(e)
{
	if($('#lot-purchase-division-table-body .lot-purchase-division-table-row').length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
		toastr.error('Please add some data to Proceed', 'Data Not Found');
		return false;
	}

	$('#division-form-append-area').html(''); // empty area
	// reset inputs default values | inputs value not updating due to dom issue
	$('#lot-purchase-division-form').find('input').each(function(e){ this.defaultValue = $(this).val(); });
	division_form_html = $('#lot-purchase-division-form').html(); // get form html
	$('#division-form-append-area').html(division_form_html); // append form html
	$('#lot-purchase-form').trigger('submit'); // submit form
});
// --------------------------------------------------------------------------------------------

// handle lot purchase division row alterations
$(document).on('keyup input','.lot-purchase-division-table-row .lot-purchses-editable-iputs',function(e)
{
	handle_lot_division_row_editable_alterations($(this).closest('.lot-purchase-division-table-row'));
});
function handle_lot_division_row_editable_alterations(pointer_parent_obj)
{
	base_currency = $('[name=temp_currency]').val();
	base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	rent_currency = pointer_parent_obj.find('.rent-currency-iput-hidden').val();
	rent_currency_usd_equalance = pointer_parent_obj.find('.rent-currency-usde-iput-hidden').val();
	expenses_currency = pointer_parent_obj.find('.expenses-currency-iput-hidden').val();
	expenses_currency_usd_equalance = pointer_parent_obj.find('.expenses-currency-usde-iput-hidden').val();

	weight = pointer_parent_obj.find('.lot-row-weight').find('input').val();
	weight_plus = pointer_parent_obj.find('.lot-row-weight-plus').find('input').val();
	weight_minus = pointer_parent_obj.find('.lot-row-weight-minus').find('input').val();
	weight_lose = pointer_parent_obj.find('.lot-row-weight-lose').find('input').val();

	cost = pointer_parent_obj.find('.lot-row-cost').find('input').val();
	rent = pointer_parent_obj.find('.lot-row-rent').find('input').val();
	expenses = pointer_parent_obj.find('.lot-row-expenses').find('input').val();

	base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
	rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
	expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);

	weight = refine_number(weight);
	weight_plus = refine_number(weight_plus);
	weight_minus = refine_number(weight_minus);
	weight_lose = refine_number(weight_lose);
	gross_weight = (weight + weight_plus) - weight_minus;
	gross_weight = gross_weight - weight_lose;

	cost = refine_number(cost);
	rent = refine_number(rent);
	expenses = refine_number(expenses);

	// convert rent if currency not same
	if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
	{
		if(base_currency != rent_currency)
		{
			rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	// convert expenses if currency not same
	if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
	{
		if(base_currency != expenses_currency)
		{
			expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
		}
	}

	real_cost = cost + rent + expenses;
	// total_cost = real_cost * weight;
	total_cost = real_cost * gross_weight;

	pointer_parent_obj.find('.lot-row-gross-weight').find('span').text(round_decimels_3(gross_weight));
	pointer_parent_obj.find('.lot-row-gross-weight').find('input').val(gross_weight);

	pointer_parent_obj.find('.lot-row-real-cost').find('span').text(round_decimels_3(real_cost));
	pointer_parent_obj.find('.lot-row-real-cost').find('input').val(real_cost);
	pointer_parent_obj.find('.lot-row-total-cost').find('span').text(round_decimels_3(total_cost));
	pointer_parent_obj.find('.lot-row-total-cost').find('input').val(total_cost);

	calculate_lot_purchase_division_totals();
}
// --------------------------------------------------------------------------------------------

function calculate_lot_purchase_division_totals()
{
	total_weight = 0;
	total_gross_weight = 0;
	total_cost = 0;
	total_rent = 0;
	total_expenses = 0;
	total_real_cost = 0;

	// loop rows
	$('#lot-purchase-division-table-body .lot-purchase-division-table-row').each(function(e)
	{
		base_currency = $('[name=temp_currency]').val();
		base_currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
		rent_currency = $(this).find('.rent-currency-iput-hidden').val();
		rent_currency_usd_equalance = $(this).find('.rent-currency-usde-iput-hidden').val();
		expenses_currency = $(this).find('.expenses-currency-iput-hidden').val();
		expenses_currency_usd_equalance = $(this).find('.expenses-currency-usde-iput-hidden').val();

		cost = $(this).find('.lot-row-cost').find('input').val();
		weight = $(this).find('.lot-row-weight').find('input').val();
		gross_weight = $(this).find('.lot-row-gross-weight').find('input').val();
		rent = $(this).find('.lot-row-rent').find('input').val();
		expenses = $(this).find('.lot-row-expenses').find('input').val();
		real_cost = $(this).find('.lot-row-real-cost').find('input').val();

		base_currency_usd_equalance = refine_number(base_currency_usd_equalance);
		rent_currency_usd_equalance = refine_number(rent_currency_usd_equalance);
		expenses_currency_usd_equalance = refine_number(expenses_currency_usd_equalance);

		cost = refine_number(cost);
		weight = refine_number(weight);
		gross_weight = refine_number(gross_weight);
		rent = refine_number(rent);
		expenses = refine_number(expenses);
		real_cost = refine_number(real_cost);

		// convert rent if currency not same
		if($.trim(base_currency).length > 0 && $.trim(rent_currency).length > 0)
		{
			if(base_currency != rent_currency)
			{
				rent = amount_conversion(rent, rent_currency_usd_equalance, base_currency_usd_equalance);
			}
		}

		// convert expenses if currency not same
		if($.trim(base_currency).length > 0 && $.trim(expenses_currency).length > 0)
		{
			if(base_currency != expenses_currency)
			{
				expenses = amount_conversion(expenses, expenses_currency_usd_equalance, base_currency_usd_equalance);
			}
		}

		total_weight += weight;
		total_gross_weight += gross_weight;

		total_cost += cost * gross_weight;
		total_rent += rent * gross_weight;
		total_expenses += expenses * gross_weight;
		total_real_cost += real_cost * gross_weight;
	});

	$('.lot-purchase-division-total-weight-row span').text(round_decimels_3(total_weight));
	$('.lot-purchase-division-total-weight-row input').val(round_decimels_3(total_weight));

	$('.lot-purchase-division-total-gross-weight-row span').text(round_decimels_3(total_gross_weight));
	$('.lot-purchase-division-total-gross-weight-row input').val(round_decimels_3(total_gross_weight));

	$('.lot-purchase-division-total-cost-row span').text(round_decimels_3(total_cost));
	$('.lot-purchase-division-total-cost-row input').val(total_cost);

	$('.lot-purchase-division-total-rent-row span').text(round_decimels_3(total_rent));
	$('.lot-purchase-division-total-rent-row input').val(total_rent);

	$('.lot-purchase-division-total-expenses-row span').text(round_decimels_3(total_expenses));
	$('.lot-purchase-division-total-expenses-row input').val(total_expenses);

	$('.lot-purchase-division-total-real-cost-row span').text(round_decimels_3(total_real_cost));
	$('.lot-purchase-division-total-real-cost-row input').val(total_real_cost);
}
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------









// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// invoice sold functions
$(document).on('click','.lot-invoice-sold-trigger',function(e)
{
	e.preventDefault();

	parent_id = $(this).attr('data-puid');
	url = app_url()+'/lot-purchase/avail/for-invoice-sale';

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: {parent_id:parent_id},
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				// reset form
				$('#lot-invoice-sale-form').trigger('reset');
				
				// populate invoices dropdown
				invoice_langed = $('#langs-span').attr('data-invoice');
				invoices_opts = '<option disabled="" selected="">-- '+invoice_langed+' --</option>';
				response.client_sales.forEach(function(inv)
				{
					invoices_opts += '<option class="display-none" data-client="'+inv.client+'" data-currency="'+inv.currency+'" value="'+inv.invoice+'">'+inv.invoice+'</option>';
				});
				$('[name=_invoice_sold_invoice]').html(invoices_opts);

				$("#lot-invoice-sale-form .chosen-select").trigger('chosen:updated');

				$('[name=invoice_lot_currency]').val(response.parent.currency);
				$('[name=invoice_lot_currency_usd_equalance]').val(response.parent.currency_usd_equalance);
				$('[name=invoice_parent_uid]').val(response.parent.uid);
				$('[name=invoice_child_uid]').val(response.items);
				$('[name=_invoice_sold_weight]').val(round_decimels_3(sum_multi_values(response.weight.split(','))));
				$('[name=invoice_lot_weight]').val(response.weight);
				$('[name=invoice_lot_real_cost]').val(response.cost);
				$('[name=invoice_lot_tankers]').val(response.items_count);
				$('#lot-invoice-sale-modal').modal('show');
			}

			if(response.status == 'sold')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error(response.message_body, response.message_head);
			}
		}
	});

});
// --------------------------------------------------------------------------------------------

function sum_multi_values(values_array)
{
	sum_bucket = 0;
	values_array.forEach(function(val)
	{
		sum_bucket += refine_number(val);
	});
	return sum_bucket;
}

$(document).on('change','#lot-invoice-sale-form [name=_invoice_sold_client]',function(e){ filter_lot_client_invoices(); });
$(document).on('change','#lot-invoice-sale-form [name=_invoice_sold_currency]',function(e){ filter_lot_client_invoices(); });
function filter_lot_client_invoices()
{
	currency = $('[name=_invoice_sold_currency]').val();
	client = $('[name=_invoice_sold_client]').val();

	$('[name=_invoice_sold_invoice] option').each(function(e)
	{
		if($(this).is(':disabled'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			$(this).prop('selected',false);
			if($(this).attr('data-client') == client && $(this).attr('data-currency') == currency)
			{
				$(this).removeClass('display-none');
			}
			else
			{
				$(this).addClass('display-none');
			}
		}
	});
	$('[name=_invoice_sold_invoice]').trigger('chosen:updated');

}
// --------------------------------------------------------------------------------------------

$(document).on('keyup input','#lot-invoice-sale-form [name=_invoice_sold_sale_price]',function(e){ calculate_lot_invoice_sold_iputs(); });
$(document).on('change','#lot-invoice-sale-form [name=_invoice_sold_currency]',function(e){ calculate_lot_invoice_sold_iputs(); });


function calculate_lot_invoice_sold_iputs()
{
	lot_currency = $('[name=invoice_lot_currency]').val();
	lot_currency_usd_equalance = $('[name=invoice_lot_currency_usd_equalance]').val();
	sale_currency = $('[name=_invoice_sold_currency]').val();
	sale_currency_usd_equalance = $('[name=_invoice_sold_currency] option:selected').attr('data-usd-equalance');

	weight = $('[name=invoice_lot_weight]').val();
	real_cost = $('[name=invoice_lot_real_cost]').val();
	gross_weight = weight;
	sale_price = $('[name=_invoice_sold_sale_price]').val();
	number_of_tankers = $('[name=invoice_lot_tankers]').val();

	weight_array = weight.split(',');
	real_cost_array = real_cost.split(',');

	sale_price = refine_number(sale_price);
	number_of_tankers = refine_number(number_of_tankers);
	// sale_price = sale_price * number_of_tankers;

	profit = 0;
	total_profit = 0;
	total_sale_price = 0;

	for(var icount=0; icount < number_of_tankers; icount++)
	{
		iweight = weight_array[icount];
		icost = real_cost_array[icount];

		// apply currency conversion
		if($.trim(sale_currency).length > 0)
		{
			icost = amount_conversion(icost, lot_currency_usd_equalance, sale_currency_usd_equalance);
		}

		iprofit = sale_price - icost;
		iprofit_total = iprofit * iweight;
		isale_price_total = sale_price * iweight;

		profit += iprofit;
		total_profit += iprofit_total;
		total_sale_price += isale_price_total;
	}

	$('[name=_invoice_sold_profit]').val(round_numbers_3(profit));
	$('[name=_invoice_sold_total_profit]').val(round_numbers_3(total_profit));
	$('[name=_invoice_sold_total]').val(round_numbers_3(total_sale_price));
}
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------











// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// populate lot sold modal
$(document).on('click','.lot-item-sold-trigger',function(e)
{
	e.preventDefault();

	parent_id = $(this).attr('data-puid');
	child_id = $(this).attr('data-cuid');
	url = app_url()+'/lot-purchase/avail/for-sale';

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: {parent_id:parent_id, child_id:child_id},
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				// reset form
				$('#lot-sale-form').trigger('reset');
				
				// populate invoices dropdown
				invoice_langed = $('#langs-span').attr('data-invoice');
				invoices_opts = '<option disabled="" selected="">-- '+invoice_langed+' --</option>';
				response.client_sales.forEach(function(inv)
				{
					invoices_opts += '<option class="display-none" data-client="'+inv.client+'" data-currency="'+inv.currency+'" value="'+inv.invoice+'">'+inv.invoice+'</option>';
				});
				$('[name=_sold_invoice]').html(invoices_opts);

				$("#lot-sale-form .chosen-select").trigger('chosen:updated');

				$('[name=lot_currency]').val(response.parent.currency);
				$('[name=lot_currency_usd_equalance]').val(response.parent.currency_usd_equalance);
				$('[name=parent_uid]').val(response.parent.uid);
				$('[name=child_uid]').val(response.child.uid);
				$('[name=_sold_weight]').val(round_numbers_3(response.child.gross_weight));
				$('#lot-sale-form [name=_sold_difference]').val('0');
				$('[name=_sold_gross_weight]').val(round_numbers_3(response.child.gross_weight));
				$('[name=lot_real_cost]').val(response.child.real_cost);
				$('#lot-sale-modal').modal('show');
			}
		}
	});

});
// --------------------------------------------------------------------------------------------
$(document).on('change','#lot-sale-form [name=_sold_client]',function(e){ filter_lot_client_invoices(); });
$(document).on('change','#lot-sale-form [name=_sold_currency]',function(e){ filter_lot_client_invoices(); });
function filter_lot_client_invoices()
{
	currency = $('[name=_sold_currency]').val();
	client = $('[name=_sold_client]').val();

	$('[name=_sold_invoice] option').each(function(e)
	{
		if($(this).is(':disabled'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			$(this).prop('selected',false);
			if($(this).attr('data-client') == client && $(this).attr('data-currency') == currency)
			{
				$(this).removeClass('display-none');
			}
			else
			{
				$(this).addClass('display-none');
			}
		}
	});
	$('[name=_sold_invoice]').trigger('chosen:updated');

}
// --------------------------------------------------------------------------------------------

$(document).on('keyup input','#lot-sale-form [name=_sold_difference]',function(e){ calculate_lot_sold_weight_difference(); });
$(document).on('change','#lot-sale-form [name=_sold_difference_type]',function(e){ calculate_lot_sold_weight_difference(); });


function calculate_lot_sold_weight_difference()
{
	weight = $('#lot-sale-form [name=_sold_weight]').val();
	difference_type = $('#lot-sale-form [name=_sold_difference_type]').val();
	difference = $('#lot-sale-form [name=_sold_difference]').val();

	weight = refine_number(weight);
	difference = refine_number(difference);

	if(difference_type == 'minus')
	{
		gross_weight = weight - difference;
	}
	else
	{
		gross_weight = weight + difference;
	}

	$('#lot-sale-form [name=_sold_gross_weight]').val(round_numbers_3(gross_weight));
	calculate_lot_sold_iputs();
}

// $(document).on('keyup input','#lot-sale-form [name=_saqlat]',function(e){ calculate_lot_liters_qty(); });
function calculate_lot_liters_qty()
{
	// _saqlat = $('#lot-sale-form [name=_saqlat]').val();
	// _sold_weight = $('#lot-sale-form [name=_sold_gross_weight]').val();
	// _real_cost = $('[name=lot_real_cost]').val();
	// _gross_weight = $('#lot-sale-form [name=_sold_gross_weight]').val();
	// _total_real_cost = _real_cost * _gross_weight;

	// _saqlat = refine_number(_saqlat);
	// _sold_weight = refine_number(_sold_weight);

	// _liters_qty = _saqlat * _sold_weight;
	// $('#lot-sale-form [name=_litres_qty]').val(_liters_qty);
}

$(document).on('keyup input','#lot-sale-form [name=_sold_sale_price]',function(e){ calculate_lot_sold_iputs(); });
$(document).on('keyup input','#lot-sale-form [name=_sold_discount]',function(e){ calculate_lot_sold_iputs(); });
$(document).on('keyup input','#lot-sale-form [name=_saqlat]',function(e){ calculate_lot_sold_iputs(); });
$(document).on('change','#lot-sale-form [name=_sold_currency]',function(e){ calculate_lot_sold_iputs(); });


function calculate_lot_sold_iputs()
{
	lot_currency = $('[name=lot_currency]').val();
	lot_currency_usd_equalance = $('[name=lot_currency_usd_equalance]').val();
	sale_currency = $('[name=_sold_currency]').val();
	sale_currency_usd_equalance = $('[name=_sold_currency] option:selected').attr('data-usd-equalance');
	weight = $('[name=_sold_weight]').val();
	gross_weight = $('#lot-sale-form [name=_sold_gross_weight]').val();
	sale_price = $('[name=_sold_sale_price]').val();
	real_cost = $('[name=lot_real_cost]').val();
	saqlat = $('#lot-sale-form [name=_saqlat]').val();
	
	if($.trim(sale_currency).length > 0)
	{
		real_cost = amount_conversion(real_cost, lot_currency_usd_equalance, sale_currency_usd_equalance);
	}

	weight = refine_number(weight);
	gross_weight = refine_number(gross_weight);
	sale_price = refine_number(sale_price);
	real_cost = refine_number(real_cost);
	saqlat = refine_number(saqlat);

	liters_qty = null;
	if(saqlat != 0 && saqlat != '')
	{
		liters_qty = gross_weight / saqlat;
		total_cost = gross_weight * real_cost;
		per_liter_cost = total_cost / liters_qty;
		profit = sale_price - per_liter_cost;
		total_profit = liters_qty * profit;
		total = sale_price * liters_qty;
	}
	else
	{
		profit = sale_price - real_cost;
		total = gross_weight * sale_price;
		total_profit = profit * gross_weight;
	}

	discount = $('[name=_sold_discount]').val();
	discount = refine_number(discount);

	discount_amount = ( total * discount) / 100;
	gross_total = total - discount_amount;

	$('#lot-sale-form [name=_litres_qty]').val(round_numbers_3(liters_qty));
	$('[name=_sold_profit]').val(round_numbers_3(profit));
	$('[name=_sold_total_profit]').val(round_numbers_3(total_profit));
	$('[name=_sold_total]').val(round_numbers_3(total));
	$('[name=_sold_discount_amount]').val(round_numbers_3(discount_amount));
	$('[name=_sold_gross_amount]').val(round_numbers_3(gross_total));
}
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------









// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
$(document).on('click','.lot-item-move-trigger',function(e)
{
	e.preventDefault();

	parent_id = $(this).attr('data-puid');
	child_id = $(this).attr('data-cuid');
	weight = $(this).attr('data-weight');

	$('#lot-move-form').trigger('reset');

	$('[name=_move_warehouse] option').each(function(e)
	{
		if($(this).is(':disabled'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			$(this).prop('selected',false).addClass('display-none');
		}
	});

	$('[name=_move_unit] option').each(function(e)
	{
		if($(this).is(':disabled'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			$(this).remove();
		}
	});
	
	$("#lot-move-form .chosen-select").trigger('chosen:updated');

	$('[name=_move_parent_uid]').val(parent_id);
	$('[name=_move_child_uid]').val(child_id);
	$('[name=_move_weight]').val(round_numbers_3(weight));
	$('[name=_move_difference]').val('0');
	$('[name=_move_gross_weight]').val(round_numbers_3(weight));

	$('#lot-move-modal').modal('show');

});


// handle weight difference calculation
$(document).on('keyup input','#lot-move-form [name=_move_difference]',function(e){ calculate_lot_move_weight_difference(); });
$(document).on('change','#lot-move-form [name=_move_difference_type]',function(e){ calculate_lot_move_weight_difference(); });
function calculate_lot_move_weight_difference()
{
	weight = $('#lot-move-form [name=_move_weight]').val();
	difference_type = $('#lot-move-form [name=_move_difference_type]').val();
	difference = $('#lot-move-form [name=_move_difference]').val();

	weight = refine_number(weight);
	difference = refine_number(difference);

	if(difference_type == 'minus')
	{
		gross_weight = weight - difference;
	}
	else
	{
		gross_weight = weight + difference;
	}

	$('#lot-move-form [name=_move_gross_weight]').val(round_numbers_3(gross_weight));
}


$(document).on('change','#lot-move-form [name=_move_item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	
	// update
	$('[name=_move_warehouse] option').each(function(e)
	{
		if($(this).is(':disabled'))
		{
			$(this).prop('selected',true);
		}
		else
		{
			$(this).prop('selected',false);
			if($(this).attr('data-opt-type') == item_type)
			{
				$(this).removeClass('display-none');
			}
			else
			{
				$(this).addClass('display-none');
			}
		}
	});
	$('[name=_move_warehouse]').trigger('chosen:updated');
	re_populate_move_lot_item_units();
});

function re_populate_move_lot_item_units()
{
	purchase_unit = $('[name=_move_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('[name=_move_item] option:selected').attr('data-sale-unit');
	production_unit = $('[name=_move_item] option:selected').attr('data-production-unit');

	unit_langed = $('#langs-span').attr('data-unit');
	options_snippet = '<option disabled="">-- '+unit_langed+' --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('[name=_move_unit]').html(options_snippet);
	$('[name=_move_unit]').trigger('chosen:updated');
}

// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------







// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
$(document).on('click','.notif-seen-status-trigger',function(e)
{
	// prevent if already seen
	if($(this).closest('.notification-info-section').hasClass('seen'))
	{
		// do stuff for seen
	}
	else
	{
		$(this).closest('.notification-info-section').addClass('seen');
		uid = $(this).attr('data-id');
		url = app_url()+'/notification/seen';

		$.ajax(
		{
			url: url,
			type: 'POST',
			data: {uid:uid},
			success: function(response)
			{
				console.log(response);
			}
		});
	}
});

$(document).on('click','.activity-url-proceeder',function(e)
{
	url = $(this).attr('data-url');
	if($.trim(url).length > 0)
	{
		window.location.href = url;
	}
});
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------





// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
$(document).on('dblclick','.accounts-report-remarks-col',function(e)
{
	if($(this).find('input').length > 0){ return false; }
	remarks = $(this).find('span').text();
	selection_length = $(this).find('span').text().length;
	$(this).find('span').addClass('display-none');
	$(this).append('<input type="text" value="'+remarks+'" style="width: 150px; text-indent: 7px;">');
	$(this).find('input').trigger('focus');
	$(this).find('input')[0].setSelectionRange(selection_length, selection_length);
});

$(document).on('focusout','.accounts-report-remarks-col input',function(e)
{
	remarks = $(this).val();
	$(this).siblings('span').removeClass('display-none').text(remarks);
	parent_obj = $(this).closest('tr');
	$(this).remove();
	update_accounts_cross_check(parent_obj);
});

$(document).on('change','.accounts-report-color-iput',function(e)
{
	color = $(this).val();
	$(this).closest('tr').css('background',color);
	update_accounts_cross_check($(this).closest('tr'));
});

$(document).on('change','.accounts-report-cross-check-checkbox',function(e)
{
	update_accounts_cross_check($(this).closest('tr'));
});

function update_accounts_cross_check(row_obj)
{
	is_checked = 'no';
	if(row_obj.find('.accounts-report-cross-check-checkbox').is(':checked')){ is_checked = 'yes'; }
	row_id = row_obj.find('.accounts-report-cross-check-checkbox').attr('value');
	color = row_obj.find('.accounts-report-color-iput').val();
	remarks = row_obj.find('.accounts-report-remarks-col').find('span').text();

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/reports/accounts-cross-check',
		data: {uid:row_id, is_checked:is_checked, color:color, remarks:remarks},
		success: function(response)
		{
			console.log(response);
			// response = JSON.parse(response);
			// if(response.status == 'success')
			// {
			// 	toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			// 	toastr.error(response.body, response.head);
			// }
		}
	});
}
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------








// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// synchronization handler
$(document).on("click",".sync-trigger",function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	$('.ibox-content').addClass('sk-loading');
	$('body').addClass('inprocess');

	url = $(this).attr("href");
	$.ajax(
	{
		url: url,
		success: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			$('body').removeClass('inprocess');
			response = JSON.parse(response);

			if(response.status == 'error')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error(response.message_body, response.message_head);
			}

			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.success(response.message_body, response.message_head);
			}
		},
		error: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------











// ------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------- showroom functions -----------------------------------------------
// ------------------------------------------------------------------------------------------------------------------

// car purchases functions

$(document).on('keyup input','#temp-car-purchases-form .in-calculation',function(e){ calculate_car_total_amount(); });

function calculate_car_total_amount()
{
	cost = refine_number($('#temp-car-purchases-form [name=temp_cost]').val());
	transfer_expenses = refine_number($('#temp-car-purchases-form [name=temp_transfer_exp]').val());
	agent_commission = refine_number($('#temp-car-purchases-form [name=temp_agent_commission]').val());
	other_expenses = refine_number($('#temp-car-purchases-form [name=temp_other_expenses]').val());

	// agent commission
	agent_commission_amount = agent_commission;
	// agent_commission_amount = 0;
	// if(agent_commission > 0){ agent_commission_amount = (cost * agent_commission) / 100; }

	total_amount = cost + transfer_expenses + agent_commission_amount + other_expenses;
	$('#temp-car-purchases-form [name=temp_total_amount]').val(total_amount);
}

$(document).on('submit','#temp-car-purchases-form',function(e)
{
	e.preventDefault();

	currency = $('[name=temp_currency]').val();
	agent = $('[name=temp_agent]').val();
	invoice = $('[name=temp_invoice]').val();
	car_name = $('[name=temp_car_name]').val();
	car_model = $('[name=temp_car_model]').val();
	shasi_num = $('[name=temp_shasi_num]').val();
	car_color = $('[name=temp_car_color]').val();
	car_make = $('[name=temp_car_make]').val();
	expense_details = $('[name=temp_expense_details]').val();
	cost = $('[name=temp_cost]').val();
	transfer_expenses = $('[name=temp_transfer_exp]').val();
	agent_commission = $('[name=temp_agent_commission]').val();
	other_expenses = $('[name=temp_other_expenses]').val();
	total_amount = $('[name=temp_total_amount]').val();

	// populate data
	html_snippet = '<tr class="text-center car-purchase-item-row">';
	    html_snippet += '<td>';
	        html_snippet += car_name;
	        html_snippet += '<input type="hidden" name="car_name[]" value="'+car_name+'">';
	        html_snippet += '<input type="hidden" name="mode[]" value="new">';
	        html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
	        html_snippet += '<input type="hidden" name="agent[]" value="'+agent+'">';
	        html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
	        html_snippet += '<input type="hidden" name="expense_details[]" value="'+expense_details+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>'+car_model+' <input type="hidden" name="car_model[]" value="'+car_model+'"></td>';
	    html_snippet += '<td>'+shasi_num+' <input type="hidden" name="shasi_num[]" value="'+shasi_num+'"></td>';
	    html_snippet += '<td>'+car_color+' <input type="hidden" name="car_color[]" value="'+car_color+'"></td>';
	    html_snippet += '<td>'+car_make+' <input type="hidden" name="car_make[]" value="'+car_make+'"></td>';

	    html_snippet += '<td class="cost-col"><input type="text" class="car-purchses-editable-iputs" name="cost[]" value="'+cost+'"></td>';
	    html_snippet += '<td class="transfer-expenses-col"><input type="text" class="car-purchses-editable-iputs" name="transfer_expenses[]" value="'+transfer_expenses+'"></td>';
	    html_snippet += '<td class="agent-commission-col"><input type="text" class="car-purchses-editable-iputs" name="agent_commission[]" value="'+agent_commission+'"></td>';
	    html_snippet += '<td class="other-expenses-col"><input type="text" class="car-purchses-editable-iputs" name="other_expenses[]" value="'+other_expenses+'"></td>';
	    html_snippet += '<td class="total-amount-col"><span>'+round_decimels(total_amount)+'</span> <input type="hidden" name="total_amount[]" value="'+total_amount+'"></td>';

	    html_snippet += '<td style="width: 40px;"><a class="btn btn-danger btn-sm car-purchase-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a></td>';
	html_snippet += '</tr>';

	$('#car-purchases-table-body').append(html_snippet);

	// reset form inputs
	$('#temp-car-purchases-form').trigger("reset");

	// populate main fields values
	$('[name=temp_currency] option[value='+currency+']').prop('selected',true);
	$('[name=temp_agent] option[value='+agent+']').prop('selected',true);
	$('[name=temp_invoice]').val(invoice);

	// make main fields readonly
	$('.fixed-fields-input').addClass('pointer-none').prop('readonly',true);

	// re-initialise chosen selects
	$(".chosen-select").trigger('chosen:updated');

	handle_car_purchases_totals();
});

// delete purchase item
$(document).on('click','.car-purchase-item-del-trigger',function(e)
{
	e.preventDefault();

	if($(this).hasClass('existing-item'))
	{
		uid = $(this).attr('data-uid');
		$('#deleted-items-wrapper').append('<input type="hidden" name="deleted[]" value="'+uid+'">');
	}
	
	$(this).closest('.car-purchase-item-row').remove();
	handle_car_purchases_totals();
});

// change purchase item table
$(document).on('keyup input','.car-purchses-editable-iputs',function(e){ handle_car_purchase_row_alteration($(this)); });
function handle_car_purchase_row_alteration(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.car-purchase-item-row');

	cost = refine_number(pointer_parent.find('.cost-col').find('input').val());
	transfer_expenses = refine_number(pointer_parent.find('.transfer-expenses-col').find('input').val());
	agent_commission = refine_number(pointer_parent.find('.agent-commission-col').find('input').val());
	other_expenses = refine_number(pointer_parent.find('.other-expenses-col').find('input').val());

	// agent commission
	agent_commission_amount = agent_commission;
	// agent_commission_amount = 0;
	// if(agent_commission > 0){ agent_commission_amount = (cost * agent_commission) / 100; }

	total_amount = cost + transfer_expenses + agent_commission_amount + other_expenses;
	pointer_parent.find('.total-amount-col').find('span').text(round_decimels(total_amount));
	pointer_parent.find('.total-amount-col').find('input').val(total_amount);

	handle_car_purchases_totals();
}

// handle purchases totals after alteration
function handle_car_purchases_totals()
{
	total_cost = 0;
	total_transfer_expenses = 0;
	total_agent_commission = 0;
	total_other_expenses = 0;
	total_total_amount = 0;

	if($('#car-purchases-table-body .car-purchase-item-row').length > 0)
	{
		$('#car-purchases-table-body .car-purchase-item-row').each(function(e)
		{
			cost = refine_number($(this).find('.cost-col').find('input').val());
			transfer_expenses = refine_number($(this).find('.transfer-expenses-col').find('input').val());
			agent_commission = refine_number($(this).find('.agent-commission-col').find('input').val());
			other_expenses = refine_number($(this).find('.other-expenses-col').find('input').val());
			total_amount = refine_number($(this).find('.total-amount-col').find('input').val());

			// agent commission
			agent_commission_amount = agent_commission;
			// agent_commission_amount = 0;
			// if(agent_commission > 0){ agent_commission_amount = (cost * agent_commission) / 100; }

			total_cost += cost;
			total_transfer_expenses += transfer_expenses;
			total_agent_commission += agent_commission_amount;
			total_other_expenses += other_expenses;
			total_total_amount += total_amount;
		});
	}

	$('.car-purchases-totals-col .purchases-total-cost-row span').text(round_decimels(total_cost));
	$('.car-purchases-totals-col .purchases-total-cost-row input').val(total_cost);

	$('.car-purchases-totals-col .purchases-transfer-exp-row span').text(round_decimels(total_transfer_expenses));
	$('.car-purchases-totals-col .purchases-transfer-exp-row input').val(total_transfer_expenses);

	$('.car-purchases-totals-col .purchases-total-agent-commission-row span').text(round_decimels(total_agent_commission));
	$('.car-purchases-totals-col .purchases-total-agent-commission-row input').val(total_agent_commission);

	$('.car-purchases-totals-col .purchases-total-other-expenses-row span').text(round_decimels(total_other_expenses));
	$('.car-purchases-totals-col .purchases-total-other-expenses-row input').val(total_other_expenses);

	$('.car-purchases-totals-col .purchases-grand-total-amount-row span').text(round_decimels(total_total_amount));
	$('.car-purchases-totals-col .purchases-grand-total-amount-row input').val(total_total_amount);
}
// ------------------------------------------------------------------------------------------------------------------


// load delivery functions
$(document).on('keyup input','#load-delivery-form .in-calculation',function(e){ handle_load_delivery_calculations(); });
function handle_load_delivery_calculations(pointer_obj)
{
	load_expenses = refine_number($('[name=load_expenses]').val());
	charges = refine_number($('[name=charges]').val());
	cash_paid = refine_number($('[name=cash_paid]').val());
	total = load_expenses + charges;
	$('[name=total]').val(total);
	pending = total - cash_paid;
	$('[name=pending]').val(pending);
}

// custom expenses
$(document).on('change','#custom-expenses-form [name=currency]',function(e)
{
	rate = $('#custom-expenses-form [name=currency] option:selected').attr('data-usd-equalance');
	$('#custom-expenses-form [name=rate]').val(rate);
});

// custom charges
$(document).on('change','#custom-charges-form [name=currency]',function(e)
{
	rate = $('#custom-charges-form [name=currency] option:selected').attr('data-usd-equalance');
	$('#custom-charges-form [name=rate]').val(rate);
});

// new work
$(document).on('change','#custom-charges-form [name=load_delivery]',function(e)
{
	load_purchase = $('#custom-charges-form [name=load_delivery] option:selected').attr('data-load-purchase');
	load_purchase = load_purchase.split(',');
	opt_count = 1;
	$('#custom-charges-form [name=car] option').each(function(e)
	{
		if(opt_count == 1)
		{
			$(this).prop('selected',true);
		}
		else
		{
			(load_purchase.indexOf($(this).attr('data-purchase')) >= 0) ? $(this).removeClass('display-none') : $(this).addClass('display-none');
		}
		opt_count = opt_count+1;
	});
	$('#custom-charges-form [name=car]').trigger('chosen:updated');
});






// fixing expenses
$(document).on('change','#temp-fixing-expenses-form [name=temp_currency]',function(e)
{
	rate = $('#temp-fixing-expenses-form [name=temp_currency] option:selected').attr('data-usd-equalance');
	$('#temp-fixing-expenses-form [name=temp_rate]').val(rate);
});


$(document).on('submit','#temp-fixing-expenses-form',function(e)
{
	e.preventDefault();

	currency = $('[name=temp_currency]').val();
	rate = $('[name=temp_rate]').val();
	invoice = $('[name=temp_invoice]').val();
	agent = $('[name=temp_agent]').val();
	agent_name = $('[name=temp_agent] option:selected').attr('data-agent-name');
	car = $('[name=temp_car]').val();
	car_name = $('[name=temp_car] option:selected').attr('data-car-name');
	amount = $('[name=temp_amount]').val();
	details = $('[name=temp_details]').val();

	// populate data
	html_snippet = '<tr class="text-center fixing-expenses-item-row">';
	    html_snippet += '<td>';
	        html_snippet += car_name;
	        html_snippet += '<input type="hidden" name="car[]" value="'+car+'">';
	        html_snippet += '<input type="hidden" name="mode[]" value="new">';
	        html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
	        html_snippet += '<input type="hidden" name="rate[]" value="'+rate+'">';
	        html_snippet += '<input type="hidden" name="agent[]" value="'+agent+'">';
	        html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
	    html_snippet += '</td>';
	    html_snippet += '<td class="amount-col"><input type="text" class="fixing-expenses-editable-iputs" name="amount[]" value="'+amount+'"></td>';
	    html_snippet += '<td>'+details+' <input type="hidden" name="details[]" value="'+details+'"></td>';
	    html_snippet += '<td style="width: 40px;"><a class="btn btn-danger btn-sm fixing-expenses-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a></td>';
	html_snippet += '</tr>';

	$('#fixing-expenses-table-body').append(html_snippet);
	$('#temp-fixing-expenses-form').trigger("reset");// reset form inputs

	// populate main fields values
	$('[name=temp_currency] option[value='+currency+']').prop('selected',true);
	$('[name=temp_agent] option[value='+agent+']').prop('selected',true);
	$('[name=temp_rate]').val(rate);
	$('[name=temp_invoice]').val(invoice);

	$('.fixed-fields-input').addClass('pointer-none').prop('readonly',true); // make main fields readonly
	$(".chosen-select").trigger('chosen:updated'); // re-initialise chosen selects
	handle_fixing_expenses_totals();
});

// delete purchase item
$(document).on('click','.fixing-expenses-item-del-trigger',function(e)
{
	e.preventDefault();

	if($(this).hasClass('existing-item'))
	{
		uid = $(this).attr('data-uid');
		$('#deleted-items-wrapper').append('<input type="hidden" name="deleted[]" value="'+uid+'">');
	}
	
	$(this).closest('.fixing-expenses-item-row').remove();
	handle_fixing_expenses_totals();
});

// change purchase item table
$(document).on('keyup input','.fixing-expenses-editable-iputs',function(e){ handle_car_fixing_expenses_row_alteration($(this)); });
function handle_car_fixing_expenses_row_alteration(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.fixing-expenses-item-row');
	amount = refine_number(pointer_parent.find('.amount-col').find('input').val());
	handle_fixing_expenses_totals();
}

// handle purchases totals after alteration
function handle_fixing_expenses_totals()
{
	total_amount = 0;

	if($('#fixing-expenses-table-body .fixing-expenses-item-row').length > 0)
	{
		$('#fixing-expenses-table-body .fixing-expenses-item-row').each(function(e)
		{
			amount = refine_number($(this).find('.amount-col').find('input').val());
			total_amount += amount;
		});
	}

	$('.fixing-expenses-totals-col .fixing-expenses-total-amount-row span').text(round_decimels(total_amount));
	$('.fixing-expenses-totals-col .fixing-expenses-total-amount-row input').val(total_amount);
}


// showroom sales
$(document).on('keyup input','#showroom-sales-form .in-calculations',function(e){ handle_showroom_sales_totals(); });
$(document).on('change','#showroom-sales-form [name=currency]',function(e){ handle_showroom_sales_totals(); });
function handle_showroom_sales_totals()
{
	real_cost = refine_number( $('[name=real_cost]').attr('data-real-cost') );
	real_cost_currency = $('[name=real_cost]').attr('data-currency');
	real_cost_currency_usd_equalance = refine_number( $('[name=real_cost]').attr('data-currency-usd-equalance') );

	currency = $('[name=currency]').val();
	currency_usd_equalance = refine_number( $('[name=currency] option:selected').attr('data-usd-equalance') );
	sale_price = refine_number( $('[name=sale_price]').val() );

	// convert real cost according to sale currency
	if(real_cost_currency != currency)
	{
		real_cost = amount_conversion(real_cost, real_cost_currency_usd_equalance, currency_usd_equalance);
	}

	

	discount = refine_number( $('[name=discount]').val() );
	discount_amount = 0;

	total = sale_price;

	if(discount > 0)
	{
		discount_amount = ( total * discount) / 100;
	}

	profit = sale_price - real_cost - discount_amount;
	
	$('[name=profit]').val(profit);
	$('[name=total]').val(total);

	gross_total = total - discount_amount;
	$('[name=gross_total]').val(gross_total);

	cash_paid = refine_number( $('[name=cash_paid]').val() );
	pending_amount = gross_total - cash_paid;
	$('[name=pending_amount]').val(pending_amount);
}


$(document).on('click','.showroom-car-images-preview-btn',function(e)
{
	car_id = $(this).attr('data-car-id');
	$('#showroom-car-images-form [name=car_uid]').val(car_id);

	$('.car-images-wrapper').html('');
	images = $(this).attr('data-images');
	if($.trim(images).length > 0)
	{
		images = images.split(',');
		images.forEach(function(img)
		{
			img_url = app_url()+'/uploads/cars/'+img;
		    img_html = '<div class="col-md-3 car-img-wrap">';
		        img_html += '<div class="text-center car-img-block">';
		            img_html += '<div class="m-b-sm">';
		                img_html += '<img alt="image" class="img-circle img-md" src="'+img_url+'">';
		            img_html += '</div>';
		            img_html += '<div class="car-img-btns">';
		                img_html += '<a href="'+img_url+'" target="_blank" class="btn btn-xs btn-primary cbtn-left"><i class="fa fa-eye"></i></a>';
		                img_html += '<a hrfe="javascript:void(0);" data-car-id="'+car_id+'" data-car-image="'+img+'" class="btn btn-xs btn-danger cbtn-right showroom-car-img-delete-btn"><i class="fa fa-trash"></i></a>';
		            img_html += '</div>';
		        img_html += '</div>';
		    img_html += '</div>';
		    $('.car-images-wrapper').append(img_html);
		});
	}

	$('#car-images-uploader-input').val(''); // clear files input
	$('#showroom-car-images-modal').modal('show');
});

// delete car images
$(document).on('click','.showroom-car-img-delete-btn',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	$('body').addClass('inprocess');
	url = app_url()+'/showroom/delete-images';
	car_uid = $(this).attr('data-car-id');
	car_image = $(this).attr('data-car-image');
	$(this).closest('.car-img-wrap').remove();

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: {car_uid:car_uid, car_image:car_image},
		success: function(response)
		{
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('[uidprint='+response.uid+']').attr('data-images',response.images);
			}
		},
		error: function(response)
		{
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});

// upload car images
$(document).on('submit','#showroom-car-images-form',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	$('body').addClass('inprocess');
	url = $(this).attr('action');

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: new FormData(this),
		contentType: false,
		processData: false,
		cache: false,
		success: function(response)
		{
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			$('#car-images-uploader-input').val('');

			if(response.status == 'success')
			{
				$('[uidprint='+response.uid+']').attr('data-images',response.images);
				new_uploads = response.new_uploads.split(',');
				new_uploads.forEach(function(img)
				{
					img_url = app_url()+'/uploads/cars/'+img;
				    img_html = '<div class="col-md-3 car-img-wrap">';
				        img_html += '<div class="text-center car-img-block">';
				            img_html += '<div class="m-b-sm">';
				                img_html += '<img alt="image" class="img-circle img-md" src="'+img_url+'">';
				            img_html += '</div>';
				            img_html += '<div class="car-img-btns">';
				                img_html += '<a href="'+img_url+'" target="_blank" class="btn btn-xs btn-primary cbtn-left"><i class="fa fa-eye"></i></a>';
				                img_html += '<a hrfe="javascript:void(0);" data-car-id="'+response.uid+'" data-car-image="'+img+'" class="btn btn-xs btn-danger cbtn-right showroom-car-img-delete-btn"><i class="fa fa-trash"></i></a>';
				            img_html += '</div>';
				        img_html += '</div>';
				    img_html += '</div>';
				    $('.car-images-wrapper').append(img_html);
				});
			}

			if(response.status == 'warning')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.warning('System not found any files to upload', 'Files Missing');
			}
		},
		error: function(response)
		{
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});

// ------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------














// ------------------------------------------------------------------------------------------------------------------
// construction scripting
// ------------------------------------------------------------------------------------------------------------------


$(document).on('keyup input','#project-form [name=cost], #project-form [name=cash_paid]',function(e){ handle_projects_form_calculations(); });
function handle_projects_form_calculations()
{
	cost = $('[name=cost]').val();
	cash_paid = $('[name=cash_paid]').val();
	cost = refine_number(cost);
	cash_paid = refine_number(cash_paid);
	pending_amount = cost - cash_paid;
	$('[name=pending_amount]').val(pending_amount);
}


// payment deduction form calculation
$(document).on('keyup input','#payment-deductions-form [name=amount]',function(e){ handle_payment_deduction_form_calculations(); });
$(document).on('change','#payment-deductions-form [name=currency], #payment-deductions-form [name=project]',function(e){ handle_payment_deduction_form_calculations(); });
function handle_payment_deduction_form_calculations()
{
	deduction_currency = $('[name=currency]').val();
	deduction_currency_usd_equalance = $('[name=currency] option:selected').attr('data-usd-equalance');
	project_currency = $('[name=project] option:selected').attr('data-currency');
	project_currency_usd_equalance = $('[name=project] option:selected').attr('data-usd-equalance');
	amount = $('[name=amount]').val();

	amount = refine_number(amount);
	deduction_currency_usd_equalance = refine_number(deduction_currency_usd_equalance);
	project_currency_usd_equalance = refine_number(project_currency_usd_equalance);

	project_amount = amount_conversion(amount, deduction_currency_usd_equalance, project_currency_usd_equalance);
	$('[name=project_according_amount]').val(project_amount);
}
// ------------------------------------

// payment deduction form calculation
$(document).on('keyup input','#project-payments-form [name=amount]',function(e){ handle_project_payments_form_calculations(); });
$(document).on('change','#project-payments-form [name=currency], #project-payments-form [name=project]',function(e){ handle_project_payments_form_calculations(); });
function handle_project_payments_form_calculations()
{
	deduction_currency = $('[name=currency]').val();
	deduction_currency_usd_equalance = $('[name=currency] option:selected').attr('data-usd-equalance');
	project_currency = $('[name=project] option:selected').attr('data-currency');
	project_currency_usd_equalance = $('[name=project] option:selected').attr('data-usd-equalance');
	amount = $('[name=amount]').val();

	amount = refine_number(amount);
	deduction_currency_usd_equalance = refine_number(deduction_currency_usd_equalance);
	project_currency_usd_equalance = refine_number(project_currency_usd_equalance);

	project_amount = amount_conversion(amount, deduction_currency_usd_equalance, project_currency_usd_equalance);
	$('[name=project_according_amount]').val(project_amount);
}
// ------------------------------------

// expenses deduction type switcher
$(document).on('ifChecked','#expenses-deductions-types [type=radio]',function(e)
{
	type = $('#expenses-deductions-types [type=radio]:checked').val();
	if(type == 'cash_expenses')
	{
		$('.inventory-expenses-row').addClass('display-none');
		$('.cash-expenses-row').removeClass('display-none');
	}
	else
	{
		$('.cash-expenses-row').addClass('display-none');
		$('.inventory-expenses-row').removeClass('display-none');
	}
});

// expenses cash deduction calculation
$(document).on('keyup input','#expenses-deductions-form [name=amount]',function(e){ handle_cash_expense_deduction_calculations(); });
$(document).on('change','#expenses-deductions-form [name=currency], #expenses-deductions-form [name=project]',function(e){ handle_cash_expense_deduction_calculations(); });
function handle_cash_expense_deduction_calculations()
{
	deduction_currency = $('[name=currency]').val();
	deduction_currency_usd_equalance = $('[name=currency] option:selected').attr('data-usd-equalance');
	project_currency = $('[name=project] option:selected').attr('data-currency');
	project_currency_usd_equalance = $('[name=project] option:selected').attr('data-usd-equalance');
	amount = $('[name=amount]').val();

	amount = refine_number(amount);
	deduction_currency_usd_equalance = refine_number(deduction_currency_usd_equalance);
	project_currency_usd_equalance = refine_number(project_currency_usd_equalance);

	project_amount = amount_conversion(amount, deduction_currency_usd_equalance, project_currency_usd_equalance);
	$('[name=project_according_amount]').val(project_amount);
}


// expenses cash deduction calculation
$(document).on('keyup input','#project-expenses-deductions-form [name=amount]',function(e){ handle_project_expense_deduction_calculations(); });
$(document).on('change','#project-expenses-deductions-form [name=currency]',function(e){ handle_project_expense_deduction_calculations(); });
function handle_project_expense_deduction_calculations()
{
	deduction_currency = $('[name=currency]').val();
	deduction_currency_usd_equalance = $('[name=currency] option:selected').attr('data-usd-equalance');
	project_currency = $('[name=project_currency]').val();
	project_currency_usd_equalance = $('[name=project_currency_usd_equalance]').val();
	amount = $('[name=amount]').val();

	amount = refine_number(amount);
	deduction_currency_usd_equalance = refine_number(deduction_currency_usd_equalance);
	project_currency_usd_equalance = refine_number(project_currency_usd_equalance);

	project_amount = amount_conversion(amount, deduction_currency_usd_equalance, project_currency_usd_equalance);
	$('[name=project_according_amount]').val(project_amount);
}


$(document).on('change','#expenses-deductions-form [name=inv_item]',function(e)
{
	if($('body').hasClass('inprocess')){ return false; }

	$('.ibox-content').addClass('sk-loading');
	$('body').addClass('inprocess');

	item = $(this).val();
	url = app_url()+'/expenses-deductions/item-stats/'+item;
	$.ajax(
	{
		url: url,
		success: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			// console.log(response);

			if(response.status == 'error')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error(response.message_body, response.message_head);
			}

			if(response.status == 'success')
			{
				// populate warehouses
				select_warehouse_langed = $('#langs-span').attr('data-select-warehouse');
				warehouse_options = '<option disabled="" selected="">-- '+select_warehouse_langed+' --</option>';
				Object.entries(response.warehouse_options).forEach(entry => {
					const [key, value] = entry;
					warehouse_uid = key;
					warehouse_name = value;
					warehouse_options += '<option value="'+warehouse_uid+'">'+warehouse_name+'</option>';
				});
				$('[name=inv_warehouse]').html(warehouse_options);
				$('[name=inv_warehouse]').trigger('chosen:updated');

				// populate units
				select_unit_langed = $('#langs-span').attr('data-select-unit');
				unit_options = '<option disabled="" selected="">-- '+select_unit_langed+' --</option>';
				Object.entries(response.units_options).forEach(entry => {
					const [key, value] = entry;
					unit = key;
					unit_info = value.split('-,-');
					unit_equalance = unit_info[0];
					unit_name = unit_info[1];
					unit_selected = (unit == 'purchase') ? 'selected="selected"' : null;
					unit_options += '<option '+unit_selected+' value="'+unit+'" data-unit-equalance="'+unit_equalance+'">'+unit_name+'</option>';
				});
				$('[name=inv_unit]').html(unit_options);
				$('[name=inv_unit]').trigger('chosen:updated');
				
				$('[name=inv_avg_cost_usd]').val(response.avg_cost);
			}
		},
		error: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});

$(document).on('keyup input','#expenses-deductions-form [name=inv_qty]',function(e){ handle_inventory_expense_deduction_calculations(); });
$(document).on('change','#expenses-deductions-form [name=inv_project], #expenses-deductions-form [name=inv_item]',function(e){ handle_inventory_expense_deduction_calculations(); });
function handle_inventory_expense_deduction_calculations()
{
	unit = $('[name=inv_unit]').val();
	unit_equalance = $('[name=inv_unit] option:selected').attr('data-unit-equalance');
	project_currency = $('[name=inv_project] option:selected').attr('data-currency');
	project_currency_usd_equalance = $('[name=inv_project] option:selected').attr('data-usd-equalance');
	qty = $('[name=inv_qty]').val();
	avg_cost = $('[name=inv_avg_cost_usd]').val(); // will laways in usd

	qty = refine_number(qty);
	avg_cost = refine_number(avg_cost);
	project_currency_usd_equalance = refine_number(project_currency_usd_equalance);
	unit_equalance = refine_number(unit_equalance);

	if($.trim(avg_cost).length > 0)
	{
		// currency conversion
		if(project_currency != 'usd')
		{
			avg_cost = amount_conversion(avg_cost, 1, project_currency_usd_equalance);
		}

		// unit conversion
		if($.trim(unit).length > 0)
		{
			if(unit_equalance < 1){ unit_equalance = 1; }
			avg_cost = amount_unit_based_conversion(unit_equalance,unit,avg_cost);
		}
		total_amount = avg_cost * qty;
		$('[name=inv_total_amount]').val(total_amount);
	}
}


// leave return
$(document).on('click','.leave-return-trigger',function(e)
{
	e.preventDefault();
	uid = $(this).attr('data-uid');
	in_time = $('.leave-row-'+uid).find('.row-in-time').attr('data-in-time');
	comments = $('.leave-row-'+uid).find('.row-comments').attr('data-comments');
	$('#leave-return-modal [name=in_time]').val(in_time);
	$('#leave-return-modal [name=comments]').val(comments);
	$('#leave-return-row-id').val(uid);
	$('#leave-return-modal').modal('show');
});


$(document).on('submit','#leave-return-form',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	$('body').addClass('inprocess');
	url = $(this).attr('action');

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: new FormData(this),
		contentType: false,
		processData: false,
		cache: false,
		success: function(response)
		{
			$('body').removeClass('inprocess');
			$('#leave-return-form').trigger("reset");
			response = JSON.parse(response);

			if(response.status == 'success')
			{
				$('.leave-row-'+response.uid).find('.row-in-time').html(response.in_time);
				$('.leave-row-'+response.uid).find('.row-comments').html(response.comments);
				$('.leave-row-'+response.uid).find('.row-attachment').html(response.attachment);
				$('#leave-return-modal').modal('hide');
			}
		},
		error: function(response)
		{
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});



// project loans
$(document).on('keyup input','#project-loans-form [name=cash_paid]',function(e)
{
	e.preventDefault();
	loan_amount = refine_number($('#project-loans-form [name=loan_amount]').val());
	cash_paid = refine_number($('#project-loans-form [name=cash_paid]').val());
	pending_amount = loan_amount - cash_paid;
	$('#project-loans-form [name=pending_amount]').val(pending_amount);
});


$(document).on('click','.loan-paid-trigger',function(e)
{
	e.preventDefault();
	url = $(this).attr('data-url');
	loan_amount = $(this).closest('tr').find('.loan-amount-row').attr('data-loan-amount');

	$('#project-loans-form').attr('action',url);
	$('#project-loans-form [name=loan_amount]').val(loan_amount);
	$('#project-loans-form [name=pending_amount]').val(loan_amount);
	$('#project-loans-modal').modal('show');
});


$(document).on('submit','#project-loans-form',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	$('body').addClass('inprocess');
	url = $(this).attr('action');

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: new FormData(this),
		contentType: false,
		processData: false,
		cache: false,
		success: function(response)
		{
			$('body').removeClass('inprocess');
			$('#project-loans-form').trigger("reset");
			response = JSON.parse(response);

			if(response.status == 'success')
			{
				$('.loan-row-'+response.output.uid).find('.loan-cash-paid-row').find('span').text(response.output.cash_paid);
				$('.loan-row-'+response.output.uid).find('.loan-pending-amount-row').find('span').text(response.output.pending_amount);
				$('.loan-row-'+response.output.uid).find('.loan-details-row').find('span').text(response.output.details);
				$('.loan-row-'+response.output.uid).find('.loan-receipt-row').html(response.output.receipt);
				$('#project-loans-modal').modal('hide');
			}
		},
		error: function(response)
		{
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
			toastr.error('Unknown error occured', 'Unknown Error');
		}
	});
});


// purchases
$(document).on('keyup input','#cpurchases-form .in-calculations',function(e){ handle_construction_purchases_calculations(); });
function handle_construction_purchases_calculations()
{
	rate = refine_number( $('[name=rate]').val() );
	qty = refine_number( $('[name=qty]').val() );
	total = rate * qty;
	$('[name=total]').val(total);

	cash_paid = refine_number( $('[name=cash_paid]').val() );
	pending_amount = total - cash_paid;
	$('[name=pending]').val(pending_amount);
}


// contracts
$(document).on('change','#ccontracts-form [name=contract_type]',function(e)
{
	contract_type = $(this).val();
	if(contract_type == 'employee')
	{
		$('.for-employee-step1').removeClass('display-none');
		$('.for-machinery-type').addClass('display-none');
	}

	if(contract_type == 'machinery')
	{
		$('.for-employee-step1, .for-employee-step2').addClass('display-none');
		$('.for-machinery-type').removeClass('display-none');
	}
});

$(document).on('change','#ccontracts-form [name=duration_type]',function(e)
{
	duration_type = $(this).val();
	$('.for-employee-step2').removeClass('display-none');

	if(duration_type == 'monthly')
	{
		$('.ce-months-label').removeClass('display-none');
		$('.ce-days-label').addClass('display-none');
		$('.ce-hours-label').addClass('display-none');
		$('.ce-working-hours-input').removeClass('display-none');
	}

	if(duration_type == 'days')
	{
		$('.ce-days-label').removeClass('display-none');
		$('.ce-months-label').addClass('display-none');
		$('.ce-hours-label').addClass('display-none');
		$('.ce-working-hours-input').removeClass('display-none');
	}

	if(duration_type == 'hours')
	{
		$('.ce-hours-label').removeClass('display-none');
		$('.ce-days-label').addClass('display-none');
		$('.ce-months-label').addClass('display-none');
		$('.ce-working-hours-input').removeClass('display-none');
	}

	if(duration_type == 'sqm')
	{
		$('.ce-months-label').removeClass('display-none');
		$('.ce-days-label').addClass('display-none');
		$('.ce-hours-label').addClass('display-none');
		$('.ce-working-hours-input').addClass('display-none');
	}
});

function reset_ccontracts_form()
{
	$('.for-employee-step1').addClass('display-none');
	$('.for-machinery-type').addClass('display-none');
	$('.for-employee-step2').addClass('display-none');
}


$(document).on('change','#projects-assign-form [name=assign_type]',function(e)
{
	assign_type = $(this).val();

	if(assign_type == 'employee')
	{
		$('.for-employee').removeClass('display-none');
		$('.for-machinery').addClass('display-none');
		$('.for-material').addClass('display-none');
	}

	if(assign_type == 'machinery')
	{
		$('.for-employee').addClass('display-none');
		$('.for-machinery').removeClass('display-none');
		$('.for-material').addClass('display-none');
	}

	if(assign_type == 'material')
	{
		$('.for-employee').addClass('display-none');
		$('.for-machinery').addClass('display-none');
		$('.for-material').removeClass('display-none');
	}
});

function reset_project_assign_form()
{
	$('.for-employee').addClass('display-none');
	$('.for-machinery').addClass('display-none');
	$('.for-material').addClass('display-none');
}

$(document).on("change","#projects-assign-form select[name=employee]",function()
{
	employee_duration_type = $(this).find('option:selected').attr('data-duration-type');
	$('.duration-labels label').addClass('display-none');
	$('.duration-labels .employee-'+employee_duration_type+'-t-label').removeClass('display-none');
});

$(document).on("change","#projects-assign-form select[name=warehouse]",function()
{
	warehouse = $(this).val();
	$("#projects-assign-form").closest('.ibox-content').addClass('sk-loading');
	url = app_url()+'/projects-assign/get-warehouse-items';
	$.ajax(
	{
		url: url,
		type: 'POST',
		data: {warehouse:warehouse},
		success: function(response)
		{
			response = JSON.parse(response);
			$('#projects-assign-form select[name=item]').html(response.options);
			$(".chosen-select").trigger('chosen:updated');
			$("#projects-assign-form").closest('.ibox-content').removeClass('sk-loading');
		}
	});
});

// ------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------


// employee attendence
// employee daily attendence


$(document).on("click",".employees-all-attandence-btn-trigger",function(e)
{
	e.preventDefault();
	pointer_obj = $(this);
	status = pointer_obj.attr("data-status");
	year = $("input[name=selected_year]").val();
	month = $("input[name=selected_month]").val();
	day = $("input[name=selected_day]").val();
	url = app_url()+'/attendence/manage-all-employees-attendence';

	title = $("input[name=mod_em_daily_attendence_confirm_heading]").val();
	text = $("input[name=mod_em_daily_attendence_confirm_message]").val();
	cancelButtonText = $("input[name=mod_em_daily_attendence_cancel_btn_text]").val();
	confirmButtonText = $("input[name=mod_em_daily_attendence_confirm_btn_text]").val();
	swal(
	{
	    title: title,
	    text: text,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: cancelButtonText,
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: confirmButtonText,
	    closeOnConfirm: true
	},
	function()
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: {status:status,year:year,month:month,day:day},
			success: function(response)
			{
				response = JSON.parse(response);

				if(response.status == 'success')
				{
					toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
					toastr.success(response.message_body,response.message_head);
					$('.ibox-content').removeClass('sk-loading');
					location.reload();
				}
			}
		});
	});
});

$(document).on("click",".employee-attendence-trigger-btn",function(e)
{
	e.preventDefault();
	pointer_obj = $(this);
	status = pointer_obj.attr("data-value");
	employee_id = pointer_obj.attr("data-employee");
	year = $("input[name=selected_year]").val();
	month = $("input[name=selected_month]").val();
	day = $("input[name=selected_day]").val();

	if($(this).hasClass("active"))
	{ 
		url = app_url()+'/attendence/delete';
		
		title = $("input[name=mod_em_daily_attendence_del_confirm_heading]").val();
		text = $("input[name=mod_em_daily_attendence_del_confirm_message]").val();
		cancelButtonText = $("input[name=mod_em_daily_attendence_confirm_del_cancel]").val();
		confirmButtonText = $("input[name=mod_em_daily_attendence_confirm_del_btn]").val();
		swal(
		{
		    title: title,
		    text: text,
		    html: true,
		    type: false,
		    showCancelButton: true,
		    cancelButtonText: cancelButtonText,
		    confirmButtonColor: "#1ab394",
		    confirmButtonText: confirmButtonText,
		    closeOnConfirm: true
		},
		function()
		{
			$(".employee-daily-attendence-ibox").addClass('sk-loading');
			$.ajax(
			{
				url: url,
				type: 'POST',
				data: {employee_id:employee_id,year:year,month:month,status:status,day:day},
				success: function(response)
				{
					response = JSON.parse(response);

					if(response.status == 'success')
					{
						pointer_obj.removeClass('btn-primary');
						pointer_obj.addClass('btn-danger');
						pointer_obj.find('i').removeClass('fa fa-check');
						pointer_obj.find('i').addClass('fa fa-times');
						pointer_obj.removeClass('active');

						toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
						toastr.error(response.message_body,response.message_head);
						$(".employee-daily-attendence-ibox").removeClass('sk-loading');
					}
				}
			});
		});
	}
	else
	{
		url = app_url()+'/attendence/save';
		
		title = $("input[name=mod_em_daily_attendence_confirm_heading]").val();
		text = $("input[name=mod_em_daily_attendence_confirm_message]").val();
		cancelButtonText = $("input[name=mod_em_daily_attendence_cancel_btn_text]").val();
		confirmButtonText = $("input[name=mod_em_daily_attendence_confirm_btn_text]").val();
		swal(
		{
		    title: title,
		    text: text,
		    html: true,
		    type: false,
		    showCancelButton: true,
		    cancelButtonText: cancelButtonText,
		    confirmButtonColor: "#1ab394",
		    confirmButtonText: confirmButtonText,
		    closeOnConfirm: true
		},
		function()
		{
			$(".employee-daily-attendence-ibox").addClass('sk-loading');
			$.ajax(
			{
				url: url,
				type: 'POST',
				data: {employee_id:employee_id,year:year,month:month,status:status,day:day},
				success: function(response)
				{
					response = JSON.parse(response);

					if(response.status == 'success')
					{
						pointer_parent = pointer_obj.closest('.employee-attendence-tr-row');

						pointer_parent.find('.active').removeClass('btn-primary');
						pointer_parent.find('.active').find('i').removeClass('fa fa-check');
						pointer_parent.find('.active').addClass('btn-danger');
						pointer_parent.find('.active').find('i').addClass('fa fa-times');
						pointer_parent.find('.active').removeClass('active');

						pointer_obj.removeClass('btn-danger');
						pointer_obj.addClass('btn-primary');
						pointer_obj.find('i').removeClass('fa fa-times');
						pointer_obj.find('i').addClass('fa fa-check');
						pointer_obj.addClass('active');

						toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
						toastr.success(response.message_body,response.message_head);
						$(".employee-daily-attendence-ibox").removeClass('sk-loading');
					}
				}
			});
		});
	}
});





// hide show in lot difference report
$(document).on('click','.show-selected-lots, .hide-selected-lots',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	pointer_obj = $(this);
	url = $(this).attr('href');


	// get checked rows
	uids = [];
	$('.lot-item-check').each(function(e)
	{
		if($(this).is(':checked'))
		{
			row_uid = $(this).attr('value');
			uids.push(row_uid);
		}
	});

	if(uids.length == 0)
	{
		// warning
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some rows to proceed.', 'No Selection');
		return false;
	}
	
	if(pointer_obj.hasClass('hide-selected-lots'))
	{
		main_title = $('#langs-span').attr('data-hide-lot-confirm-main-title');
		sub_title = $('#langs-span').attr('data-hide-lot-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-hide-lot-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-hide-lot-confirm-cancel-btn-text');
	}
	else
	{
		main_title = $('#langs-span').attr('data-show-lot-confirm-main-title');
		sub_title = $('#langs-span').attr('data-show-lot-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-show-lot-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-show-lot-confirm-cancel-btn-text');
	}

	swal(
	{
	    title: main_title,
	    text: sub_title,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: cancel_btn_text,
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: confirm_btn_text,
	    closeOnConfirm: true
	},
	function()
	{
		$('.ibox-content').addClass('sk-loading');
		$('body').addClass('inprocess');
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: {uids:uids.join(',')},
			success:function(response)
			{
				$('body').removeClass('inprocess');
				$('.ibox-content').removeClass('sk-loading');
				response = JSON.parse(response);

				if(response.status == 'success')
				{
					$('.lot-item-check').each(function(e)
					{
						if($(this).is(':checked'))
						{
							$(this).closest('tr').remove();
						}
					});
				}
			},
			error: function(data)
			{
				$('.ibox-content').removeClass('sk-loading');
				$('body').removeClass('inprocess');
			}
		});
	});
});


// hide show in lot moved difference report
$(document).on('click','.show-selected-lots-moved, .hide-selected-lots-moved',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	pointer_obj = $(this);
	url = $(this).attr('href');


	// get checked rows
	uids = [];
	$('.lot-moved-item-check').each(function(e)
	{
		if($(this).is(':checked'))
		{
			row_uid = $(this).attr('value');
			uids.push(row_uid);
		}
	});

	if(uids.length == 0)
	{
		// warning
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some rows to proceed.', 'No Selection');
		return false;
	}
	
	if(pointer_obj.hasClass('hide-selected-lots-moved'))
	{
		main_title = $('#langs-span').attr('data-hide-lot-confirm-main-title');
		sub_title = $('#langs-span').attr('data-hide-lot-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-hide-lot-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-hide-lot-confirm-cancel-btn-text');
	}
	else
	{
		main_title = $('#langs-span').attr('data-show-lot-confirm-main-title');
		sub_title = $('#langs-span').attr('data-show-lot-confirm-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-show-lot-confirm-confirm-btn-text');
		cancel_btn_text = $('#langs-span').attr('data-show-lot-confirm-cancel-btn-text');
	}

	swal(
	{
	    title: main_title,
	    text: sub_title,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: cancel_btn_text,
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: confirm_btn_text,
	    closeOnConfirm: true
	},
	function()
	{
		$('.ibox-content').addClass('sk-loading');
		$('body').addClass('inprocess');
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: {uids:uids.join(',')},
			success:function(response)
			{
				$('body').removeClass('inprocess');
				$('.ibox-content').removeClass('sk-loading');
				response = JSON.parse(response);

				if(response.status == 'success')
				{
					$('.lot-moved-item-check').each(function(e)
					{
						if($(this).is(':checked'))
						{
							$(this).closest('tr').remove();
						}
					});
				}
			},
			error: function(data)
			{
				$('.ibox-content').removeClass('sk-loading');
				$('body').removeClass('inprocess');
			}
		});
	});
});







// buy cars 
$(document).on('click','.buy-cars-images-preview-btn',function(e)
{
	car_id = $(this).attr('id');

	$('.buy-cars-images-wrapper').html('');
	images = $(this).attr('data-images');
	if($.trim(images).length > 0)
	{
		images = images.split(',');
		images.forEach(function(img)
		{
			img_url = app_url()+'/uploads/buy_cars/'+img;
			delete_url = app_url()+'/buy-cars/delete-images/'+car_id+'?image='+img;
		    img_html = '<div class="col-md-3 car-img-wrap">';
		        img_html += '<div class="text-center car-img-block">';
		            img_html += '<div class="m-b-sm">';
		                img_html += '<img alt="image" class="img-circle img-md" src="'+img_url+'">';
		            img_html += '</div>';
		            img_html += '<div class="car-img-btns">';
		                img_html += '<a href="'+img_url+'" target="_blank" class="btn btn-xs btn-primary cbtn-left"><i class="fa fa-eye"></i></a>';
		                img_html += '<a hrfe="javascript:void(0);" data-url="'+delete_url+'" class="btn btn-xs btn-danger cbtn-right buy-cars-img-delete-btn"><i class="fa fa-trash"></i></a>';
		            img_html += '</div>';
		        img_html += '</div>';
		    img_html += '</div>';
		    $('.buy-cars-images-wrapper').append(img_html);
		});
	}

	$('#buy-cars-images-modal').modal('show');
});

// delete car images
$(document).on('click','.buy-cars-img-delete-btn',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	url = $(this).attr('data-url');
	$(this).closest('.car-img-wrap').remove();

	$.ajax(
	{
		url: url,
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('#'+response.uid).attr('data-images',response.images)
			}
		},
		error: function(response)
		{
			
		}
	});
});

$(document).on("click",".buy-car-expense-trigger",function(e)
{
	e.preventDefault();
	main_currency_eq = $("#buy-cars-form select[name=currency] option:selected").attr("data-usd-equalance");
	expense_date = $("#expense_date").val();
	expense_currency = $("#expense_currency").val();
	expense_currency_text = $("#expense_currency option:selected").text();
	expense_currency_eq = $("#expense_currency option:selected").attr("data-usd-equalance");
	expense_amount = $("#expense_amount").val();
	expense_agent = $("#expense_agent").val();
	expense_agent_text = $("#expense_agent option:selected").text();
	expense_details = $("#expense_details").val();

	main_currency_expenses = amount_conversion(expense_amount, expense_currency_eq, main_currency_eq);

	if(expense_date == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please select date to proceed.', 'No Selection');
		return false;
	}

	if(expense_currency == null)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please select currency to proceed.', 'No Selection');
		return false;
	}

	if(expense_amount == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please enter amount to proceed.', 'No Selection');
		return false;
	}

	if($.trim(expense_agent).length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please select agent to proceed.', 'No Selection');
		return false;
	}

	html_snippet = '<tr class="car-buy-expenses-tbody-row">';
		html_snippet += '<td>';
			html_snippet += expense_date;
			html_snippet += '<input type="hidden" name="main_currency_expenses[]" class="main_currency_expenses" value="'+main_currency_expenses+'">';
			html_snippet += '<input type="hidden" name="expense_date_snip[]" value="'+expense_date+'">';
			html_snippet += '<input type="hidden" name="expense_currency_snip[]" value="'+expense_currency+'">';
			html_snippet += '<input type="hidden" name="expense_currency_eq_snip[]" value="'+expense_currency_eq+'">';
			html_snippet += '<input type="hidden" name="expense_amount_snip[]" value="'+expense_amount+'">';
			html_snippet += '<input type="hidden" name="expense_agent_snip[]" value="'+expense_agent+'">';
			html_snippet += '<input type="hidden" name="expense_details_snip[]" value="'+expense_details+'">';
		html_snippet += '</td>';

		html_snippet += '<td>';
			html_snippet += expense_currency_text;
		html_snippet += '</td>';

		html_snippet += '<td>';
			html_snippet += expense_amount;
		html_snippet += '</td>';

		html_snippet += '<td>';
			html_snippet += expense_agent_text;
		html_snippet += '</td>';

		html_snippet += '<td>';
			html_snippet += expense_details;
		html_snippet += '</td>';

		html_snippet += '<td>';
			html_snippet += '<a class="btn btn-danger sm buy-car-expense-trigger-del" style="padding: 3px 7px;" href="javascript:void(0)"><i class="fa fa-trash"></i></a>';
		html_snippet += '</td>';
	html_snippet += '</tr>';

	$('#car-buy-expenses-tbody').append(html_snippet);
	calculate_car_total_expense();
});

function calculate_car_total_expense()
{
	total_expense = 0;
	$("#car-buy-expenses-tbody .car-buy-expenses-tbody-row").each(function(e)
	{
		amount = $(this).find('.main_currency_expenses').val();
		amount = refine_number(amount);
		total_expense += amount;
	});

	$("#buy-cars-form input[name=expense_totals]").val(total_expense);
}

$(document).on('click','.buy-car-expense-trigger-del',function(e)
{
	e.preventDefault();
	$(this).closest('.car-buy-expenses-tbody-row').remove();
	calculate_car_total_expense();
});



$(document).on('click','.buy-cars-images-preview-btn-showroom',function(e)
{
	car_id = $(this).attr('id');

	$('.buy-cars-images-wrapper').html('');
	images = $(this).attr('data-images');
	if($.trim(images).length > 0)
	{
		images = images.split(',');
		images.forEach(function(img)
		{
			img_url = app_url()+'/uploads/people_showroom/'+img;
			delete_url = app_url()+'/people-showroom/delete-images/'+car_id+'?image='+img;
		    img_html = '<div class="col-md-3 car-img-wrap">';
		        img_html += '<div class="text-center car-img-block">';
		            img_html += '<div class="m-b-sm">';
		                img_html += '<img alt="image" class="img-circle img-md" src="'+img_url+'">';
		            img_html += '</div>';
		            img_html += '<div class="car-img-btns">';
		                img_html += '<a href="'+img_url+'" target="_blank" class="btn btn-xs btn-primary cbtn-left"><i class="fa fa-eye"></i></a>';
		                img_html += '<a hrfe="javascript:void(0);" data-url="'+delete_url+'" class="btn btn-xs btn-danger cbtn-right buy-cars-img-delete-btn-showroom"><i class="fa fa-trash"></i></a>';
		            img_html += '</div>';
		        img_html += '</div>';
		    img_html += '</div>';
		    $('.buy-cars-images-wrapper').append(img_html);
		});
	}

	$('#buy-cars-images-modal').modal('show');
});

// delete car images
$(document).on('click','.buy-cars-img-delete-btn-showroom',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	url = $(this).attr('data-url');
	$(this).closest('.car-img-wrap').remove();

	$.ajax(
	{
		url: url,
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('#'+response.uid).attr('data-images',response.images)
			}
		},
		error: function(response)
		{
			
		}
	});
});


// showroom sales
$(document).on('keyup input','#buy-cars-sales-form .in-calculations',function(e){ handle_buy_cars_sales_totals(); });
$(document).on('change','#buy-cars-sales-form [name=currency]',function(e){ handle_buy_cars_sales_totals(); });
function handle_buy_cars_sales_totals()
{
	real_cost = refine_number( $('[name=real_cost]').attr('data-real-cost') );
	real_cost_currency = $('[name=real_cost]').attr('data-currency');
	real_cost_currency_usd_equalance = refine_number( $('[name=real_cost]').attr('data-currency-usd-equalance') );

	currency = $('[name=currency]').val();
	currency_usd_equalance = refine_number( $('[name=currency] option:selected').attr('data-usd-equalance') );
	sale_price = refine_number( $('[name=sale_price]').val() );

	// convert real cost according to sale currency
	if(real_cost_currency != currency)
	{
		real_cost = amount_conversion(real_cost, real_cost_currency_usd_equalance, currency_usd_equalance);
	}

	total = sale_price;

	

	discount = refine_number( $('[name=discount]').val() );
	discount_amount = 0;
	if(discount > 0)
	{
		discount_amount = ( total * discount) / 100;
	}

	profit = sale_price - real_cost - discount_amount;
	$('[name=profit]').val(profit);
	$('[name=total]').val(total);

	gross_total = total - discount_amount;
	$('[name=gross_total]').val(gross_total);

	cash_paid = refine_number( $('[name=cash_paid]').val() );
	pending_amount = gross_total - cash_paid;
	$('[name=pending_amount]').val(pending_amount);
}


// showroom sales
$(document).on('keyup input','#poeple-showroom-sales-form .in-calculations',function(e){ handle_buy_cars_sales_totals_people(); });
$(document).on('change','#poeple-showroom-sales-form [name=currency]',function(e){ handle_buy_cars_sales_totals_people(); });
function handle_buy_cars_sales_totals_people()
{
	real_cost = refine_number( $('[name=real_cost]').attr('data-real-cost') );
	real_cost_currency = $('[name=real_cost]').attr('data-currency');
	real_cost_currency_usd_equalance = refine_number( $('[name=real_cost]').attr('data-currency-usd-equalance') );

	currency = $('[name=currency]').val();
	currency_usd_equalance = refine_number( $('[name=currency] option:selected').attr('data-usd-equalance') );
	sale_price = refine_number( $('[name=sale_price]').val() );


	commission = refine_number( $('[name=commission]').val() );
	commission_dicsount = refine_number( $('[name=commission_discount]').val() );

	// convert real cost according to sale currency

	total = real_cost;

	discount = refine_number( $('[name=discount]').val() );
	discount_amount = 0;
	if(discount > 0)
	{
		discount_amount = ( total * discount) / 100;
	}

	gross_total = total - discount;
	$('[name=gross_total]').val(gross_total);

	cash_paid = refine_number( $('[name=cash_paid]').val() );
	pending_amount = commission - commission_dicsount - cash_paid;
	$('[name=pending_amount]').val(pending_amount);
}


$(document).on("click",".buyer-info-popup-trigger",function(e)
{
	e.preventDefault();
	name = $(this).attr("data-name");
	f_name = $(this).attr("data-f-name");
	tazkira = $(this).attr("data-tazkira");
	mobile = $(this).attr("data-mobile");
	address = $(this).attr("data-address");

	console.log(name);

	$("#buyer-info-name").text(name);
	$("#buyer-info-f-name").text(f_name);
	$("#buyer-mobile").text(tazkira);
	$("#buyer-tazkira").text(mobile);
	$("#buyer-address").text(address);

	$("#buyerInfoModal").modal("show");
});

$(document).on("click",".seller-info-popup-trigger",function(e)
{
	e.preventDefault();
	name = $(this).attr("data-name");
	tazkira = $(this).attr("data-tazkira");
	mobile = $(this).attr("data-mobile");
	address = $(this).attr("data-address");

	console.log(name);

	$("#seller-info-name").text(name);
	$("#seller-mobile").text(tazkira);
	$("#seller-tazkira").text(mobile);
	$("#seller-address").text(address);

	$("#sellerInfoModal").modal("show");
});



// ================================SERVICES SCRIPT=======================================================

$(document).on("keyup","#services-temp-form input[name=temp_rate], #services-temp-form input[name=temp_qty], #services-temp-form input[name=temp_discount]", function()
{
	services_item_total();
});

function services_item_total()
{
	rate = $("#services-temp-form input[name=temp_rate]").val();
	qty = $("#services-temp-form input[name=temp_qty]").val();
	discount = $("#services-temp-form input[name=temp_discount]").val();
	rate = refine_number(rate);
	qty = refine_number(qty);
	discount = refine_number(discount);

	total = rate * qty;
	total_amount = total - discount;
	$("#services-temp-form input[name=temp_total]").val(total_amount);
}



$(document).on('submit','#services-temp-form',function(e)
{
	e.preventDefault();

	type = $('#services-type-btns [type=radio]:checked').val();
	if(type == 'registered')
	{
		title_id = $('[name=temp_title_dp] option:selected').val();
		title = $('[name=temp_title_dp] option:selected').text();
	}
	else
	{
		title_id = '';
		title = $('[name=temp_title]').val();
	}

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency]').val();
	sdate = $('[name=temp_sdate]').val();
	client_name = $('[name=temp_client] option:selected').text();
	client = $('[name=temp_client]').val();
	marketer = $('[name=temp_marketer]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	unit = $('[name=temp_unit]').val();
	qty = $('[name=temp_qty]').val();
	rate = $('[name=temp_rate]').val();
	discount = $('[name=temp_discount]').val();
	total = $('[name=temp_total]').val();

	qty = refine_number(qty);
	rate = refine_number(rate);
	discount = refine_number(discount);
	total = refine_number(total);

	

	// populate data
	html_snippet = '<tr class="text-center services-item-row">';
        html_snippet += '<td class="services-item-self">';
            html_snippet += '<span>'+title+'</span>';
            html_snippet += '<input type="hidden" name="type[]" class="services-form-item-name" value="'+type+'">';
            html_snippet += '<input type="hidden" name="title_id[]" class="services-form-item-name" value="'+title_id+'">';
            html_snippet += '<input type="hidden" name="title[]" class="services-form-item-name" value="'+title+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="sdate[]" value="'+sdate+'">';
            html_snippet += '<input type="hidden" class="client_edit_input" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" class="marketer_edit_input" name="marketer[]" value="'+marketer+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" class="memo_edit_input" name="memo[]" value="'+memo+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-item-unit">';
            html_snippet += '<span>'+unit+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-item-qty">';
            html_snippet += '<span>'+qty+'</span>';
            html_snippet += '<input type="hidden" name="qty[]" value="'+qty+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-item-rate">';
        html_snippet += '<span>'+round_decimels(rate)+'</span>';
            html_snippet += '<input type="hidden" name="rate[]" value="'+rate+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-item-discount">';
        html_snippet += '<span>'+round_decimels(discount)+'</span>';
            html_snippet += '<input type="hidden" name="discount[]" value="'+discount+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-item-total">';
            html_snippet += '<span>'+round_decimels(total)+'</span>';
            html_snippet += '<input type="hidden" name="total[]" value="'+total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm services-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';
        

	$('#services-items-table-body').append(html_snippet);

	$('.services-fix-row').addClass('pointer-none');
	$('[name=temp_title]').val('');
	$('.service-registered-dp').val('').trigger('chosen:updated');
	$('[name=temp_unit]').val('');
	$('[name=temp_qty]').val('');
	$('[name=temp_rate]').val('');
	$('[name=temp_discount]').val('');
	$('[name=temp_total]').val('');

	handle_services_items_totals_calculation();
});


$(document).on('keyup','.services-totals-box .services-cash-received-row input',function(e){ handle_services_items_totals_calculation(); });
$(document).on('input','.services-totals-box .services-cash-received-row input',function(e){ handle_services_items_totals_calculation(); });


function handle_services_items_totals_calculation()
{
	sales_total = 0;

	total_discount = 0;
	total_amunt = 0;
	total_items_profit_amount = 0;

	if($('#services-items-table-body .services-item-row').length > 0)
	{
		$('#services-items-table-body .services-item-row').each(function(e)
		{
			// --------------------------------
			discount = $(this).find('.services-item-discount').find('input').val();
			total = $(this).find('.services-item-total').find('input').val();

			discount = refine_number(discount);
			total = refine_number(total);

			total_discount += discount;
			total_amunt += total;
			// --------------------------------
		});
	}

	// under table row totals
	services_totals = total_amunt + total_discount;

	$('.services-under-table-totals .total-services-cel span').text(round_decimels(services_totals));
	$('.services-under-table-totals .total-services-cel input').val(services_totals);
	$('.services-under-table-totals .total-diss-cel span').text(total_discount);
	$('.services-under-table-totals .total-diss-cel input').val(total_discount);
	$('.services-under-table-totals .gross-total-cel span').text(total_amunt);
	$('.services-under-table-totals .gross-total-cel input').val(total_amunt);

	// side table totals
	cash_received = $('.services-totals-box .services-cash-received-row input').val();
	cash_received = refine_number(cash_received);

	pending_amount = total_amunt - cash_received;

	$('.services-totals-box .services-total-amount-row input').val(total_amunt);
	$('.services-totals-box .services-total-amount-row span').text(round_decimels(total_amunt));

	$('.services-totals-box .services-remaining-amount-row input').val(pending_amount);
	$('.services-totals-box .services-remaining-amount-row span').text(round_decimels(pending_amount));
}

$(document).on('click','.services-item-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.services-item-row').remove();
	handle_services_items_totals_calculation();
});




$(document).on('ifChecked','#services-type-btns [type=radio]',function(e)
{
	type = $('#services-type-btns [type=radio]:checked').val();
	if(type == 'registered')
	{
		$('.manual-service-row').addClass('display-none');
		$('.registered-service-row').removeClass('display-none');
	}
	else
	{
		$('.manual-service-row').removeClass('display-none');
		$('.registered-service-row').addClass('display-none');
		$('[name=temp_unit]').val('');
		$('[name=temp_qty]').val('');
		$('[name=temp_rate]').val('');
		$('[name=temp_discount]').val('');
		$('[name=temp_total]').val('');
		$('.service-registered-dp').val('').trigger('chosen:updated');
	}
});


$(document).on("change",".service-registered-dp, #services-temp-form [name=temp_currency]",function()
{
	services_items_managing();
});

function services_items_managing()
{
	main_currency = $("#services-temp-form [name=temp_currency] option:selected").val();
	main_currency_equalance = $("#services-temp-form [name=temp_currency] option:selected").attr("data-usd-equalance");

	if(main_currency == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please select currency.', 'No Selection');
		$('.service-registered-dp').val('').trigger('chosen:updated');
		return false;
	}


	service = $('.service-registered-dp option:selected').val();
	service_name = $('.service-registered-dp option:selected').text();
	unit = $('.service-registered-dp option:selected').attr("data-unit");
	rate = $('.service-registered-dp option:selected').attr("data-rate");
	currency = $('.service-registered-dp option:selected').attr("data-currency");
	currency_equalance = $('.service-registered-dp option:selected').attr("data-currency-equalance");

	rate = refine_number(rate);

	if(main_currency != currency)
	{
		rate = amount_conversion(rate, currency_equalance, main_currency_equalance);
	}

	$("[name=temp_unit]").val(unit);
	$("[name=temp_rate]").val(rate);

	services_item_total();
}









// ================================SERVICES SCRIPT=======================================================





$(document).on("keyup","#services-quotation-temp-form input[name=temp_rate], #services-quotation-temp-form input[name=temp_qty], #services-quotation-temp-form input[name=temp_discount]", function()
{
	services_quotation_item_total();
});

function services_quotation_item_total()
{
	rate = $("#services-quotation-temp-form input[name=temp_rate]").val();
	qty = $("#services-quotation-temp-form input[name=temp_qty]").val();
	discount = $("#services-quotation-temp-form input[name=temp_discount]").val();
	rate = refine_number(rate);
	qty = refine_number(qty);
	discount = refine_number(discount);
	total = rate * qty;
	total_amount = total - discount;
	$("#services-quotation-temp-form input[name=temp_total]").val(total_amount);
}



$(document).on('submit','#services-quotation-temp-form',function(e)
{
	e.preventDefault();

	type = $('#services-qut-type-btns [type=radio]:checked').val();
	if(type == 'registered')
	{
		title_id = $('[name=temp_title_dp] option:selected').val();
		title = $('[name=temp_title_dp] option:selected').text();
	}
	else
	{
		title_id = '';
		title = $('[name=temp_title]').val();
	}

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency]').val();
	sdate = $('[name=temp_sdate]').val();
	client_name = $('[name=temp_client] option:selected').text();
	client = $('[name=temp_client]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	unit = $('[name=temp_unit]').val();
	qty = $('[name=temp_qty]').val();
	rate = $('[name=temp_rate]').val();
	discount = $('[name=temp_discount]').val();
	total = $('[name=temp_total]').val();

	qty = refine_number(qty);
	rate = refine_number(rate);
	discount = refine_number(discount);
	total = refine_number(total);

	

	// populate data
	html_snippet = '<tr class="text-center services-quotation-item-row">';
        html_snippet += '<td class="services-quotation-item-self">';
            html_snippet += '<span>'+title+'</span>';
            html_snippet += '<input type="hidden" name="type[]" class="services-form-item-name" value="'+type+'">';
            html_snippet += '<input type="hidden" name="title_id[]" class="services-form-item-name" value="'+title_id+'">';
            html_snippet += '<input type="hidden" name="title[]" class="services-quotation-form-item-name" value="'+title+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="sdate[]" value="'+sdate+'">';
            html_snippet += '<input type="hidden" class="client_edit_input" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" class="memo_edit_input" name="memo[]" value="'+memo+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-quotation-item-unit">';
            html_snippet += '<span>'+unit+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-quotation-item-qty">';
            html_snippet += '<span>'+qty+'</span>';
            html_snippet += '<input type="hidden" name="qty[]" value="'+qty+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-quotation-item-rate">';
        html_snippet += '<span>'+round_decimels(rate)+'</span>';
            html_snippet += '<input type="hidden" name="rate[]" value="'+rate+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-quotation-item-discount">';
        html_snippet += '<span>'+round_decimels(discount)+'</span>';
            html_snippet += '<input type="hidden" name="discount[]" value="'+discount+'" class="sales-editable-iputs">';
        html_snippet += '</td>';
        html_snippet += '<td class="services-quotation-item-total">';
            html_snippet += '<span>'+round_decimels(total)+'</span>';
            html_snippet += '<input type="hidden" name="total[]" value="'+total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm services-quotation-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';
        

	$('#services-quotation-items-table-body').append(html_snippet);

	$('.services-quotation-fix-row').addClass('pointer-none');
	$('[name=temp_title]').val('');
	$('.service-qut-registered-dp').val('').trigger('chosen:updated');
	$('[name=temp_unit]').val('');
	$('[name=temp_qty]').val('');
	$('[name=temp_rate]').val('');
	$('[name=temp_discount]').val('');
	$('[name=temp_total]').val('');

	handle_services_quotation_items_totals_calculation();
});


$(document).on('keyup','.services-quotation-totals-box .services-quotation-cash-received-row input',function(e){ handle_services_quotation_items_totals_calculation(); });
$(document).on('input','.services-quotation-totals-box .services-quotation-cash-received-row input',function(e){ handle_services_quotation_items_totals_calculation(); });


function handle_services_quotation_items_totals_calculation()
{
	sales_total = 0;

	total_discount = 0;
	total_amunt = 0;
	total_items_profit_amount = 0;

	if($('#services-quotation-items-table-body .services-quotation-item-row').length > 0)
	{
		$('#services-quotation-items-table-body .services-quotation-item-row').each(function(e)
		{
			// --------------------------------
			discount = $(this).find('.services-quotation-item-discount').find('input').val();
			total = $(this).find('.services-quotation-item-total').find('input').val();

			discount = refine_number(discount);
			total = refine_number(total);

			total_discount += discount;
			total_amunt += total;
			// --------------------------------
		});
	}

	// under table row totals
	services_totals = total_amunt + total_discount;

	$('.services-quotation-under-table-totals .total-services-quotation-cel span').text(round_decimels(services_totals));
	$('.services-quotation-under-table-totals .total-services-quotation-cel input').val(services_totals);
	$('.services-quotation-under-table-totals .total-diss-cel span').text(total_discount);
	$('.services-quotation-under-table-totals .total-diss-cel input').val(total_discount);
	$('.services-quotation-under-table-totals .gross-total-cel span').text(total_amunt);
	$('.services-quotation-under-table-totals .gross-total-cel input').val(total_amunt);

	// side table totals
	cash_received = $('.services-quotation-totals-box .services-quotation-cash-received-row input').val();
	cash_received = refine_number(cash_received);

	pending_amount = total_amunt - cash_received;

	$('.services-quotation-totals-box .services-quotation-total-amount-row input').val(total_amunt);
	$('.services-quotation-totals-box .services-quotation-total-amount-row span').text(round_decimels(total_amunt));

	$('.services-quotation-totals-box .services-quotation-remaining-amount-row input').val(pending_amount);
	$('.services-quotation-totals-box .services-quotation-remaining-amount-row span').text(round_decimels(pending_amount));
}

$(document).on('click','.services-quotation-item-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.services-quotation-item-row').remove();
	handle_services_quotation_items_totals_calculation();
});



$(document).on('ifChecked','#services-qut-type-btns [type=radio]',function(e)
{
	type = $('#services-qut-type-btns [type=radio]:checked').val();
	if(type == 'registered')
	{
		$('.manual-service-qut-row').addClass('display-none');
		$('.registered-service-qut-row').removeClass('display-none');
		$('[name=temp_unit]').prop('readonly',true);
		$('[name=temp_rate]').prop('readonly',true);
	}
	else
	{
		$('.manual-service-qut-row').removeClass('display-none');
		$('.registered-service-qut-row').addClass('display-none');
		$('[name=temp_unit]').prop('readonly',false);
		$('[name=temp_rate]').prop('readonly',false);
		$('[name=temp_unit]').val('');
		$('[name=temp_qty]').val('');
		$('[name=temp_rate]').val('');
		$('[name=temp_discount]').val('');
		$('[name=temp_total]').val('');
		$('.service-registered-qut-dp').val('').trigger('chosen:updated');
	}
});


$(document).on("change",".service-qut-registered-dp, #services-quotation-temp-form [name=temp_currency]",function()
{
	services_qut_items_managing();
});

function services_qut_items_managing()
{
	main_currency = $("#services-quotation-temp-form [name=temp_currency] option:selected").val();
	main_currency_equalance = $("#services-quotation-temp-form [name=temp_currency] option:selected").attr("data-usd-equalance");

	if(main_currency == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.error('Please select currency.', 'No Selection');
		$('.service-qut-registered-dp').val('').trigger('chosen:updated');
		return false;
	}


	service = $('.service-qut-registered-dp option:selected').val();
	service_name = $('.service-qut-registered-dp option:selected').text();
	unit = $('.service-qut-registered-dp option:selected').attr("data-unit");
	rate = $('.service-qut-registered-dp option:selected').attr("data-rate");
	currency = $('.service-qut-registered-dp option:selected').attr("data-currency");
	currency_equalance = $('.service-qut-registered-dp option:selected').attr("data-currency-equalance");

	rate = refine_number(rate);

	if(main_currency != currency)
	{
		rate = amount_conversion(rate, currency_equalance, main_currency_equalance);
	}

	$("[name=temp_unit]").val(unit);
	$("[name=temp_rate]").val(rate);

	services_quotation_item_total();
}



















$(document).on("click",".send-mails-trigger",function(e)
{
	e.preventDefault();
	
	$('.ibox-content').addClass('sk-loading');
	url = app_url()+'/send-mails';

	$.ajax(
	{
		url: url,
		type: 'POST',
		success: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.success('Payment alerts sent successfully to clients', 'Mails Sent');
				return false;
			}

			if(response.status == 'error')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error('No Clients found for sending mails', 'No Clients Found');
				return false;
			}
		}
	});
});


$(document).on("click",".send-message-trigger",function(e)
{
	e.preventDefault();
	
	$('.ibox-content').addClass('sk-loading');
	url = app_url()+'/send-message';

	$.ajax(
	{
		url: url,
		type: 'POST',
		success: function(response)
		{
			$('.ibox-content').removeClass('sk-loading');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.success('Payment alerts sent successfully to clients', 'Messages Sent');
				return false;
			}

			if(response.status == 'error')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 3000 };
				toastr.error('No Clients found for sending messages', 'No Clients Found');
				return false;
			}
		}
	});
});

$(document).on('change','#money-receipts-form select[name=currency], #money-receipts-form select[name=client]', function()
{
	currency = $('#money-receipts-form select[name=currency] option:selected').val();
	client = $('#money-receipts-form select[name=client] option:selected').val();

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/money-receipts/get-client-balance',
		data: {currency:currency,client:client},
		success: function(response)
		{
			$('#money-receipts-client-balance-span').text(response);
		}
	});
});

$(document).on('click','#receipts-check-all',function()
{
	$('input:checkbox').not(this).prop('checked', this.checked);
});

$(document).on('click','.receipts-approval-checkbox,#receipts-check-all',function()
{
	check_val = [];
	$("input:checkbox[name=approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});
});


$(document).on('click','.receipts-pending-item',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }

	account = $("#receipts-default-account option:selected").val();
	exchange_currency = $(".receipts-approval-exchange-currency option:selected").val();
	rate = $("#receipts-rate").val();
	receipts_formula = $("[name=receipts_formula]:checked").val();
	
	rate = refine_number(rate);
	
	if(account == null || account == '' || rate == 0 || rate == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select rate and default account to proceed.', 'No Selection');
		$('body').removeClass('inprocess');
		$('.ibox-content').removeClass('sk-loading');
		return false;
	}
	$('.ibox-content').addClass('sk-loading');
	pointer_obj = $(this);
	url = $(this).attr('data-url');
	check_val = [];
	$("input:checkbox[name=approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});
	$('body').addClass('inprocess');
	$.ajax(
	{
		type: 'POST',
		url: url,
		data: {account:account,uids:check_val,exchange_currency:exchange_currency, rate:rate, receipts_formula:receipts_formula},
		success: function(response)
		{
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.success('Receipt approved successfully.', 'Status Changed');
				$("input:checkbox[name=approval_checkbox]:checked").each(function(){
				    $(this).closest('tr').remove();
				});
				$('.ibox-content').removeClass('sk-loading');
			}
			else
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.error('No row selected.', 'Please select row');
				$('.ibox-content').removeClass('sk-loading');
			}
		}
	});

});



$(document).on('click','#activities-check-all',function()
{
	$('input:checkbox').not(this).prop('checked', this.checked);
});

$(document).on('click','.activities-approval-checkbox,#activities-check-all',function()
{
	check_val = [];
	$("input:checkbox[name=approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});
});


$(document).on('click','.activities-pending-item',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	account = $("#activities-default-account option:selected").val();
	exchange_currency = $(".activities-approval-exchange-currency option:selected").val();
	rate = $("#activities-rate").val();
	activities_formula = $("[name=activities_formula]:checked").val();
	rate = refine_number(rate);

	if(account == null || account == '' || rate == 0 || rate == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select default account and rate.', 'No Selection');
		$('body').removeClass('inprocess');
		$('.ibox-content').removeClass('sk-loading');
		return false;
	}
	
	pointer_obj = $(this);
	url = $(this).attr('data-url');

	check_val = [];
	$("input:checkbox[name=approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});

	if(check_val == null || check_val == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some activities.', 'No Selection');
		return false;
	}

	$('.ibox-content').addClass('sk-loading');
	$('body').addClass('inprocess');
	$.ajax(
	{
		type: 'POST',
		url: url,
		data: {account:account,uids:check_val,exchange_currency:exchange_currency, rate:rate, activities_formula:activities_formula},
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.success('Activities approved successfully.', 'Status Changed');
				$("input:checkbox[name=approval_checkbox]:checked").each(function(){
				    $(this).closest('tr').remove();
				});
				$('.ibox-content').removeClass('sk-loading');
			}
			else
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.error('No row selected.', 'Please select row');
				$('.ibox-content').removeClass('sk-loading');
			}
		}
	});

});


$(document).on('click','#dbcn-check-all',function()
{
	$('input:checkbox').not(this).prop('checked', this.checked);
});

$(document).on('click','.dbcn-passing-checkbox,#dbcn-check-all',function()
{
	check_val = [];
	$("input:checkbox[name=passing_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});
});

$(document).on('click','.dbcn-note-pass-elm',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	
	pointer_obj = $(this);
	url = $(this).attr('data-url');

	check_val = [];
	$("input:checkbox[name=passing_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});

	if(check_val == null || check_val == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some entries.', 'No Selection');
		return false;
	}

	$('.ibox-content').addClass('sk-loading');
	$('body').addClass('inprocess');
	$.ajax(
	{
		type: 'POST',
		url: url,
		data: {uids:check_val},
		success: function(response)
		{
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.success('Activities approved successfully.', 'Status Changed');

				$("input:checkbox[name=passing_checkbox]:checked").each(function(){
				    $(this).closest('tr').find('.dbcn-pending-item').addClass('display-none');
				    $(this).closest('tr').find('.dbcn-passed-item').removeClass('display-none');
				    $(this).css('display','none');
				});
				$('.ibox-content').removeClass('sk-loading');
			}
			else
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.error('No row selected.', 'Please select row');
				$('.ibox-content').removeClass('sk-loading');
			}
		}
	});

});


$(document).on('change','#refund-seach-invoice-form select[name=client]', function()
{
	client = $('#refund-seach-invoice-form select[name=client] option:selected').val();
	console.log(client);
	
	

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales-return/get-client-invoices',
		data: {client:client},
		success: function(response)
		{
			console.log(response);
			$('#refund-seach-invoice-form select[name=invoice]').html(response);
			$('#refund-seach-invoice-form select[name=invoice]').trigger('chosen:updated');
		}
	});
});


$(document).on('change','#client-balance-summary-search-form select[name=type_filter]',function()
{
	value = $('#client-balance-summary-search-form select[name=type_filter] option:selected').val();
	$('.ibox-content').addClass('sk-loading');
	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/get-balance-summary-filter-by',
		data: {value:value},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.ibox-content').removeClass('sk-loading');
			$('#client-balance-summary-search-form select[name=filter_by]').html(response.options);
			$('#client-balance-summary-search-form select[name=filter_by]').trigger('chosen:updated');

			$('#client-balance-summary-search-form select[name=account]').html(response.options_c);
			$('#client-balance-summary-search-form select[name=account]').trigger('chosen:updated');
		}
	});
});


$(document).on('change','#client-balance-summary-search-form select[name=filter_by]',function()
{
	value = $('#client-balance-summary-search-form select[name=filter_by] option:selected').val();
	type = $('#client-balance-summary-search-form select[name=type_filter] option:selected').val();
	$('.ibox-content').addClass('sk-loading');
	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/get-balance-summary-accounts',
		data: {value:value,type:type},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.ibox-content').removeClass('sk-loading');

			$('#client-balance-summary-search-form select[name=account]').html(response.options_c);
			$('#client-balance-summary-search-form select[name=account]').trigger('chosen:updated');
		}
	});
});



// on add and edit leave show confirm text
$(window).on('beforeunload', function(){
	page = $("#page_in_action").val();
	// if(page == 'add' || page == 'edit')
	// {
	// 	return 'Are you sure you want to leave?';
	// }
	// return 'Are you sure you want to leave?';
});

$(document).on("change",".temp_transfer_in_edit",function(){update_transfer_in_client();});
$(document).on("keyup input",".temp_p_memo_edit",function(){update_transfer_in_client();});

function update_transfer_in_client()
{
	client = $(".temp_transfer_in_edit").find(":selected").val();
	memo = $(".temp_p_memo_edit").val();
	$('.client_edit_input').val(client);
	$('.memo_p_edit_input').val(memo);
}


$(document).on('change','#temp-transfer-in-form [name=temp_item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	item_last_profit = $(this).find('option:selected').attr('data-last-profit');
	item_last_tp = $(this).find('option:selected').attr('data-tp');
	qty = $('[name=temp_qty]').val();

	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }


	$('[name=temp_qty]').val(qty);
	$('[name=temp_cost]').val(item_last_cost);
	$('[name=temp_profit]').val(item_last_profit);
	$('[name=temp_tp]').val(item_last_tp);

	// reset
	$('[name=temp_warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=temp_warehouse]').trigger('chosen:updated');
	// update
	$('[name=temp_warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=temp_warehouse]').trigger('chosen:updated');
	re_populate_punits_ti();
});

function re_populate_punits_ti()
{
	purchase_unit = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#temp-transfer-in-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#temp-transfer-in-form [name=temp_unit]').html(options_snippet);
	$('#temp-transfer-in-form [name=temp_unit]').trigger('chosen:updated');
}

$(document).on('change','#temp-transfer-in-form [name=temp_pdate]',function()
{
	value = $(this).val();
	$('.tr_in_date').val(value);
});

$(document).on('submit','#temp-transfer-in-form',function(e)
{
	e.preventDefault();

	currency = $('[name=temp_currency]').val();
	pdate = $('[name=temp_pdate]').val();
	client = $('[name=temp_client]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	item = $('[name=temp_item]').val();
	item_name = $('[name=temp_item] option:selected').text();
	warehouse = $('[name=temp_warehouse]').val();
	warehouse_name = $('[name=temp_warehouse] option:selected').text();
	batch = $('[name=temp_batch]').val();
	mfg = $('[name=temp_mfg]').val();
	expiry = $('[name=temp_expiry]').val();
	cost = $('[name=temp_cost]').val();
	unit = $('[name=temp_unit]').val();
	profit = $('[name=temp_profit]').val();
	tp = $('[name=temp_tp]').val();
	qty = $('[name=temp_qty]').val();
	bonus = $('[name=temp_bonus]').val();

	unit_name = null;
	if(unit == 'purchase'){ unit_name = $('[name=temp_item] option:selected').attr('data-purchase-unit'); }
	if(unit == 'sale'){ unit_name = $('[name=temp_item] option:selected').attr('data-sale-unit'); }
	if(unit == 'production'){ unit_name = $('[name=temp_item] option:selected').attr('data-production-unit'); }

	cost = refine_number(cost);
	qty = refine_number(qty);
	bonus = refine_number(bonus);
	profit = refine_number(profit);
	tp = refine_number(tp);

	first_cost = cost;

	// calculations
	sale_price = cost + parseFloat(profit);
	// sale_price = tp;

	// total_amount = parseFloat(qty) * parseFloat(cost);
	total_amount = parseFloat(qty) * parseFloat(cost);

	// populate data
	html_snippet = '<tr class="text-center transfer-in-item-row">';
	    html_snippet += '<td class="td-self-transfer-in">';
	        html_snippet += item_name;
	        html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
	        html_snippet += '<input type="hidden" name="pdate[]" value="'+pdate+'">';
	        html_snippet += '<input type="hidden" class="supplier_edit_input" name="client[]" value="'+client+'">';
	        html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
	        html_snippet += '<input type="hidden" class="memo_p_edit_input" name="memo[]" value="'+memo+'">';
	        html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
	        html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
	        html_snippet += '<input type="hidden" name="mfg[]" value="'+mfg+'">';
	        html_snippet += '<input type="hidden" name="expiry[]" value="'+expiry+'">';
	        html_snippet += '<input type="hidden" name="item[]" value="'+item+'">';
	        html_snippet += '<input type="hidden" name="bonus[]" value="'+bonus+'">';
	        html_snippet += '<input type="hidden" name="first_cost[]" class="first-cost" value="'+first_cost+'">';
	    html_snippet += '</td>';
	    html_snippet += '<td>'+unit_name+' <input type="hidden" name="unit[]" value="'+unit+'"></td>';
	    html_snippet += '<td class="qty-col" style="width: 60px;">'+qty+' <input type="hidden" name="qty[]" value="'+qty+'"></td>';
	    html_snippet += '<td class="cost-col"><span>'+cost+'</span><input type="hidden" class="transfer-in-editable-iputs" style="width: 75px;" name="cost[]" value="'+cost+'"></td>';
	    html_snippet += '<td class="profit-col"><input type="text" class="transfer-in-editable-iputs" style="width: 75px;" name="profit[]" value="'+profit+'"></td>';
	    html_snippet += '<td class="sale-price-col"><span>'+round_decimels(sale_price)+'</span> <input type="hidden" name="sale_price[]" value="'+sale_price+'"></td>';

	    html_snippet += '<td class="transfer-in-item-discount">';
	        html_snippet += '<input type="text" style="width: 80px;" name="discount[]" value="" class="transfer-in-editable-iputs">';
	    html_snippet += '</td>';

	    html_snippet += '<td class="transfer-in-item-discount-2">';
	        html_snippet += '<input type="text" style="width: 80px;" name="discount_2[]" value="" class="transfer-in-editable-iputs">';
	    html_snippet += '</td>';


	    html_snippet += '<td class="tp-col"><input type="text" class="transfer-in-editable-iputs" style="width: 75px;" name="tp[]" value="'+tp+'"></td>';
	    html_snippet += '<td class="total-amount-col"><span>'+round_decimels(total_amount)+'</span> <input type="hidden" name="total[]" value="'+total_amount+'"></td>';
	    html_snippet += '<td style="width: 40px;"><a class="btn btn-danger btn-sm transfer-in-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a></td>';
	html_snippet += '</tr>';

	$('#transfer-in-table-body').append(html_snippet);

	// reset form inputs
	$('#temp-transfer-in-form').trigger("reset");

	// populate main fields values
	$('[name=temp_currency] option[value='+currency+']').prop('selected',true);
	$('[name=temp_client] option[value='+client+']').prop('selected',true);
	$('[name=temp_invoice]').val(invoice);
	$('[name=temp_memo]').val(memo);

	// make main fields readonly
	$('.fixed-fields-row').addClass('pointer-none');

	$('[name=temp_qty]').removeClass('pointer-none').prop('readonly',false);

	options_snippet = '<option disabled="" selected="">-- Unit --</option>';
	$('[name=temp_unit]').html(options_snippet);

	// re-initialise chosen selects
	$(".chosen-select").trigger('chosen:updated');

	$('[name=temp_warehouse] option').addClass('display-none');
	$('[name=temp_warehouse] [data-opt-type=default]').removeClass('display-none').prop('selected',true);
	$('[name=temp_warehouse]').trigger('chosen:updated');

	handle_transfer_in_totals();
});


// delete transfer in item
$(document).on('click','.transfer-in-item-del-trigger',function(e)
{
	e.preventDefault();	
	$(this).closest('.transfer-in-item-row').remove();
	handle_transfer_in_totals();
});


// handle purchases totals after alteration
function handle_transfer_in_totals()
{
	total_amounts = 0;
	total_amounts_all = 0;
	discount_amounts = 0;
	total_items_discount_amount = 0;
	total_items_discount_2_amount = 0;

	if($('#transfer-in-table-body .transfer-in-item-row').length > 0)
	{
		$('#transfer-in-table-body .transfer-in-item-row').each(function(e)
		{
			item_total_amount = $(this).find('.total-amount-col').find('input').val();
			sale_price = $(this).find('.tp-col').find('input').val();
			cost = $(this).find('.cost-col').find('input').val();
			first_cost = $(this).find('.first-cost').val();
			qty = $(this).find('.qty-col').find('input').val();
			dis_1 = $(this).find('.transfer-in-item-discount').find('input').val();
			dis_2 = $(this).find('.transfer-in-item-discount-2').find('input').val();

			item_total_amount = refine_number(item_total_amount);
			cost = refine_number(cost);
			sale_price = refine_number(sale_price);
			first_cost = refine_number(first_cost);
			qty = refine_number(qty);
			dis_1 = refine_number(dis_1);
			dis_2 = refine_number(dis_2);


			total_amounts_all += cost * qty;

			dis_1_amount = (cost * dis_1) / 100;
			dis_2_amount = ((cost - dis_1_amount) * dis_2) / 100;

			item_total_amount = cost - dis_1_amount - dis_2_amount;
			total_amounts += item_total_amount * qty;

			item_total_discount_amount = dis_1_amount * qty;
			item_total_discount_amount_2 = dis_2_amount * qty;

			total_items_discount_amount += item_total_discount_amount;
			total_items_discount_2_amount += item_total_discount_amount_2;

		});
	}

	$('.transfer-in-totals-col .transfer-in-sub-total-amount-row span').text(round_decimels(total_amounts));
	$('.transfer-in-totals-col .transfer-in-sub-total-amount-row input').val(total_amounts);

	$('.transfer-in-totals-col .transfer-in-total-amount-row span').text(round_decimels(total_amounts_all));
	$('.transfer-in-totals-col .transfer-in-total-amount-row input').val(total_amounts_all);

	$('.transfer-in-totals-col .transfer-in-total-discount-row span').text(round_decimels(total_items_discount_amount + total_items_discount_2_amount));
	$('.transfer-in-totals-col .transfer-in-total-discount-row input').val(total_items_discount_amount + total_items_discount_2_amount);
	$('.transfer-in-discount-amount-1').val(total_items_discount_amount);
	$('.transfer-in-discount-amount-2').val(total_items_discount_2_amount);

	paid_amount = $('.transfer-in-totals-col .transfer-in-paid-amount-row input').val();
	paid_amount = refine_number(paid_amount);
	pending_amount = total_amounts - paid_amount;
	$('.transfer-in-totals-col .transfer-in-remaining-amount-row span').text(round_decimels(pending_amount));
	$('.transfer-in-totals-col .transfer-in-remaining-amount-row input').val(pending_amount);
}

$(document).on('keyup','.transfer-in-totals-col [name=paid_amount]',function(e){ handle_transfer_in_totals(); });
$(document).on('input','.transfer-in-totals-col [name=paid_amount]',function(e){ handle_transfer_in_totals(); });

$(document).on('keyup','.transfer-in-editable-iputs',function(e){ handle_transfer_in_row_alteration($(this)); });
$(document).on('input','.transfer-in-editable-iputs',function(e){ handle_transfer_in_row_alteration($(this)); });

function handle_transfer_in_row_alteration(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.transfer-in-item-row');

	first_cost = pointer_parent.find('.first-cost').val();
	cost = pointer_parent.find('.cost-col').find('input').val();
	sale_price = pointer_parent.find('.tp-col').find('input').val();
	tp = pointer_parent.find('.tp-col').find('input').val();
	profit = pointer_parent.find('.profit-col').find('input').val();
	qty = pointer_parent.find('.qty-col').find('input').val();
	dis_1 = pointer_parent.find('.transfer-in-item-discount').find('input').val();
	dis_2 = pointer_parent.find('.transfer-in-item-discount-2').find('input').val();

	first_cost = refine_number(first_cost);
	cost = refine_number(cost);
	profit = refine_number(profit);
	qty = refine_number(qty);
	dis_1 = refine_number(dis_1);
	dis_2 = refine_number(dis_2);
	

	dis_1_amount = (cost * dis_1) / 100;
	dis_2_amount = ((cost - dis_1_amount) * dis_2) / 100;
	sale_price = sale_price - dis_1_amount - dis_2_amount;
	// calculations
	// sale_price = cost + profit;
	pointer_parent.find('.sale-price-col').find('input').val(sale_price);
	pointer_parent.find('.sale-price-col').find('span').text(sale_price);
	cost = first_cost - dis_1_amount - dis_2_amount;

	// cost = cost - dis_2_amount;

	total_amount = cost * qty;

	pointer_parent.find('.sale-price-col').find('span').text(round_decimels(sale_price));
	pointer_parent.find('.sale-price-col').find('input').val(sale_price);
	pointer_parent.find('.total-amount-col').find('span').text(round_decimels(total_amount));
	pointer_parent.find('.total-amount-col').find('input').val(total_amount);

	handle_transfer_in_totals();
}




$(document).on('change','#transfer-out-items-temp-form [name=temp_item]',function(e)
{
	item = $('#transfer-out-items-temp-form [name=temp_item] option:selected').val();
	warehouse = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-warehouse');

	purchase_unit = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#transfer-out-items-temp-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#transfer-out-items-temp-form [name=temp_batch]').html(response);
			$('#transfer-out-items-temp-form [name=temp_batch]').trigger('chosen:updated');
		}
	});

	$('#transfer-out-items-temp-form [name=temp_unit]').html(options_snippet);
	$('#transfer-out-items-temp-form [name=temp_unit]').trigger('chosen:updated');
});


$(document).on('submit','#transfer-out-items-temp-form',function(e)
{
	e.preventDefault();

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency]').val();
	sdate = $('[name=temp_sdate]').val();
	client_name = $('[name=temp_client] option:selected').text();
	client = $('[name=temp_client]').val();
	marketer = $('[name=temp_marketer]').val();
	invoice = $('[name=temp_invoice]').val();
	memo = $('[name=temp_memo]').val();
	batch_name = $('[name=temp_batch] option:selected').text();
	batch = $('[name=temp_batch]').val();
	bonus = $('[name=temp_bonus]').val();
	qty = $('[name=temp_qty]').val();
	narration = $('[name=temp_narration]').val();

	item = $('[name=temp_item]').val();
	item_name = $('[name=temp_item] option:selected').attr('data-item-name');
	item_currency = $('[name=temp_item] option:selected').attr('data-item-currency');
	item_currency_usd_equalance = $('[name=temp_item] option:selected').attr('data-usd-equalance');
	warehouse = $('[name=temp_item] option:selected').attr('data-warehouse');
	warehouse_name = $('[name=temp_item] option:selected').attr('data-warehouse-name');
	// profit = $('[name=temp_item] option:selected').attr('data-profit');
	profit = $('[name=temp_batch] option:selected').attr('data-profit');
	sale_price = $('[name=temp_batch] option:selected').attr('data-sale-price');
	mfg = $('[name=temp_batch] option:selected').attr('data-mfg');
	expiry = $('[name=temp_batch] option:selected').attr('data-expiry');
	avg_cost = $('[name=temp_item] option:selected').attr('data-cost');
	// avail_units = $('[name=temp_item] option:selected').attr('data-avail-units');
	avail_units = $('[name=temp_batch] option:selected').attr('data-ava-units');
	option_reference = $('[name=temp_item] option:selected').attr('data-opt-ref');

	avail_units = refine_number(avail_units);
	avg_cost = refine_number(avg_cost);
	profit = refine_number(profit);
	sale_price = refine_number(sale_price);
	qty = refine_number(qty);

	// apply unit based conversion
	unit = $('[name=temp_unit]').val();
	unit_name = null;
	unit_equalance = 1;
	if(unit == 'purchase')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-purchase-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-purchase-unit-equalance');
	}

	if(unit == 'sale')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-sale-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-sale-unit-equalance');
	}

	if(unit == 'production')
	{
		unit_name = $('[name=temp_item] option:selected').attr('data-production-unit');
		unit_equalance = $('[name=temp_item] option:selected').attr('data-production-unit-equalance');
	}

	avail_units = unit_based_conversion(unit_equalance,unit,avail_units);
	avg_cost = amount_unit_based_conversion(unit_equalance,unit,avg_cost);
	profit = amount_unit_based_conversion(unit_equalance,unit,profit);
	sale_price = amount_unit_based_conversion(unit_equalance,unit,sale_price);



	// check if used qty is within avail limit
	// if(qty > avail_units)
	// {
	// 	toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
	// 	toastr.error('Item do not have sufficient quantity to sale.', "Insufficient Quantity");
	// 	return false;
	// }
	if(currency == item_currency)
	{
		currency_usd_equalance = item_currency_usd_equalance;
	}

	// convert avg cost according to sale currency
	avg_cost = amount_conversion(avg_cost, item_currency_usd_equalance, currency_usd_equalance);
	profit = amount_conversion(profit, item_currency_usd_equalance, currency_usd_equalance);
	sale_price = amount_conversion(sale_price, item_currency_usd_equalance, currency_usd_equalance);
	profit = sale_price - avg_cost;
	// sale_price = avg_cost + profit;

	// if user has no right for system profit than show cost and profit 0
	// system_profit = $("#system_profit").val();
	// if(system_profit == 'yes')
	// {
	// 	system_profit_val = profit;
	// 	system_profit_cost = avg_cost;
	// }
	// else
	// {
	// 	system_profit_val = 0;
	// 	system_profit_cost = 0;
	// }

	system_profit_val = profit;
	system_profit_cost = avg_cost;

	item_total = sale_price * qty;

	// populate data
	html_snippet = '<tr class="text-center transfer-out-item-row">';
        html_snippet += '<td class="transfer-out-item-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="item[]" class="sale-form-item-name" value="'+item+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" name="sdate[]" value="'+sdate+'">';
            html_snippet += '<input type="hidden" class="client_edit_input" name="client[]" value="'+client+'">';
            html_snippet += '<input type="hidden" class="marketer_edit_input" name="marketer[]" value="'+marketer+'">';
            html_snippet += '<input type="hidden" name="invoice[]" value="'+invoice+'">';
            html_snippet += '<input type="hidden" class="memo_edit_input" name="memo[]" value="'+memo+'">';
            html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
            html_snippet += '<input type="hidden" name="bonus[]" value="'+bonus+'">';
            html_snippet += '<input type="hidden" name="mfg[]" value="'+mfg+'">';
            html_snippet += '<input type="hidden" name="expiry[]" value="'+expiry+'">';
            html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
            html_snippet += '<input type="hidden" name="narration[]" value="'+narration+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="transfer-out-item-warehouse">';
            html_snippet += '<span>'+unit_name+'</span>';
            html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="transfer-out-item-cost">';
            html_snippet += '<span>'+round_decimels(system_profit_cost)+'</span>';
            html_snippet += '<input type="hidden" name="cost[]" value="'+avg_cost+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="transfer-out-item-sale-price">';
            html_snippet += '<input type="text" name="sale_price[]" style="width:75px;" value="'+sale_price+'" class="transfer-out-editable-iputs">';
        html_snippet += '</td>';

        html_snippet += '<td class="transfer-out-item-qty">';
            html_snippet += '<input type="text" name="qty[]" style="width:75px;" value="'+qty+'" class="transfer-out-editable-iputs">';
        html_snippet += '</td>';

        html_snippet += '<td class="transfer-out-item-discount">';
            html_snippet += '<input type="text" name="discount[]" style="width:75px;" value="" class="transfer-out-editable-iputs">';
        html_snippet += '</td>';

        html_snippet += '<td class="transfer-out-item-discount-2">';
            html_snippet += '<input type="text" name="discount_2[]" style="width:75px;" value="" class="transfer-out-editable-iputs">';
        html_snippet += '</td>';
        
        html_snippet += '<td class="transfer-out-item-profit">';
            html_snippet += '<span>'+round_decimels(system_profit_val)+'</span>';
            html_snippet += '<input type="hidden" name="profit[]" value="'+profit+'">';
        html_snippet += '</td>';        
        
        html_snippet += '<td class="transfer-out-item-total">';
            html_snippet += '<span>'+round_decimels(item_total)+'</span>';
            html_snippet += '<input type="hidden" name="item_total[]" value="'+item_total+'">';
        html_snippet += '</td>';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm transfer-out-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';


    if(avail_units <= 0 || avail_units < qty)
    {
    	swal(
    	{
    	    title: 'Are you sure?',
    	    text: 'Item qty is 0 or less than entered qty!',
    	    html: true,
    	    type: false,
    	    showCancelButton: true,
    	    cancelButtonText: 'Cancel',
    	    confirmButtonColor: "#1ab394",
    	    confirmButtonText: 'Continue',
    	    closeOnConfirm: true
    	},
    	function()
    	{
	    	$('#transfer-out-items-table-body').append(html_snippet);

			$('.transfer-out-fix-row').addClass('pointer-none');
			$('[name=temp_item]').prop('selectedIndex',0);
			$('[name=temp_item]').trigger('chosen:updated');
			$('[name=temp_batch]').prop('selectedIndex',0);
			$('[name=temp_batch]').trigger('chosen:updated');
			$('[name=temp_qty]').val('');
			$('[name=temp_narration]').val('');

			handle_transfer_out_items_totals_calculation();
    	});
    }
    else
    {
    	$('#transfer-out-items-table-body').append(html_snippet);

		$('.transfer-out-fix-row').addClass('pointer-none');
		$('[name=temp_item]').prop('selectedIndex',0);
		$('[name=temp_item]').trigger('chosen:updated');
		$('[name=temp_batch]').prop('selectedIndex',0);
		$('[name=temp_batch]').trigger('chosen:updated');
		$('[name=temp_qty]').val('');
		$('[name=temp_narration]').val('');

		handle_transfer_out_items_totals_calculation();
    }
});

function handle_transfer_out_items_totals_calculation()
{
	sales_total = 0;

	total_items_sale_amount = 0;
	total_items_discount_amount = 0;
	total_items_discount_2_amount = 0;
	total_items_profit_amount = 0;

	if($('#transfer-out-items-table-body .transfer-out-item-row').length > 0)
	{
		$('#transfer-out-items-table-body .transfer-out-item-row').each(function(e)
		{
			// --------------------------------
			sale_price = $(this).find('.transfer-out-item-sale-price').find('input').val();
			cost = $(this).find('.transfer-out-item-cost').find('input').val();
			qty = $(this).find('.transfer-out-item-qty').find('input').val();
			discount = $(this).find('.transfer-out-item-discount').find('input').val();
			discount_2 = $(this).find('.transfer-out-item-discount-2').find('input').val();

			sale_price = refine_number(sale_price);
			cost = refine_number(cost);
			qty = refine_number(qty);
			discount = refine_number(discount);
			discount_2 = refine_number(discount_2);

			discount_amount = (sale_price * discount) / 100;
			discount_amount_2 = ((sale_price - discount_amount) * discount_2) / 100;

			tb_sale_price = sale_price - discount_amount;

			profit = tb_sale_price - cost;

			real_qty = qty;

			item_total_sale_amount = sale_price * real_qty;
			item_total_discount_amount = discount_amount * real_qty;
			item_total_discount_amount_2 = discount_amount_2 * real_qty;
			item_total_profit_amount = profit * real_qty;

			total_items_sale_amount += item_total_sale_amount;
			total_items_discount_amount += item_total_discount_amount;
			total_items_discount_2_amount += item_total_discount_amount_2;
			total_items_profit_amount += item_total_profit_amount;
			// --------------------------------

			// --------------------------------
			row_item_total = $(this).find('.transfer-out-item-total').find('input').val();
			row_item_total = refine_number(row_item_total);
			sales_total += row_item_total;
			// --------------------------------
		});
	}

	// if user has no right for system profit than show cost and profit 0
	// system_profit = $("#system_profit").val();
	// if(system_profit == 'yes')
	// {
	// 	system_profit_val = total_items_profit_amount;
	// }
	// else
	// {
	// 	system_profit_val = 0;
	// }

	system_profit_val = total_items_profit_amount;

	sale_gross_total_amount = total_items_sale_amount - total_items_discount_amount - total_items_discount_2_amount;

	$('.transfer-out-under-table-totals .total-transfer-out-cel span').text(round_decimels(total_items_sale_amount));
	$('.transfer-out-under-table-totals .total-transfer-out-cel input').val(total_items_sale_amount);

	$('.transfer-out-under-table-totals .total-discount-transfer-out-cel span').text(round_decimels(total_items_discount_amount + total_items_discount_2_amount));
	$('.transfer-out-under-table-totals .total-discount-transfer-out-cel input').val(total_items_discount_amount + total_items_discount_2_amount);
	$('.transfer-out-discount-amount-1').val(total_items_discount_amount);
	$('.transfer-out-discount-amount-2').val(total_items_discount_2_amount);

	$('.transfer-out-under-table-totals .total-profit-cel span').text(round_decimels(system_profit_val));
	$('.transfer-out-under-table-totals .total-profit-cel input').val(total_items_profit_amount);

	$('.transfer-out-under-table-totals .total-gross-transfer-out-cel span').text(round_decimels(sale_gross_total_amount));
	$('.transfer-out-under-table-totals .total-gross-transfer-out-cel input').val(sale_gross_total_amount);

	cash_received = $('.transfer-out-under-table-totals .transfer-out-cash-received-amount-row input').val();
	cash_received = refine_number(cash_received);
	pending_amount = sale_gross_total_amount - cash_received;
	$('.transfer-out-under-table-totals .transfer-out-remaining-amount-row span').text(round_decimels(pending_amount));
	$('.transfer-out-under-table-totals .transfer-out-remaining-amount-row input').val(pending_amount);
}

$(document).on('keyup','.transfer-out-under-table-totals [name=cash_received]',function(e){ handle_transfer_out_items_totals_calculation(); });
$(document).on('input','.transfer-out-under-table-totals [name=cash_received]',function(e){ handle_transfer_out_items_totals_calculation(); });

$(document).on('click','.transfer-out-item-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.transfer-out-item-row').remove();
	handle_transfer_out_items_totals_calculation();
});


$(document).on('keyup','.transfer-out-item-sale-price input, .transfer-out-item-discount input, .transfer-out-item-discount-2, .transfer-out-item-qty input',function(e){ handle_transfer_out_items_row_alterations($(this)); });
$(document).on('input','.transfer-out-item-sale-price input, .transfer-out-item-discount input, .transfer-out-item-discount-2, .transfer-out-item-qty input',function(e){ handle_transfer_out_items_row_alterations($(this)); });

$(document).on("change",".temp_transfer_out_edit",function(){update_transfer_out_client();});
$(document).on("keyup input",".temp_p_memo_edit",function(){update_transfer_out_client();});

function update_transfer_out_client()
{
	client = $(".temp_transfer_out_edit").find(":selected").val();
	memo = $(".temp_p_memo_edit").val();
	$('.client_edit_input').val(client);
	$('.memo_p_edit_input').val(memo);
}


function handle_transfer_out_items_row_alterations(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.transfer-out-item-row');
	sale_price = pointer_parent.find('.transfer-out-item-sale-price').find('input').val();
	cost = pointer_parent.find('.transfer-out-item-cost').find('input').val();
	qty = pointer_parent.find('.transfer-out-item-qty').find('input').val();
	discount = pointer_parent.find('.transfer-out-item-discount').find('input').val();
	discount_2 = pointer_parent.find('.transfer-out-item-discount-2').find('input').val();

	sale_price = refine_number(sale_price);
	cost = refine_number(cost);
	qty = refine_number(qty);
	discount = refine_number(discount);
	discount_2 = refine_number(discount_2);

	discount_amount = (sale_price * discount) / 100;
	discount_2_amount = ((sale_price - discount_amount) * discount_2) / 100;

	sale_price = sale_price - discount_amount;
	profit = sale_price - cost;

	sale_price = sale_price - discount_2_amount;

	item_total = sale_price * qty;

	// if user has no right for system profit than show cost and profit 0
	// system_profit = $("#system_profit").val();
	// if(system_profit == 'yes')
	// {
	// 	system_profit_val = profit;
	// 	system_profit_cost = cost;
	// }
	// else
	// {
	// 	system_profit_val = 0;
	// 	system_profit_cost = 0;
	// }

	system_profit_val = profit;
	system_profit_cost = cost;

	// populate profit
	pointer_parent.find('.transfer-out-item-profit').find('input').val(profit);
	pointer_parent.find('.transfer-out-item-profit').find('span').text(round_decimels(system_profit_val));
	// populate item total
	pointer_parent.find('.transfer-out-item-total').find('input').val(item_total);
	pointer_parent.find('.transfer-out-item-total').find('span').text(round_decimels(item_total));

	handle_transfer_out_items_totals_calculation();
}

$(document).on("change","#journal-form [name=receiving_currency], #journal-form [name=receiving_account]",function(){ journal_receiving_account_balance(); });

function journal_receiving_account_balance()
{
	currency = $('#journal-form [name=receiving_currency] option:selected').val();
	client = $('#journal-form [name=receiving_account] option:selected').val();

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/money-receipts/get-client-balance',
		data: {currency:currency,client:client},
		success: function(response)
		{
			$('#receiving_account_span').text(response);
		}
	});
}

$(document).on("change","#journal-form [name=payment_currency], #journal-form [name=payment_account]",function(){ journal_payment_account_balance(); });

function journal_payment_account_balance()
{
	currency = $('#journal-form [name=payment_currency] option:selected').val();
	client = $('#journal-form [name=payment_account] option:selected').val();

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/money-receipts/get-client-balance',
		data: {currency:currency,client:client},
		success: function(response)
		{
			$('#payment_account_span').text(response);
		}
	});
}

$(document).on('change','#damage-stock-form [name=warehouse], #damage-stock-form [name=item]', function()
{
	item = $('#damage-stock-form [name=item] option:selected').val();
	warehouse = $('#damage-stock-form [name=warehouse] option:selected').val();
	
	if($.trim(item).length != 0 && $.trim(warehouse).length != 0)
	{
		$.ajax(
		{
			type: 'POST',
			url: app_url()+'/sales/get-items-batch',
			data: {item:item,warehouse:warehouse},
			success: function(response)
			{
				console.log(response);
				$('#damage-stock-form [name=batch]').html(response);
				$('#damage-stock-form [name=batch]').trigger('chosen:updated');
			}
		});
	}
	
});


// DEBIT CREDIT NOTE SCRIPT=======================================================================

$(document).on('ifChecked','#temp-debit-credit-form [type=radio][name=type]', function()
{
	type = $('#temp-debit-credit-form [type=radio][name=type]:checked').val();
	debit_account = $('#debit-type-account').text();
	debit_amount = $('#debit-type-amount').text();
	credit_account = $('#credit-type-account').text();
	credit_amount = $('#credit-type-amount').text();

	console.log(type);
	console.log(debit_account);
	console.log(debit_amount);
	console.log(credit_account);
	console.log(credit_amount);

	if(type == 'debit')
	{
		$('.main-account-label').text(debit_account);
		$('.main-amount-label').text(debit_amount);
		$('.d-account-label').text(credit_account);
		$('.d-amount-label').text(credit_amount);
	}
	else
	{
		$('.main-account-label').text(credit_account);
		$('.main-amount-label').text(credit_amount);
		$('.d-account-label').text(debit_account);
		$('.d-amount-label').text(debit_amount);
	}
});



$(document).on('submit','#temp-debit-credit-form',function(e)
{
	e.preventDefault();

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency] option:selected').val();
	account_name = $('[name=temp_account] option:selected').text();
	account = $('[name=temp_account] option:selected').val();
	amount = $('[name=temp_amount]').val();
	d_account_name = $('[name=temp_d_account] option:selected').text();
	d_account_type = $('[name=temp_d_account] option:selected').attr('data-account-type');
	d_account = $('[name=temp_d_account] option:selected').val();
	d_amount = $('[name=temp_d_amount]').val();
	narration = $('[name=temp_narration]').val();
	type = $('#temp-debit-credit-form input[name="type"]:checked').val();
	if(type == 'debit')
	{
		d_type = 'credit';
	}
	else
	{
		d_type = 'debit';
	}

	amount = refine_number(amount);
	d_amount = refine_number(d_amount);

	// populate data
	html_snippet = '<tr class="text-center debit-credit-note-row">';
        html_snippet += '<td class="debit-credit-note-self">';
            html_snippet += '<span>'+d_account_name+'</span>';
            html_snippet += '<input type="hidden" name="d_account[]" value="'+d_account+'">';
            html_snippet += '<input type="hidden" name="d_account_type[]" value="'+d_account_type+'">';
            html_snippet += '<input type="hidden" class="debit-credit-note-account"  name="account[]" value="'+account+'">';
            html_snippet += '<input type="hidden" class="debit-credit-note-currency"  name="currency[]" value="'+currency+'">';
            html_snippet += '<input type="hidden" class="debit-credit-note-account-type" name="type[]" value="'+type+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="debit-credit-note-type">';
            html_snippet += '<span>'+d_type+'</span>';
            html_snippet += '<input type="hidden" name="d_type[]" value="'+d_type+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="debit-credit-note-d-amount">';
            html_snippet += '<input type="text" style="width: 100px; text-align: center;" class="debit-credit-note-editable-iput" name="d_amount[]" value="'+d_amount+'">';
        html_snippet += '</td>';

        html_snippet += '<td class="debit-credit-note-narration">';
            html_snippet += '<span>'+narration+'</span>';
            html_snippet += '<input type="hidden" name="narration[]" value="'+narration+'">';
        html_snippet += '</td>';

        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm debit-credit-note-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';


	$('#debit-credit-note-table-body').append(html_snippet);

	// $('.fixed-fields-row').addClass('pointer-none');
	$('[name=temp_d_account]').prop('selectedIndex',0);
	$('[name=temp_d_account]').trigger('chosen:updated');
	$('[name=temp_d_amount]').val('');
	$('[name=temp_narration]').val('');

	handle_debit_credit_note_totals_calculation();
});

$(document).on('keyup','#temp-debit-credit-form [name=main_temp_narration]',function()
{
	set_debit_credit_note_narration();
});

$(document).on('change','#temp-debit-credit-form [name=temp_currency], #temp-debit-credit-form [name=temp_account]',function()
{
	set_debit_credit_note_debit_details();
});

$(document).on('keyup','#temp-debit-credit-form [name=main_temp_narration]',function()
{
	set_debit_credit_note_debit_details();
});

$(document).on('click','#temp-debit-credit-form input[name="type"]',function()
{
	set_debit_credit_note_debit_details();
});

function set_debit_credit_note_debit_details()
{
	account = $("#temp-debit-credit-form [name=temp_account] option:selected").val();
	type = $('#temp-debit-credit-form input[name="type"]:checked').val();
	currency = $("#temp-debit-credit-form [name=temp_currency] option:selected").val();
	details = $("#temp-debit-credit-form [name=main_temp_narration]").val();

	$('.debit-credit-note-account').val(account);
	$('.debit-credit-note-account-type').val(type);
	$('.debit-credit-note-narration').val(details);
	$('.debit-credit-note-currency').val(currency);
}

$(document).on('input','#temp-debit-credit-form [name=main_temp_narration]',function()
{
	set_debit_credit_note_narration();
});
function set_debit_credit_note_narration()
{
	narration = $('#temp-debit-credit-form [name=main_temp_narration]').val();
	$('#debit-credit-note-form [name=main_narration]').val(narration);
}

$(document).on('input','#temp-debit-credit-form [name=temp_amount], .debit-credit-note-editable-iput',function()
{
	handle_debit_credit_note_totals_calculation();
});

$(document).on('keyup','#temp-debit-credit-form [name=temp_amount], .debit-credit-note-editable-iput',function()
{
	handle_debit_credit_note_totals_calculation();
});

function handle_debit_credit_note_totals_calculation()
{
	a_amount_total = 0;
	amount_total = 0;
	pending_total = 0;

	if($('#debit-credit-note-table-body .debit-credit-note-row').length > 0)
	{
		$('#debit-credit-note-table-body .debit-credit-note-row').each(function(e)
		{
			// --------------------------------
			d_amount = $(this).find('.debit-credit-note-d-amount').find('input').val();

			d_amount = refine_number(d_amount);

			amount_total += d_amount;
			// --------------------------------
		});
	}

	a_amount_total = $('#temp-debit-credit-form [name=temp_amount]').val();
	pending_total = refine_number(a_amount_total) - refine_number(amount_total);

	$('.debit-credit-note-totals-col .debit-credit-note-total-main-cel span').text(round_numbers_3(a_amount_total));
	$('.debit-credit-note-totals-col .debit-credit-note-total-main-cel input').val(round_numbers_3(a_amount_total));

	$('.debit-credit-note-totals-col .debit-credit-note-total-cel span').text(round_numbers_3(amount_total));
	$('.debit-credit-note-totals-col .debit-credit-note-total-cel input').val(round_numbers_3(amount_total));

	$('.debit-credit-note-totals-col .debit-credit-note-pending-cel span').text(round_numbers_3(pending_total));
	$('.debit-credit-note-totals-col .debit-credit-note-pending-cel input').val(round_numbers_3(pending_total));
}

$(document).on('click','.debit-credit-note-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.debit-credit-note-row').remove();
	handle_debit_credit_note_totals_calculation();
});







// DEBIT CREDIT NOTE SCRIPT=======================================================================


// BOOKINGS SCRIPT=======================================================================

$(document).on('submit','#temp-bookings-form',function(e)
{
	e.preventDefault();

	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency_name = $('[name=temp_currency] option:selected').text();
	currency = $('[name=temp_currency] option:selected').val();
	pdate = $('[name=temp_pdate]').val();
	memo = $('[name=temp_memo]').val();
	item = $('[name=temp_item]').val();
	item_name = $('[name=temp_item] option:selected').text();
	item_currency = $('[name=temp_item] option:selected').attr('data-item-currency');
	item_currency_usd_equalance = $('[name=temp_item] option:selected').attr('data-item-currency-equalance');
	tp = $('[name=temp_tp]').val();
	qty = $('[name=temp_qty]').val();

	tp = refine_number(tp);
	// convert avg cost according to sale currency
	// if(currency == item_currency)
	// {
	// 	currency_usd_equalance = item_currency_usd_equalance;
	// }
	// tp = amount_conversion(tp, item_currency_usd_equalance, currency_usd_equalance);
	qty = refine_number(qty);
	total_r = qty * tp;

	// populate data
	html_snippet = '<tr class="text-center bookings-row">';
        html_snippet += '<td class="bookings-self">';
            html_snippet += '<span>'+item_name+'</span>';
            html_snippet += '<input type="hidden" name="item[]" value="'+item+'">';
            html_snippet += '<input type="hidden" name="pdate[]" value="'+pdate+'">';
            html_snippet += '<input type="hidden" name="memo[]" value="'+memo+'">';
            html_snippet += '<input type="hidden" name="currency[]" value="'+currency+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="bookings-qty">';
            html_snippet += '<span>'+round_decimels(qty)+'</span>';
            html_snippet += '<input type="hidden" name="qty[]" value="'+qty+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="bookings-tp">';
            html_snippet += '<span>'+round_decimels(tp)+'</span>';
            html_snippet += '<input type="hidden" name="tp[]" value="'+tp+'">';
        html_snippet += '</td>';
        html_snippet += '<td class="bookings-total">';
            html_snippet += '<span>'+round_decimels(total_r)+'</span>';
            html_snippet += '<input type="hidden" name="total_r[]" value="'+total_r+'">';
        html_snippet += '<td>';
            html_snippet += '<a class="btn btn-danger btn-sm bookings-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a>';
        html_snippet += '</td>';
    html_snippet += '</tr>';


	$('#bookings-table-body').append(html_snippet);

	$('.fixed-fields-row').addClass('pointer-none');
	$('[name=temp_item]').prop('selectedIndex',0);
	$('[name=temp_item]').trigger('chosen:updated');
	$('[name=temp_qty]').val('');
	$('[name=temp_tp]').val('');

	handle_bookings_totals_calculation();
});


function handle_bookings_totals_calculation()
{
	amount_total = 0;

	if($('#bookings-table-body .bookings-row').length > 0)
	{
		$('#bookings-table-body .bookings-row').each(function(e)
		{
			// --------------------------------
			amount = $(this).find('.bookings-total').find('input').val();
			amount = refine_number(amount);

			amount_total += amount;
			// --------------------------------
		});
	}

	$('.bookings-totals-col .bookings-total-amount-row span').text(round_decimels(amount_total));
	$('.bookings-totals-col .bookings-total-amount-row input').val(amount_total);
}

$(document).on('click','.bookings-del-trigger',function(e)
{
	e.preventDefault();
	$(this).closest('.bookings-row').remove();
	handle_bookings_totals_calculation();
});


$(document).on('change','#temp-bookings-form [name=temp_item], #temp-bookings-form [name=temp_currency]',function(e)
{
	item_last_tp = $('#temp-bookings-form [name=temp_item]').find('option:selected').attr('data-tp');
	item_last_tp = refine_number(item_last_tp);
	currency_usd_equalance = $('[name=temp_currency] option:selected').attr('data-usd-equalance');
	currency = $('[name=temp_currency] option:selected').val();
	item_currency = $('[name=temp_item] option:selected').attr('data-item-currency');
	item_currency_usd_equalance = $('[name=temp_item] option:selected').attr('data-item-currency-equalance');
	
	if(currency == item_currency)
	{
		currency_usd_equalance = item_currency_usd_equalance;
	}
	item_last_tp = amount_conversion(item_last_tp, item_currency_usd_equalance, currency_usd_equalance);
	$('#temp-bookings-form [name=temp_tp]').val(round_decimels_3(item_last_tp));
});



// BOOKINGS SCRIPT=======================================================================

// ORDERS SCRIPT=======================================================================

$(document).on('click','#orders-check-all',function()
{
	$('input:checkbox').not(this).prop('checked', this.checked);
});

$(document).on('click','.order-status-trigger-btn',function(e)
{
	pointer_obj = $(this);
	status = $(this).attr('data-type');
	msg = $(this).attr('data-msg');
	url = $(this).attr('data-url');

	check_val = [];
	$("input:checkbox[name=approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});

	if(check_val == null || check_val == '')
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select some bookings.', 'No Selection');
		return false;
	}

	swal(
	{
	    title: 'Are you sure?',
	    text: msg,
	    html: true,
	    type: false,
	    showCancelButton: true,
	    cancelButtonText: 'No',
	    confirmButtonColor: "#1ab394",
	    confirmButtonText: 'Yes',
	    closeOnConfirm: true
	},
	function()
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			type: 'POST',
			url: url,
			data: {status:status,uids:check_val},
			success: function(response)
			{
				response = JSON.parse(response);
				if(response.status == 'success')
				{
					toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
					toastr.success('Orders status changed successfully.', 'Status Changed');
					$("input:checkbox[name=approval_checkbox]:checked").each(function(){
					    $(this).closest('tr').remove();
					});
					$('.ibox-content').removeClass('sk-loading');
				}
				else
				{
					toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
					toastr.error('No row selected.', 'Please select row');
					$('.ibox-content').removeClass('sk-loading');
				}
			}
		});
	});

});


$(document).on('keyup','.bookings-qty-process',function(e){ handle_order_process_totals($(this)); });
$(document).on('input','.bookings-qty-process',function(e){ handle_order_process_totals($(this)); });

function handle_order_process_totals(pointer_obj)
{
	pointer_parent = pointer_obj.closest('.bookings-row');
	tp = pointer_parent.find('.bookings-tp').find('input').val();
	qty = pointer_parent.find('.bookings-qty-process').find('input').val();
	tp = refine_number(tp);
	qty = refine_number(qty);
	total = tp * qty;
	
	pointer_parent.find('.bookings-total-process').find('span').text(round_decimels(total));
	pointer_parent.find('.bookings-total-process').find('input').val(total);

	calculate_order_process_total();
}

function calculate_order_process_total()
{
	total_amounts = 0;

	if($('#bookings-table-body .bookings-row').length > 0)
	{
		$('#bookings-table-body .bookings-row').each(function(e)
		{
			item_total_amount = $(this).find('.bookings-total-process').find('input').val();
			item_total_amount = refine_number(item_total_amount);
			total_amounts += item_total_amount;
		});
	}

	$('.bookings-totals-col .bookings-total-amount-row-process span').text(round_decimels(total_amounts));
	$('.bookings-totals-col .bookings-total-amount-row-process input').val(total_amounts);
}



// ORDERS SCRIPT=======================================================================


// items cbm calculation SCRIPT=======================================================================

$(document).on('keyup','#items-form input[name=item_width], #items-form input[name=item_length], #items-form input[name=item_height]', function()
{
	calculate_item_cbm();
});
$(document).on('input','#items-form input[name=item_width], #items-form input[name=item_length], #items-form input[name=item_height]', function()
{
	calculate_item_cbm();
});

function calculate_item_cbm()
{
	item_width = $("#items-form input[name=item_width]").val();
	item_length = $("#items-form input[name=item_length]").val();
	item_height = $("#items-form input[name=item_height]").val();

	item_width = refine_number(item_width);
	item_length = refine_number(item_length);
	item_height = refine_number(item_height);

	cbm = item_width * item_length * item_height;
	$("#items-form input[name=cbm]").val(cbm);
}

// items cbm calculation SCRIPT=======================================================================

// purchase cbm popup SCRIPT=======================================================================
$(document).on('click','.purchase-cbm-popup-trigger',function(e)
{
	e.preventDefault();

	item = $("#temp-purchases-form [name=temp_item] option:selected").val();
	width = $("#temp-purchases-form [name=temp_item] option:selected").attr('data-item-cbm-width');
	height = $("#temp-purchases-form [name=temp_item] option:selected").attr('data-item-cbm-height');
	length = $("#temp-purchases-form [name=temp_item] option:selected").attr('data-item-cbm-length');
	cbm = $("#temp-purchases-form [name=temp_item] option:selected").attr('data-item-cbm');
	weight = $("#temp-purchases-form [name=temp_item] option:selected").attr('data-item-weight');
	
	if($.trim(item).length == 0)
	{
		toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
		toastr.warning('Please select item to proceed.', 'No Selection');
		return false;
	}

	$('#purchases-cbm-weight-form input[name=old_width]').val(width);
	$('#purchases-cbm-weight-form input[name=old_height]').val(height);
	$('#purchases-cbm-weight-form input[name=old_length]').val(length);
	$('#purchases-cbm-weight-form input[name=old_cbm]').val(cbm);
	$('#purchases-cbm-weight-form input[name=old_weight]').val(weight);
	$('#purchases-cbm-weight-form input[name=item]').val(item);

	$("#purchaseCbmPopup").modal('show');
});


$(document).on('keyup','#purchases-cbm-weight-form input[name=width], #purchases-cbm-weight-form input[name=length], #purchases-cbm-weight-form input[name=height]', function()
{
	calculate_purchase_item_cbm();
});
$(document).on('input','#purchases-cbm-weight-form input[name=width], #purchases-cbm-weight-form input[name=length], #purchases-cbm-weight-form input[name=height]', function()
{
	calculate_purchase_item_cbm();
});

function calculate_purchase_item_cbm()
{
	item_width = $("#purchases-cbm-weight-form input[name=width]").val();
	item_length = $("#purchases-cbm-weight-form input[name=length]").val();
	item_height = $("#purchases-cbm-weight-form input[name=height]").val();

	item_width = refine_number(item_width);
	item_length = refine_number(item_length);
	item_height = refine_number(item_height);

	cbm = item_width * item_length * item_height;
	$("#purchases-cbm-weight-form input[name=cbm]").val(cbm);
}
// purchase cbm popup SCRIPT=======================================================================






$(document).on('change','#cn-purchases-form [name=item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	qty = $('[name=qty]').val();

	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }

	$('[name=cost]').val(item_last_cost);
	

	// reset
	$('[name=warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=warehouse]').trigger('chosen:updated');
	// update
	$('[name=warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=warehouse]').trigger('chosen:updated');
	re_populate_cnpunits();
});

function re_populate_cnpunits()
{
	purchase_unit = $('#cn-purchases-form [name=item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#cn-purchases-form [name=item] option:selected').attr('data-sale-unit');
	production_unit = $('#cn-purchases-form [name=item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#cn-purchases-form [name=item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#cn-purchases-form [name=item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#cn-purchases-form [name=item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#cn-purchases-form [name=unit]').html(options_snippet);
	$('#cn-purchases-form [name=unit]').trigger('chosen:updated');
}

$(document).on('keyup','#cn-purchases-form [name=qty], #cn-purchases-form [name=cost]', function()
{
	calulate_cn_purchase_total();
});

function calulate_cn_purchase_total()
{
	qty = $('#cn-purchases-form [name=qty]').val();
	cost = $('#cn-purchases-form [name=cost]').val();
	qty = refine_number(qty);
	cost = refine_number(cost);
	total = qty * cost;
	$("#cn-purchases-form [name=total]").val(total);
}



$(document).on('change','#process-form [name=item]',function(e)
{
	warehouse = $(this).find('option:selected').attr('data-warehouse');
	item = $(this).find('option:selected').val();
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	qty = $('[name=qty]').val();

	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }	

	// reset
	$('[name=warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=warehouse]').trigger('chosen:updated');
	// update
	$('[name=warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=warehouse]').val(warehouse).trigger('chosen:updated');

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#process-form [name=batch]').html(response);
			$('#process-form [name=batch]').trigger('chosen:updated');
		}
	});

	re_populate_pripunits();
});

function re_populate_pripunits()
{
	purchase_unit = $('#process-form [name=item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#process-form [name=item] option:selected').attr('data-sale-unit');
	production_unit = $('#process-form [name=item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#process-form [name=item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#process-form [name=item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#process-form [name=item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#process-form [name=unit]').html(options_snippet);
	$('#process-form [name=unit]').trigger('chosen:updated');
}


$(document).on('change','#process-form [name=carton_item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	qty = $('[name=qty]').val();

	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }	

	// reset
	$('[name=carton_warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=carton_warehouse]').trigger('chosen:updated');
	// update
	$('[name=carton_warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=carton_warehouse]').trigger('chosen:updated');
	re_populate_prcpunits();
});

function re_populate_prcpunits()
{
	purchase_unit = $('#process-form [name=carton_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#process-form [name=carton_item] option:selected').attr('data-sale-unit');
	production_unit = $('#process-form [name=carton_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#process-form [name=carton_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#process-form [name=carton_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#process-form [name=carton_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#process-form [name=carton_unit]').html(options_snippet);
	$('#process-form [name=carton_unit]').trigger('chosen:updated');
}

$(document).on('change','#process-form [name=chigit_item]',function(e)
{
	item_type = $(this).find('option:selected').attr('data-opt-type');
	item_last_cost = $(this).find('option:selected').attr('data-last-cost');
	qty = $('[name=qty]').val();

	qty = refine_number(qty);
	if(qty <= 0){ qty = 1; }	

	// reset
	$('[name=chigit_warehouse] [data-opt-type=default]').prop('selected',true);
	$('[name=chigit_warehouse]').trigger('chosen:updated');
	// update
	$('[name=chigit_warehouse] option').each(function(e)
	{
		option_type = $(this).attr('data-opt-type');
		if(option_type != 'default')
		{
			if(option_type == item_type)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=chigit_warehouse]').trigger('chosen:updated');
	re_populate_prchgpunits();
});

function re_populate_prchgpunits()
{
	purchase_unit = $('#process-form [name=chigit_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#process-form [name=chigit_item] option:selected').attr('data-sale-unit');
	production_unit = $('#process-form [name=chigit_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#process-form [name=chigit_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#process-form [name=chigit_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#process-form [name=chigit_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#process-form [name=chigit_unit]').html(options_snippet);
	$('#process-form [name=chigit_unit]').trigger('chosen:updated');
}

// branch to branch transfer script

$(document).on('change','#b-to-b-transfer-items-form [name=temp_item]',function(e)
{
	item = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').val();
	warehouse = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-warehouse');

	purchase_unit = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-sale-unit');
	production_unit = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#b-to-b-transfer-items-form [name=temp_batch]').html(response);
			$('#b-to-b-transfer-items-form [name=temp_batch]').trigger('chosen:updated');
		}
	});

	$('#b-to-b-transfer-items-form [name=temp_unit]').html(options_snippet);
	$('#b-to-b-transfer-items-form [name=temp_unit]').trigger('chosen:updated');
});

$(document).on('change','#b-to-b-transfer-items-form [name=temp_to_branch]',function()
{
	warehouse_branch = $('#b-to-b-transfer-items-form [name=temp_to_branch] option:selected').val();
	$('[name=temp_to_warehouse] option').each(function(e)
	{
		option_branch = $(this).attr('data-opt-branch');
		if(option_branch != 'default')
		{
			if(option_branch == warehouse_branch)
			{
				$(this).removeAttr('selected').removeClass('display-none');
			}
			else
			{
				$(this).removeAttr('selected').addClass('display-none');
			}
		}
	});
	$('[name=temp_to_warehouse]').trigger('chosen:updated');

});


$(document).on('submit','#b-to-b-transfer-items-form',function(e)
{
	e.preventDefault();
	t_date = $('#b-to-b-transfer-items-form [name=temp_t_date]').val();
	item = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').val();
	item_name = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-name');
	cost = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-cost');
	profit = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-profit');
	warehouse = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-warehouse');
	warehouse_name = $('#b-to-b-transfer-items-form [name=temp_item] option:selected').attr('data-warehouse-name');
	batch = $('#b-to-b-transfer-items-form [name=temp_batch] option:selected').val();
	unit = $('#b-to-b-transfer-items-form [name=temp_unit] option:selected').val();
	unit_name = $('#b-to-b-transfer-items-form [name=temp_unit] option:selected').text();
	to_branch = $('#b-to-b-transfer-items-form [name=temp_to_branch] option:selected').val();
	to_branch_name = $('#b-to-b-transfer-items-form [name=temp_to_branch] option:selected').text();
	to_warehouse = $('#b-to-b-transfer-items-form [name=temp_to_warehouse] option:selected').val();
	to_warehouse_name = $('#b-to-b-transfer-items-form [name=temp_to_warehouse] option:selected').text();
	qty = $('#b-to-b-transfer-items-form [name=temp_qty]').val();
	details = $('#b-to-b-transfer-items-form [name=temp_details]').val();

	qty = refine_number(qty);
	cost = refine_number(cost);
	profit = refine_number(profit);



	html_snippet = '<tr class="text-center b-to-b-transfer-item-row">';

	    html_snippet += '<td>';
	        html_snippet += t_date;
	        html_snippet += '<input type="hidden" name="t_date[]" value="'+t_date+'">';
	        html_snippet += '<input type="hidden" name="cost[]" value="'+cost+'">';
	        html_snippet += '<input type="hidden" name="profit[]" value="'+profit+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += item_name;
	        html_snippet += '<input type="hidden" name="item[]" value="'+item+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += warehouse_name;
	        html_snippet += '<input type="hidden" name="warehouse[]" value="'+warehouse+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += unit_name;
	        html_snippet += '<input type="hidden" name="unit[]" value="'+unit+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += batch;
	        html_snippet += '<input type="hidden" name="batch[]" value="'+batch+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += '<input type="text" style="width:100px;" name="qty[]" value="'+qty+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += to_branch_name;
	        html_snippet += '<input type="hidden" name="to_branch[]" value="'+to_branch+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += to_warehouse_name;
	        html_snippet += '<input type="hidden" name="to_warehouse[]" value="'+to_warehouse+'">';
	    html_snippet += '</td>';

	    html_snippet += '<td>';
	        html_snippet += details;
	        html_snippet += '<input type="hidden" name="details[]" value="'+details+'">';
	    html_snippet += '</td>';
	    
	    html_snippet += '<td style="width: 40px;"><a class="btn btn-danger btn-sm b-to-b-transfer-item-del-trigger" href="javascript:void(0);"><i class="fa fa-trash"></i></a></td>';
	html_snippet += '</tr>';


	$('#b-to-b-transfer-items-table-body').append(html_snippet);
	$('#b-to-b-transfer-items-form').trigger("reset");

	// reset form inputs and select
	unit_snippet = '<option disabled="" selected="">-- Unit --</option>';
	$('[name=temp_unit]').html(unit_snippet);

	batch_snippet = '<option disabled="" selected="">-- Batch --</option>';
	$('[name=temp_batch]').html(batch_snippet);

	$('[name=temp_item]').prop('selectedIndex',0);
	$(".chosen-select").trigger('chosen:updated');

	$('[name=temp_to_branch]').prop('selectedIndex',0);
	$(".chosen-select").trigger('chosen:updated');

	$('[name=temp_to_warehouse]').prop('selectedIndex',0);
	$(".chosen-select").trigger('chosen:updated');

	$('[name=temp_to_warehouse] option').addClass('display-none');
	$('[name=temp_to_warehouse]').trigger('chosen:updated');
	// reset form inputs and select
});

$(document).on('click','.b-to-b-transfer-item-del-trigger',function(e)
{
	e.preventDefault();	
	$(this).closest('.b-to-b-transfer-item-row').remove();
});







$(document).on('change','#b-to-b-transfer-update-form [name=item]',function(e)
{
	item = $('#b-to-b-transfer-update-form [name=item] option:selected').val();
	warehouse = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-warehouse');
	cost = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-cost');
	profit = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-profit');

	purchase_unit = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-sale-unit');
	production_unit = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#b-to-b-transfer-update-form [name=item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			$('#b-to-b-transfer-update-form [name=batch]').html(response);
			$('#b-to-b-transfer-update-form [name=batch]').trigger('chosen:updated');
		}
	});

	$('#b-to-b-transfer-update-form [name=unit]').html(options_snippet);
	$('#b-to-b-transfer-update-form [name=unit]').trigger('chosen:updated');

	$('#b-to-b-transfer-update-form [name=warehouse]').val(warehouse);
	$('#b-to-b-transfer-update-form [name=cost]').val(cost);
	$('#b-to-b-transfer-update-form [name=profit]').val(profit);
});

$(document).on('change','#b-to-b-transfer-update-form [name=to_branch]',function()
{
	warehouse_branch = $('#b-to-b-transfer-update-form [name=to_branch] option:selected').val();
	$('[name=to_warehouse] option').each(function(e)
	{
		option_branch = $(this).attr('data-opt-branch');
		if(option_branch == warehouse_branch)
		{
			$(this).removeAttr('selected').removeClass('display-none');
		}
		else
		{
			$(this).removeAttr('selected').addClass('display-none');
		}
	});
	$('[name=to_warehouse]').trigger('chosen:updated');

});
// branch to branch transfer script


$(window).on('beforeunload', function()
{
	if($("#confirm_msg_div").hasClass('confirm-leave'))
	{
		return 'Are you sure you want to leave?';
	}
});


// $(document).on('click','.items-info-popup-btn',function()
// {
// 	name = $(this).attr('data-name');
// 	details = $(this).attr('data-details');

// 	$('.item-details-popup-item-name-span').text(name);
// 	$('.item-details-popup-item-name-para').text(details);

// 	$('#itemDetailsModal').modal('show');
// });


$(document).on('keyup','#metu-purchases-form input[name=value], #metu-purchases-form input[name=percentage]',function()
{
	handle_metu_purchases_totals();
});
// metu purchases scrpt
function handle_metu_purchases_totals()
{
	mrate = 1;
	mvalue = refine_number($('#metu-purchases-form input[name=value]').val());
	mpercentage = refine_number($('#metu-purchases-form input[name=percentage]').val());

	percentage_amount = (mrate * mpercentage) / 100;
	if(mpercentage == 0){percentage_amount = 0;}
	mcost = mrate + percentage_amount;
	total = mvalue * mcost;

	$('#metu-purchases-form input[name=cost]').val(mcost);
	$('#metu-purchases-form input[name=percentage_amount]').val(percentage_amount);
	$('#metu-purchases-form input[name=total]').val(total);
}

$(document).on('keyup','#metu-sales-form input[name=value], #metu-sales-form input[name=percentage]',function()
{
	handle_metu_sales_totals();
});
// metu sales scrpt
function handle_metu_sales_totals()
{
	mrate = 1;
	mvalue = refine_number($('#metu-sales-form input[name=value]').val());
	mpercentage = refine_number($('#metu-sales-form input[name=percentage]').val());

	percentage_amount = (mrate * mpercentage) / 100;
	if(mpercentage == 0){percentage_amount = 0;}
	mcost = mrate + percentage_amount;
	total = mvalue * mcost;

	$('#metu-sales-form input[name=cost]').val(mcost);
	$('#metu-sales-form input[name=percentage_amount]').val(percentage_amount);
	$('#metu-sales-form input[name=total]').val(total);
}
// metu purchases scrpt

$(document).on('ifChecked','#items-settings-form [type=radio]', function()
{
	pointer_obj = $(this);
	input_name = $(this).attr('name');
	input_val = $(this).val();

	$('body').addClass('inprocess');
	ibox_obj = pointer_obj.closest('.ibox-content');
	ibox_obj.addClass('sk-loading');

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/items-settings/update-system-modules',
		data: {input_name:input_name,input_val:input_val},
		success: function(response)
		{
			response = JSON.parse(response);
			$('body').removeClass('inprocess');
			ibox_obj.removeClass('sk-loading');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
			toastr.success(response.message_body, response.message_head);
		},
		error: function(data)
		{
			response = JSON.parse(data);
			$('body').removeClass('inprocess');
			ibox_obj.removeClass('sk-loading');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
			toastr.error(response.message_body, response.message_head);
		}
	});
});

$(document).on('change','#stock-general-ledger-report-search-form [name=item]',function()
{
	re_populate_general_stock_ledger_report();
});

function re_populate_general_stock_ledger_report()
{
	purchase_unit = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-purchase-unit');
	sale_unit = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-sale-unit');
	production_unit = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = $('#stock-general-ledger-report-search-form [name=item] option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != sale_unit && production_unit != purchase_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}

	$('#stock-general-ledger-report-search-form [name=unit]').html(options_snippet);
	$('#stock-general-ledger-report-search-form [name=unit]').trigger('chosen:updated');
}

$(document).on('change','.set-add-to-list-item',function(e)
{
	pointer_parent = $(this).closest('.sets-add-to-list-row');
	item = pointer_parent.find('.set-add-to-list-item option:selected').val();
	warehouse = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-warehouse');

	purchase_unit = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-purchase-unit');
	sale_unit = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-sale-unit');
	production_unit = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-production-unit');
	purchase_unit_usd_equalance = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-purchase-unit-usd-equalance');
	sale_unit_usd_equalance = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-sale-unit-usd-equalance');
	production_unit_usd_equalance = pointer_parent.find('.set-add-to-list-item option:selected').attr('data-production-unit-usd-equalance');

	options_snippet = '<option disabled="">-- Unit --</option>';
	options_snippet += '<option value="purchase" selected="selected">'+purchase_unit+'</option>';
	if(sale_unit != purchase_unit)
	{
		options_snippet += '<option value="sale">'+sale_unit+'</option>';
	}

	if(production_unit != purchase_unit && production_unit != sale_unit)
	{
		options_snippet += '<option value="production">'+production_unit+'</option>';
	}


	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sales/get-items-batch',
		data: {item:item,warehouse:warehouse},
		success: function(response)
		{
			console.log(response);
			pointer_parent.find('.set-add-to-list-batch').html(response);
			pointer_parent.find('.set-add-to-list-batch').trigger('chosen:updated');
		}
	});

	pointer_parent.find('.set-add-to-list-unit').html(options_snippet);
	pointer_parent.find('.set-add-to-list-unit').trigger('chosen:updated');

	pointer_parent.find('.set-add-to-list-warehouse').val(warehouse);
});

// sets script
$(document).on('click','.set-add-to-list-trigger',function()
{
	if(custom_validation('sets-form','add-to-list-validate') == false){ console.warn('validation Failed!'); return false; }
	pointer_parent = $(this).closest('.sets-add-to-list-row');
	item = pointer_parent.find('.set-add-to-list-item option:selected').val();
	warehouse = pointer_parent.find('.set-add-to-list-warehouse').val();
	batch = pointer_parent.find('.set-add-to-list-batch').val();
	unit = pointer_parent.find('.set-add-to-list-unit').val();
	qty = pointer_parent.find('.set-add-to-list-qty').val();

	$('.ibox-content').addClass('sk-loading');
	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/sets/get-items-appended-data',
		data: {item:item,warehouse:warehouse,batch:batch,unit:unit,qty:qty},
		success: function(response)
		{
			response = JSON.parse(response);
			console.log(response);
			$('.sets-appended-data-row').append(response.html);
			// $('#branch-transfer-out-form [name=batch]').html(response);
			$('.set-add-to-list-item').chosen({ dropdownParent: $('#sets-form') });
			$('.set-add-to-list-batch').chosen({ dropdownParent: $('#sets-form') });
			$('.set-add-to-list-unit').chosen({ dropdownParent: $('#sets-form') });
			pointer_parent.find('.set-add-to-list-item').val('').trigger('chosen:updated');
			pointer_parent.find('.set-add-to-list-batch').val('').trigger('chosen:updated');
			pointer_parent.find('.set-add-to-list-unit').val('').trigger('chosen:updated');
			pointer_parent.find('.set-add-to-list-qty').val('');
			$('.ibox-content').removeClass('sk-loading');
		}
	});
});

$(document).on('click','.set-del-to-list-trigger',function()
{
	$(this).closest('.sets-add-to-list-row').remove();
});
// sets script
function is_empty(value)
{
	return ($.trim(value).length == 0) ? true : false;
}

function custom_validation(form_id,class_to_check)
{
	validation = true;
	error_message = '<label class="error">Required</label>';
	
	if($('#'+form_id+' .'+class_to_check+'').length > 0)
	{
		$('#'+form_id+' .'+class_to_check+'').each(function(e)
		{
			if($(this).is('input,select,textarea'))
			{
				if(is_empty($(this).val()))
				{
					validation = false;
					if($(this).parent().find('label.error').length == 0)
					{
						$(this).parent().append(error_message);
					}
				}
				else
				{
					$(this).parent().find('label.error').remove();
				}
			}
		});
	}

	return validation;
}

$(document).on('input change','input.cv-required, select.cv-required, textarea.cv-required, input.add-to-list-validate, select.add-to-list-validate, textarea.add-to-list-validate',function(e)
{
	error_message = '<label class="error">This field is required</label>';
	if(is_empty($(this).val()))
	{
		if($(this).parent().find('label.error').length == 0)
		{
			$(this).parent().append(error_message);
		}
	}
	else
	{
		$(this).parent().find('label.error').remove();
	}
});


$(document).on('change','#tokens-form select[name=client], #tokens-form select[name=item]',function()
{
	get_client_sold_token_value();
});

$(document).on('keyup','#tokens-form input[name=purchase_qty]',function()
{
	handle_tokens_form_totals();
});

function get_client_sold_token_value()
{
	client = $('#tokens-form select[name=client] option:selected').val();
	item = $('#tokens-form select[name=item] option:selected').val();
	rate = refine_number($('#tokens-form select[name=item] option:selected').attr('data-token-rate'));

	if(is_empty(client) || is_empty(item))
	{
		$('#tokens-form input[name=sold_qty]').val('');
		$('#tokens-form input[name=sold_amount]').val('');
		handle_tokens_form_totals();
	}
	else
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			type: 'POST',
			url: app_url()+'/tokens/get-client-sold-data',
			data: {client:client,item:item},
			success: function(response)
			{
				response = JSON.parse(response);
				$('#tokens-form input[name=sold_qty]').val(response.available_qty);
				sold_value = response.available_qty * rate;
				$('#tokens-form input[name=sold_amount]').val(sold_value);
				$('.ibox-content').removeClass('sk-loading');
				handle_tokens_form_totals();
			}
		});
	}
}

function handle_tokens_form_totals()
{
	client = $('#tokens-form select[name=client] option:selected').val();
	item = $('#tokens-form select[name=item] option:selected').val();
	rate = refine_number($('#tokens-form select[name=item] option:selected').attr('data-token-rate'));
	qty = refine_number($('#tokens-form input[name=purchase_qty]').val());
	purchase_amount = qty * rate;
	$('#tokens-form input[name=purchase_amount]').val(purchase_amount);
}


$(document).on('change','.shareholder-credit-select', function(){

	percentage_amount = refine_number($('.shareholder-credit-select option:selected').attr('data-percentage'));

	$('.find-percentage').val(percentage_amount);

});

$(document).on('change','.shareholder-capitals-select', function(){

	percentage_amount = refine_number($('.shareholder-capitals-select option:selected').attr('data-percentage'));

	$('.find-percentage').val(percentage_amount);

});

$(document).on('keyup','#item-stock-out-form input[name=out_quantity]',function()
{
	out_quantity = refine_number($('#item-stock-out-form input[name=out_quantity]').val());
	available_quantity = refine_number($('#item-stock-out-form select[name=item] option:selected').attr('data-available'));

	if(out_quantity > available_quantity)
	{
		main_title = $('#langs-span').attr('data-item-stock-out-quantity-main-title');
		sub_title = $('#langs-span').attr('data-item-stock-out-quantity-sub-title');
		confirm_btn_text = $('#langs-span').attr('data-item-stock-out-quantity-confirm-btn-text');

		swal(
		{
		    title: main_title,
		    text: sub_title,
		    html: true,
		    type: false,
		    showCancelButton: false,
		    confirmButtonColor: "#1ab394",
		    confirmButtonText: confirm_btn_text,
		    closeOnConfirm: true
		},
		function()
		{
			$('#item-stock-out-form input[name=out_quantity]').val(available_quantity);
		});
	}
});


// stock items
$(document).on('change','#item-stock-in-form select[name=item]',function()
{
	handle_item_stock_in_currency_unit();
});

function handle_item_stock_in_currency_unit()
{
	currency = $('#item-stock-in-form select[name=item] option:selected').attr('data-currency');
	unit = $('#item-stock-in-form select[name=item] option:selected').attr('data-unit');

	$('#item-stock-in-form select[name=currency]').val(currency).trigger('chosen:updated');
	$('#item-stock-in-form input[name=unit]').val(unit);
}
// stock items




// prodcution relation module
$(document).on('click','.production-relation-produced-items-trigger',function()
{
	if(custom_validation_produced('production-relation-form','cv-produced-required') == false){ console.warn('validation Failed!'); return false; }
	item = $('.production-relation-produced-items-dp option:selected').val();
	item_name = $('.production-relation-produced-items-dp option:selected').text();
	qty = refine_number($('.production-relation-produced-qty-ip').val());
	cost = refine_number($('.production-relation-produced-cost-percentage-ip').val());

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/production-relation/produced-items-data',
		data: {item:item,item_name:item_name,qty:qty,cost:cost},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.production-relation-produced-items-row').append(response.html);
			$('.production-relation-produced-items-dp').val('').trigger('chosen:updated');
			$('.production-relation-produced-qty-ip').val(1);
			$('.production-relation-produced-cost-percentage-ip').val(1);
			$('.ibox-content').removeClass('sk-loading');
		}
	});
});

$(document).on('click','.produced-items-del-btn',function()
{
	$(this).closest('.produced-appended-data-rows').remove();
});

function custom_validation_produced(form_id,class_to_check)
{
	validation = true;
	error_message = '<label class="error">Required</label>';
	
	if($('#'+form_id+' .'+class_to_check+'').length > 0)
	{
		$('#'+form_id+' .'+class_to_check+'').each(function(e)
		{
			if($(this).is('input,select,textarea'))
			{
				if(is_empty($(this).val()))
				{
					validation = false;
					if($(this).parent().find('label.error').length == 0)
					{
						$(this).parent().append(error_message);
					}
				}
				else
				{
					$(this).parent().find('label.error').remove();
				}
			}
		});
	}

	return validation;
}

$(document).on('input change','input.cv-produced-required, select.cv-produced-required, textarea.cv-produced-required, input.add-to-list-validate, select.add-to-list-validate, textarea.add-to-list-validate',function(e)
{
	error_message = '<label class="error">This field is required</label>';
	if(is_empty($(this).val()))
	{
		if($(this).parent().find('label.error').length == 0)
		{
			$(this).parent().append(error_message);
		}
	}
	else
	{
		$(this).parent().find('label.error').remove();
	}
});




$(document).on('click','.production-relation-raw-items-trigger',function()
{
	if(custom_validation_raw('production-relation-form','cv-raw-required') == false){ console.warn('validation Failed!'); return false; }
	item = $('.production-relation-raw-items-dp option:selected').val();
	item_name = $('.production-relation-raw-items-dp option:selected').text();
	qty = refine_number($('.production-relation-raw-qty-ip').val());

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/production-relation/raw-items-data',
		data: {item:item,item_name:item_name,qty:qty},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.production-relation-raw-items-row').append(response.html);
			$('.production-relation-raw-items-dp').val('').trigger('chosen:updated');
			$('.production-relation-raw-qty-ip').val(1);
			$('.ibox-content').removeClass('sk-loading');
		}
	});
});

$(document).on('click','.raw-items-del-btn',function()
{
	$(this).closest('.raw-appended-data-rows').remove();
});

function custom_validation_raw(form_id,class_to_check)
{
	validation = true;
	error_message = '<label class="error">Required</label>';
	
	if($('#'+form_id+' .'+class_to_check+'').length > 0)
	{
		$('#'+form_id+' .'+class_to_check+'').each(function(e)
		{
			if($(this).is('input,select,textarea'))
			{
				if(is_empty($(this).val()))
				{
					validation = false;
					if($(this).parent().find('label.error').length == 0)
					{
						$(this).parent().append(error_message);
					}
				}
				else
				{
					$(this).parent().find('label.error').remove();
				}
			}
		});
	}

	return validation;
}

$(document).on('input change','input.cv-raw-required, select.cv-raw-required, textarea.cv-raw-required, input.add-to-list-validate, select.add-to-list-validate, textarea.add-to-list-validate',function(e)
{
	error_message = '<label class="error">This field is required</label>';
	if(is_empty($(this).val()))
	{
		if($(this).parent().find('label.error').length == 0)
		{
			$(this).parent().append(error_message);
		}
	}
	else
	{
		$(this).parent().find('label.error').remove();
	}
});
// prodcution relation module

// production moduel script
$(document).on('change','.production-item, .production-currency',function()
{
	get_production_item_relational_data();
});

function get_production_item_relational_data()
{
	item = $(".production-item option:selected").val();
	currency = $(".production-currency option:selected").val();
	if(is_empty(item) || is_empty(currency))
	{
		$('.production-relational-items-data').html('');
	}
	else
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			type: 'POST',
			url: app_url()+'/production/get-relational-items',
			data: {item:item,currency:currency},
			success: function(response)
			{
				response = JSON.parse(response);
				$('.production-relational-items-data').html(response.html);
				$('.chosen-select').chosen({
				    dropdownParent: $('.production-relational-items-data')
				});
				$('.chosen-select').trigger('chosen:updated');
				handle_production_totals_cost();
				$('.ibox-content').removeClass('sk-loading');
			}
		});
	}

}

$(document).on('keyup','.production-qty, .production-total-expenses',function()
{
	handle_production_totals_cost();
});

function handle_production_totals_cost()
{
	qty = refine_number($('.production-qty').val());

	total_produced_qty = qty;
	$('.produced-relational-items-row').each(function(e)
	{
		produced_relational_qty = refine_number($(this).find('.produced-rel-qty-input').val());
		produced_new_qty = produced_relational_qty * qty;
		total_produced_qty += produced_new_qty;
		$(this).find('.produced-qty-input').val(produced_new_qty);
	});

	total_raw_cost = 0;
	$('.raw-relational-items-row').each(function(e)
	{
		raw_relational_qty = refine_number($(this).find('.raw-rel-qty-input').val());
		raw_cost = refine_number($(this).find('.raw-item-cost').val());
		raw_new_qty = raw_relational_qty * qty;
		total_cost = raw_new_qty * raw_cost;
		$(this).find('.raw-qty-input').val(raw_new_qty);
		total_raw_cost += total_cost;
	});

	total_expenses = refine_number($('.production-total-expenses').val());
	total_real_cost = total_expenses + total_raw_cost;
	per_item_produced_cost = total_real_cost / total_produced_qty;

	$('.production-total-raw-cost').val(total_raw_cost);
	$('.production-total-real-cost').val(total_real_cost);
	$('.production-total-produced-qty').val(total_produced_qty);
	$('.production-per-item-produced-cost').val(per_item_produced_cost);

	total_produced_row_wise_cost = 0;
	$('.produced-relational-items-row').each(function(e)
	{
		produced_relational_cost_percentage = refine_number($(this).find('.produced-item-cost-percentage').val());
		if(produced_relational_cost_percentage == 0){item_row_cost = 0;}else{ item_row_cost = (per_item_produced_cost * produced_relational_cost_percentage) / 100; }
		
		total_produced_row_wise_cost += item_row_cost;
		$(this).find('.produced-item-cost').val(item_row_cost);
	});

	production_item_cost = per_item_produced_cost - total_produced_row_wise_cost;
	$('.production-item-cost').val(production_item_cost);
}

// prodcution relation module
$(document).on('click','.production-raw-relation-produced-items-trigger',function()
{
	if(custom_validation_produced('production-raw-relation-form','cv-produced-required') == false){ console.warn('validation Failed!'); return false; }
	item = $('.production-raw-relation-produced-items-dp option:selected').val();
	item_name = $('.production-raw-relation-produced-items-dp option:selected').text();
	qty = refine_number($('.production-raw-relation-produced-qty-ip').val());
	cost = refine_number($('.production-raw-relation-produced-cost-percentage-ip').val());

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/production-raw-relation/produced-items-data',
		data: {item:item,item_name:item_name,qty:qty,cost:cost},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.production-raw-relation-produced-items-row').append(response.html);
			$('.production-raw-relation-produced-items-dp').val('').trigger('chosen:updated');
			$('.production-raw-relation-produced-qty-ip').val(1);
			$('.production-raw-relation-produced-cost-percentage-ip').val(1);
			$('.ibox-content').removeClass('sk-loading');
		}
	});
});

$(document).on('click','.produced-items-del-btn',function()
{
	$(this).closest('.produced-appended-data-rows').remove();
});

function custom_validation_produced(form_id,class_to_check)
{
	validation = true;
	error_message = '<label class="error">Required</label>';
	
	if($('#'+form_id+' .'+class_to_check+'').length > 0)
	{
		$('#'+form_id+' .'+class_to_check+'').each(function(e)
		{
			if($(this).is('input,select,textarea'))
			{
				if(is_empty($(this).val()))
				{
					validation = false;
					if($(this).parent().find('label.error').length == 0)
					{
						$(this).parent().append(error_message);
					}
				}
				else
				{
					$(this).parent().find('label.error').remove();
				}
			}
		});
	}

	return validation;
}

$(document).on('input change','input.cv-produced-required, select.cv-produced-required, textarea.cv-produced-required, input.add-to-list-validate, select.add-to-list-validate, textarea.add-to-list-validate',function(e)
{
	error_message = '<label class="error">This field is required</label>';
	if(is_empty($(this).val()))
	{
		if($(this).parent().find('label.error').length == 0)
		{
			$(this).parent().append(error_message);
		}
	}
	else
	{
		$(this).parent().find('label.error').remove();
	}
});




$(document).on('click','.production-raw-relation-raw-items-trigger',function()
{
	if(custom_validation_raw('production-raw-relation-form','cv-raw-required') == false){ console.warn('validation Failed!'); return false; }
	item = $('.production-raw-relation-raw-items-dp option:selected').val();
	item_name = $('.production-raw-relation-raw-items-dp option:selected').text();
	qty = refine_number($('.production-raw-relation-raw-qty-ip').val());

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/production-raw-relation/raw-items-data',
		data: {item:item,item_name:item_name,qty:qty},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.production-raw-relation-raw-items-row').append(response.html);
			$('.production-raw-relation-raw-items-dp').val('').trigger('chosen:updated');
			$('.production-raw-relation-raw-qty-ip').val(1);
			$('.ibox-content').removeClass('sk-loading');
		}
	});
});

$(document).on('click','.raw-items-del-btn',function()
{
	$(this).closest('.raw-appended-data-rows').remove();
});
// prodcution relation module



// production moduel script
$(document).on('change','.raw-production-item, .raw-production-currency',function()
{
	get_production_raw_item_relational_data();
});

function get_production_raw_item_relational_data()
{
	item = $(".raw-production-item option:selected").val();
	currency = $(".raw-production-currency option:selected").val();
	if(is_empty(item) || is_empty(currency))
	{
		$('.production-raw-relational-items-data').html('');
	}
	else
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			type: 'POST',
			url: app_url()+'/production-raw/get-relational-items',
			data: {item:item,currency:currency},
			success: function(response)
			{
				response = JSON.parse(response);
				$('.production-raw-relational-items-data').html(response.html);
				$('.chosen-select').chosen({
				    dropdownParent: $('.production-raw-relational-items-data')
				});
				$('.chosen-select').trigger('chosen:updated');
				handle_production_raw_totals_cost();
				$('.ibox-content').removeClass('sk-loading');
			}
		});
	}
}

$(document).on('keyup','.raw-production-qty, .raw-production-total-expenses',function()
{
	handle_production_raw_totals_cost();
});

function handle_production_raw_totals_cost()
{
	qty = refine_number($('.raw-production-qty').val());
	cost = refine_number($('.raw-production-item option:selected').attr('data-cost'));
	item_currency = $('.raw-production-item option:selected').attr('data-currency');
	item_currency_equalance = refine_number($('.raw-production-item option:selected').attr('data-currency-equalance'));
	currency = $(".raw-production-currency option:selected").val();
	currency_equalance = refine_number($(".raw-production-currency option:selected").attr('data-usd-equalance'));

	if(item_currency != currency)
	{
		cost = amount_conversion(cost, item_currency_equalance, currency_equalance);
	}
	$('.raw-production-cost').val(round_numbers_3(cost));

	total_produced_qty = 0;
	$('.produced-raw-relational-items-row').each(function(e)
	{
		produced_relational_qty = refine_number($(this).find('.produced-rel-qty-input').val());
		produced_new_qty = produced_relational_qty * qty;
		total_produced_qty += produced_new_qty;
		$(this).find('.produced-qty-input').val(produced_new_qty);
	});

	total_raw_cost = qty * cost;
	console.log(total_raw_cost);
	$('.raw-raw-relational-items-row').each(function(e)
	{
		raw_relational_qty = refine_number($(this).find('.raw-rel-qty-input').val());
		raw_cost = refine_number($(this).find('.raw-item-cost').val());
		raw_new_qty = raw_relational_qty * qty;
		total_cost = raw_new_qty * raw_cost;
		$(this).find('.raw-qty-input').val(raw_new_qty);
		total_raw_cost += total_cost;
	});

	total_expenses = refine_number($('.raw-production-total-expenses').val());
	total_real_cost = total_expenses + total_raw_cost;
	per_item_produced_cost = total_real_cost / total_produced_qty;

	$('.production-total-raw-cost').val(round_numbers_3(total_raw_cost));
	$('.production-total-real-cost').val(round_numbers_3(total_real_cost));
	$('.production-total-produced-qty').val(round_numbers_3(total_produced_qty));
	$('.production-per-item-produced-cost').val(round_numbers_3(per_item_produced_cost));

	total_produced_row_wise_cost = 0;
	$('.produced-raw-relational-items-row').each(function(e)
	{
		produced_relational_cost_percentage = refine_number($(this).find('.produced-item-cost-percentage').val());
		if(produced_relational_cost_percentage == 0){item_row_cost = 0;}else{ item_row_cost = (per_item_produced_cost * produced_relational_cost_percentage) / 100; }
		
		total_produced_row_wise_cost += item_row_cost;
		$(this).find('.produced-item-cost').val(round_numbers_3(item_row_cost));
	});
}


// new prodcution script
$(document).on('click','.new-production-formula-items-trigger',function()
{
	get_new_production_item_data();
});

function get_new_production_item_data()
{
	item = $(".new-production-formula-item option:selected").val();
	percentage = refine_number($(".new-production-formula-percentage").val());
	
	if(custom_validation_raw('new-production-formula-form','ex-cv-required') == false){ console.warn('validation Failed!'); return false; }

	$.ajax(
	{
		type: 'POST',
		url: app_url()+'/new-production-formula/get-items-data',
		data: {item:item,percentage:percentage},
		success: function(response)
		{
			response = JSON.parse(response);
			$('.new-production-formula-items-row').append(response.html);
			$('.chosen-select').chosen({
			    dropdownParent: $('.new-production-formula-items-row')
			});
			$('.chosen-select').trigger('chosen:updated');
			$('.new-production-formula-item').val('').trigger('chosen:updated');
			$(".new-production-formula-percentage").val(1);
			$('.ibox-content').removeClass('sk-loading');
		}
	});
}

$(document).on('click','.new-production-formula-items-del-btn',function()
{
	$(this).closest('.new-production-appended-data-rows').remove();
});

function custom_validation_production_new_formula(form_id,class_to_check)
{
	validation = true;
	error_message = '<label class="error">Required</label>';
	
	if($('#'+form_id+' .'+class_to_check+'').length > 0)
	{
		$('#'+form_id+' .'+class_to_check+'').each(function(e)
		{
			if($(this).is('input,select,textarea'))
			{
				if(is_empty($(this).val()))
				{
					validation = false;
					if($(this).parent().find('label.error').length == 0)
					{
						$(this).parent().append(error_message);
					}
				}
				else
				{
					$(this).parent().find('label.error').remove();
				}
			}
		});
	}

	return validation;
}

$(document).on('input change','input.ex-cv-required, select.ex-cv-required, textarea.ex-cv-required, input.add-to-list-validate, select.add-to-list-validate, textarea.add-to-list-validate',function(e)
{
	error_message = '<label class="error">This field is required</label>';
	if(is_empty($(this).val()))
	{
		if($(this).parent().find('label.error').length == 0)
		{
			$(this).parent().append(error_message);
		}
	}
	else
	{
		$(this).parent().find('label.error').remove();
	}
});


$(document).on('change','.new-production-currency, .new-production-formula',function()
{
	handle_production_new_items_formula_relation();
});

function handle_production_new_items_formula_relation()
{
	currency = $('.new-production-currency option:selected').val();
	formula = $('.new-production-formula option:selected').val();

	if(is_empty(formula) || is_empty(currency))
	{
		$('.production-raw-relational-items-data').html('');
	}
	else
	{
		$('.ibox-content').addClass('sk-loading');
		$.ajax(
		{
			type: 'POST',
			url: app_url()+'/new-production/get-items-data',
			data: {formula:formula,currency:currency},
			success: function(response)
			{
				response = JSON.parse(response);
				$('.new-production-formula-items-data').html(response.html);
				$('.chosen-select').chosen({
				    dropdownParent: $('.new-production-formula-items-data')
				});
				$('.chosen-select').trigger('chosen:updated');
				handle_new_production_raw_totals_cost();
				$('.ibox-content').removeClass('sk-loading');
			}
		});
	}
}

$(document).on('keyup','.new-production-qty, .new-production-weight, .new-production-used-expenses',function()
{
	handle_new_production_raw_totals_cost();
});

function handle_new_production_raw_totals_cost()
{
	qty = refine_number($('#new-production-form input[name=qty]').val());
	weight = refine_number($('#new-production-form input[name=weight]').val());
	total_weight = qty * weight;
	$('#new-production-form input[name=total_weight]').val(total_weight);

	total_raw_cost = 0;
	$('.new-production-formula-items-row').each(function(e)
	{
		raw_item_cost = refine_number($(this).find('.new-production-raw-item-cost').val());
		raw_item_percentage = refine_number($(this).find('.new-production-raw-item-percentage').val());
		raw_item_qty = (total_weight * raw_item_percentage)/100;
		$(this).find('.new-production-raw-item-qty').val(round_numbers_3(raw_item_qty));
		raw_item_total_cost = raw_item_cost * raw_item_qty;
		total_raw_cost += raw_item_total_cost;
	});

	total_expenses = refine_number($('.new-production-used-expenses').val());
	total_real_cost = total_expenses + total_raw_cost;
	per_item_produced_cost = total_real_cost / qty;

	$('.new-production-total-cost').val(round_numbers_3(total_raw_cost));
	$('.new-production-total-real-cost').val(round_numbers_3(total_real_cost));
	$('.new-production-per-item-produced-cost').val(round_numbers_3(per_item_produced_cost));
}
// new production script


// system approvals
$(document).on('click','#system-approvals-check-all',function()
{
	$('input:checkbox').not(this).prop('checked', this.checked);
});

$(document).on('click','.system-approvals-checkbox,#system-approvals-check-all',function()
{
	check_val = [];
	$("input:checkbox[name=system_approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});
});


$(document).on('click','.system-approval-button',function(e)
{
	e.preventDefault();
	if($('body').hasClass('inprocess')){ return false; }
	status = $(this).attr('data-action');
	approval_status = $(this).attr('data-approval-action');
	module_name = $('.system-approvals-module-select option:selected').val();

	check_val = [];
	$("input:checkbox[name=system_approval_checkbox]:checked").each(function(){
	    check_val.push($(this).val());
	});

	if (check_val.length === 0) {
	    toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
	    toastr.error('No row selected.', 'Please select row');
	    $('.ibox-content').removeClass('sk-loading');
	    return false;
	}

	$('.ibox-content').addClass('sk-loading');
	url = app_url()+'/process-system-approvals';
	
	$('body').addClass('inprocess');
	$.ajax(
	{
		type: 'POST',
		url: url,
		data: {status:status,uids:check_val,approval_status:approval_status, module_name:module_name},
		success: function(response)
		{
			$('body').removeClass('inprocess');
			response = JSON.parse(response);
			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.success(response.message_body, response.message_head);
				$("input:checkbox[name=system_approval_checkbox]:checked").each(function(){
				    $(this).closest('tr').remove();
				});
				$('.ibox-content').removeClass('sk-loading');
				location.reload();
			}
			else
			{
				$('body').removeClass('inprocess');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
				toastr.error(response.message_body, response.message_head);
				$('.ibox-content').removeClass('sk-loading');
			}
		}
	});

});