Fetch defaults in purchase common and sales common related doctypes and fix minor utf-8 issues
diff --git a/erpnext/accounts/DocType Mapper/Purchase Order-Payable Voucher/Purchase Order-Payable Voucher.txt b/erpnext/accounts/DocType Mapper/Purchase Order-Payable Voucher/Purchase Order-Payable Voucher.txt
index e58f738..4bb3141 100644
--- a/erpnext/accounts/DocType Mapper/Purchase Order-Payable Voucher/Purchase Order-Payable Voucher.txt
+++ b/erpnext/accounts/DocType Mapper/Purchase Order-Payable Voucher/Purchase Order-Payable Voucher.txt
@@ -5,145 +5,145 @@
 	{
 		'creation': '2010-08-08 17:09:35',
 		'docstatus': 0,
-		'modified': '2011-10-12 12:10:15',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
+		'modified': '2012-02-06 15:25:06',
+		'modified_by': u'Administrator',
+		'owner': u'Administrator'
 	},
 
 	# These values are common for all Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
+		'doctype': u'Table Mapper Detail',
 		'name': '__common__',
-		'parent': 'Purchase Order-Payable Voucher',
-		'parentfield': 'table_mapper_details',
-		'parenttype': 'DocType Mapper'
+		'parent': u'Purchase Order-Payable Voucher',
+		'parentfield': u'table_mapper_details',
+		'parenttype': u'DocType Mapper'
 	},
 
 	# These values are common for all Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
+		'doctype': u'Field Mapper Detail',
 		'name': '__common__',
-		'parent': 'Purchase Order-Payable Voucher',
-		'parentfield': 'field_mapper_details',
-		'parenttype': 'DocType Mapper'
+		'parent': u'Purchase Order-Payable Voucher',
+		'parentfield': u'field_mapper_details',
+		'parenttype': u'DocType Mapper'
 	},
 
 	# These values are common for all DocType Mapper
 	{
 		'doctype': u'DocType Mapper',
-		'from_doctype': 'Purchase Order',
-		'module': 'Accounts',
+		'from_doctype': u'Purchase Order',
+		'module': u'Accounts',
 		'name': '__common__',
 		'ref_doc_submitted': 1,
-		'to_doctype': 'Payable Voucher'
+		'to_doctype': u'Payable Voucher'
 	},
 
 	# DocType Mapper, Purchase Order-Payable Voucher
 	{
 		'doctype': u'DocType Mapper',
-		'name': 'Purchase Order-Payable Voucher'
+		'name': u'Purchase Order-Payable Voucher'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: flt(obj.qty) - flt(obj.billed_qty)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: flt(obj.qty) - flt(obj.billed_qty)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'qty'
+		'to_field': u'qty'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'purchase_rate',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'purchase_rate',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'rate'
+		'to_field': u'rate'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'amount'
+		'to_field': u'amount'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'import_amount'
+		'to_field': u'import_amount'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'parent',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'parent',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'purchase_order'
+		'to_field': u'purchase_order'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'name',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'name',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'po_detail'
+		'to_field': u'po_detail'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'naming_series',
-		'map': 'No',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'naming_series',
+		'map': u'No',
 		'match_id': 0,
-		'to_field': 'naming_series'
+		'to_field': u'naming_series'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'total_tax',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'total_tax',
+		'map': u'Yes',
 		'match_id': 0,
-		'to_field': 'total_tax'
+		'to_field': u'total_tax'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_table': 'Purchase Order',
+		'doctype': u'Table Mapper Detail',
+		'from_table': u'Purchase Order',
 		'match_id': 0,
-		'to_table': 'Payable Voucher',
-		'validation_logic': 'docstatus =1'
+		'to_table': u'Payable Voucher',
+		'validation_logic': u'docstatus =1'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_field': 'po_details',
-		'from_table': 'PO Detail',
+		'doctype': u'Table Mapper Detail',
+		'from_field': u'po_details',
+		'from_table': u'PO Detail',
 		'match_id': 1,
-		'to_field': 'entries',
-		'to_table': 'PV Detail',
-		'validation_logic': 'ifnull(billed_qty,0)  < qty and docstatus = 1'
+		'to_field': u'entries',
+		'to_table': u'PV Detail',
+		'validation_logic': u'ifnull(billed_qty,0)  < qty and docstatus = 1'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_field': 'purchase_tax_details',
-		'from_table': 'Purchase Tax Detail',
+		'doctype': u'Table Mapper Detail',
+		'from_field': u'purchase_tax_details',
+		'from_table': u'Purchase Tax Detail',
 		'match_id': 2,
-		'to_field': 'purchase_tax_details',
-		'to_table': 'Purchase Tax Detail',
-		'validation_logic': 'docstatus =1'
+		'to_field': u'purchase_tax_details',
+		'to_table': u'Purchase Tax Detail',
+		'validation_logic': u'docstatus =1'
 	}
 ]
\ No newline at end of file
diff --git a/erpnext/accounts/DocType Mapper/Purchase Receipt-Payable Voucher/Purchase Receipt-Payable Voucher.txt b/erpnext/accounts/DocType Mapper/Purchase Receipt-Payable Voucher/Purchase Receipt-Payable Voucher.txt
index 1744c4d..ffc748b 100644
--- a/erpnext/accounts/DocType Mapper/Purchase Receipt-Payable Voucher/Purchase Receipt-Payable Voucher.txt
+++ b/erpnext/accounts/DocType Mapper/Purchase Receipt-Payable Voucher/Purchase Receipt-Payable Voucher.txt
@@ -5,181 +5,181 @@
 	{
 		'creation': '2010-08-08 17:09:35',
 		'docstatus': 0,
-		'modified': '2011-10-12 10:49:26',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
+		'modified': '2012-02-06 15:26:25',
+		'modified_by': u'Administrator',
+		'owner': u'Administrator'
 	},
 
 	# These values are common for all Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
+		'doctype': u'Table Mapper Detail',
 		'name': '__common__',
-		'parent': 'Purchase Receipt-Payable Voucher',
-		'parentfield': 'table_mapper_details',
-		'parenttype': 'DocType Mapper'
+		'parent': u'Purchase Receipt-Payable Voucher',
+		'parentfield': u'table_mapper_details',
+		'parenttype': u'DocType Mapper'
 	},
 
 	# These values are common for all Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
+		'doctype': u'Field Mapper Detail',
 		'name': '__common__',
-		'parent': 'Purchase Receipt-Payable Voucher',
-		'parentfield': 'field_mapper_details',
-		'parenttype': 'DocType Mapper'
+		'parent': u'Purchase Receipt-Payable Voucher',
+		'parentfield': u'field_mapper_details',
+		'parenttype': u'DocType Mapper'
 	},
 
 	# These values are common for all DocType Mapper
 	{
 		'doctype': u'DocType Mapper',
-		'from_doctype': 'Purchase Receipt',
-		'module': 'Accounts',
+		'from_doctype': u'Purchase Receipt',
+		'module': u'Accounts',
 		'name': '__common__',
 		'ref_doc_submitted': 1,
-		'to_doctype': 'Payable Voucher'
+		'to_doctype': u'Payable Voucher'
 	},
 
 	# DocType Mapper, Purchase Receipt-Payable Voucher
 	{
 		'doctype': u'DocType Mapper',
-		'name': 'Purchase Receipt-Payable Voucher'
+		'name': u'Purchase Receipt-Payable Voucher'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: flt(obj.qty) - flt(obj.billed_qty)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: flt(obj.qty) - flt(obj.billed_qty)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'qty'
+		'to_field': u'qty'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'purchase_rate',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'purchase_rate',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'rate'
+		'to_field': u'rate'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'amount'
+		'to_field': u'amount'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'import_amount'
+		'to_field': u'import_amount'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'parent',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'parent',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'purchase_receipt'
+		'to_field': u'purchase_receipt'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'prevdoc_docname',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'prevdoc_docname',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'purchase_order'
+		'to_field': u'purchase_order'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'name',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'name',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'pr_detail'
+		'to_field': u'pr_detail'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'prevdoc_detail_docname',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'prevdoc_detail_docname',
+		'map': u'Yes',
 		'match_id': 1,
-		'to_field': 'po_detail'
+		'to_field': u'po_detail'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'naming_series',
-		'map': 'No',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'naming_series',
+		'map': u'No',
 		'match_id': 0,
-		'to_field': 'naming_series'
+		'to_field': u'naming_series'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'net_total',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'net_total',
+		'map': u'Yes',
 		'match_id': 0,
-		'to_field': 'net_total'
+		'to_field': u'net_total'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'grand_total',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'grand_total',
+		'map': u'Yes',
 		'match_id': 0,
-		'to_field': 'grand_total'
+		'to_field': u'grand_total'
 	},
 
 	# Field Mapper Detail
 	{
-		'doctype': 'Field Mapper Detail',
-		'from_field': 'total_tax',
-		'map': 'Yes',
+		'doctype': u'Field Mapper Detail',
+		'from_field': u'total_tax',
+		'map': u'Yes',
 		'match_id': 0,
-		'to_field': 'total_tax'
+		'to_field': u'total_tax'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_field': 'purchase_receipt_details',
-		'from_table': 'Purchase Receipt Detail',
+		'doctype': u'Table Mapper Detail',
+		'from_field': u'purchase_receipt_details',
+		'from_table': u'Purchase Receipt Detail',
 		'match_id': 1,
-		'to_field': 'entries',
-		'to_table': 'PV Detail',
-		'validation_logic': 'ifnull(billed_qty,0)  < qty'
+		'to_field': u'entries',
+		'to_table': u'PV Detail',
+		'validation_logic': u'ifnull(billed_qty,0)  < qty'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_table': 'Purchase Receipt',
+		'doctype': u'Table Mapper Detail',
+		'from_table': u'Purchase Receipt',
 		'match_id': 0,
-		'to_table': 'Payable Voucher',
-		'validation_logic': 'docstatus=1'
+		'to_table': u'Payable Voucher',
+		'validation_logic': u'docstatus=1'
 	},
 
 	# Table Mapper Detail
 	{
-		'doctype': 'Table Mapper Detail',
-		'from_field': 'purchase_tax_details',
-		'from_table': 'Purchase Tax Detail',
+		'doctype': u'Table Mapper Detail',
+		'from_field': u'purchase_tax_details',
+		'from_table': u'Purchase Tax Detail',
 		'match_id': 2,
-		'to_field': 'purchase_tax_details',
-		'to_table': 'Purchase Tax Detail',
-		'validation_logic': 'docstatus=1'
+		'to_field': u'purchase_tax_details',
+		'to_table': u'Purchase Tax Detail',
+		'validation_logic': u'docstatus=1'
 	}
 ]
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/journal_voucher/journal_voucher.js b/erpnext/accounts/doctype/journal_voucher/journal_voucher.js
index 99fb10a..b63f448 100644
--- a/erpnext/accounts/doctype/journal_voucher/journal_voucher.js
+++ b/erpnext/accounts/doctype/journal_voucher/journal_voucher.js
@@ -1,156 +1,177 @@
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
-  var cp = locals['Control Panel']['Control Panel'];
-  
-  if (!doc.voucher_date) doc.voucher_date = dateutil.obj_to_str(new Date());
+	var cp = locals['Control Panel']['Control Panel'];
+	
+	if (!doc.voucher_date) doc.voucher_date = dateutil.obj_to_str(new Date());
 
-  if(cp.country == 'India') {
-    unhide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
-  }
-  else {
-    hide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
-  }
+	if(cp.country == 'India') {
+		unhide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
+	}
+	else {
+		hide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
+	}
+
+	cur_frm.cscript.load_defaults(doc, cdt, cdn);
+
 }
 
+
+cur_frm.cscript.load_defaults = function(doc, cdt, cdn) {
+	if(!cur_frm.doc.__islocal || !cur_frm.doc.company) { return; }
+
+	doc = locals[doc.doctype][doc.name];
+	var fields_to_refresh = LocalDB.set_default_values(doc);
+	if(fields_to_refresh) { refresh_many(fields_to_refresh); }
+
+	fields_to_refresh = null;
+	var children = getchildren('Journal Voucher Detail', doc.name, 'entries');
+	if(!children) { return; }
+	for(var i=0; i<children.length; i++) {
+		LocalDB.set_default_values(children[i]);
+	}
+	refresh_field('entries');
+}
+
+
 cur_frm.cscript.is_opening = function(doc, cdt, cdn) {
-  hide_field('aging_date');
-  if (doc.is_opening == 'Yes') unhide_field('aging_date');
-  
-  if(doc.docstatus==1) { unhide_field('View Ledger Entry'); }
-  else hide_field('View Ledger Entry');
+	hide_field('aging_date');
+	if (doc.is_opening == 'Yes') unhide_field('aging_date');
+	
+	if(doc.docstatus==1) { unhide_field('View Ledger Entry'); }
+	else hide_field('View Ledger Entry');
 }
 
 cur_frm.cscript.refresh = cur_frm.cscript.is_opening;
 
 cur_frm.fields_dict['entries'].grid.get_field('account').get_query = function(doc) {
-  return "SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company='"+doc.company+"' AND tabAccount.group_or_ledger = 'Ledger' AND tabAccount.docstatus != 2 AND `tabAccount`.%(key)s LIKE '%s' ORDER BY `tabAccount`.name DESC LIMIT 50";
+	return "SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company='"+doc.company+"' AND tabAccount.group_or_ledger = 'Ledger' AND tabAccount.docstatus != 2 AND `tabAccount`.%(key)s LIKE '%s' ORDER BY `tabAccount`.name DESC LIMIT 50";
 }
 
 cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50';
+	return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY	`tabCost Center`.`name` ASC LIMIT 50';
 }
 
 // Restrict Voucher based on Account
 // ---------------------------------
 cur_frm.fields_dict['entries'].grid.get_field('against_voucher').get_query = function(doc) {
-  var d = locals[this.doctype][this.docname];
-  return "SELECT `tabPayable Voucher`.name, `tabPayable Voucher`.credit_to, `tabPayable Voucher`.outstanding_amount,`tabPayable Voucher`.bill_no, `tabPayable Voucher`.bill_date FROM `tabPayable Voucher` WHERE `tabPayable Voucher`.credit_to='"+d.account+"' AND `tabPayable Voucher`.outstanding_amount > 0 AND `tabPayable Voucher`.docstatus = 1 AND `tabPayable Voucher`.%(key)s LIKE '%s' ORDER BY `tabPayable Voucher`.name DESC LIMIT 200";
+	var d = locals[this.doctype][this.docname];
+	return "SELECT `tabPayable Voucher`.name, `tabPayable Voucher`.credit_to, `tabPayable Voucher`.outstanding_amount,`tabPayable Voucher`.bill_no, `tabPayable Voucher`.bill_date FROM `tabPayable Voucher` WHERE `tabPayable Voucher`.credit_to='"+d.account+"' AND `tabPayable Voucher`.outstanding_amount > 0 AND `tabPayable Voucher`.docstatus = 1 AND `tabPayable Voucher`.%(key)s LIKE '%s' ORDER BY `tabPayable Voucher`.name DESC LIMIT 200";
 }
 
 cur_frm.fields_dict['entries'].grid.get_field('against_invoice').get_query = function(doc) {
-  var d = locals[this.doctype][this.docname];
-  return "SELECT `tabReceivable Voucher`.name, `tabReceivable Voucher`.debit_to, `tabReceivable Voucher`.outstanding_amount FROM `tabReceivable Voucher` WHERE `tabReceivable Voucher`.debit_to='"+d.account+"' AND `tabReceivable Voucher`.outstanding_amount > 0 AND `tabReceivable Voucher`.docstatus = 1 AND `tabReceivable Voucher`.%(key)s LIKE '%s' ORDER BY `tabReceivable Voucher`.name DESC LIMIT 200";
+	var d = locals[this.doctype][this.docname];
+	return "SELECT `tabReceivable Voucher`.name, `tabReceivable Voucher`.debit_to, `tabReceivable Voucher`.outstanding_amount FROM `tabReceivable Voucher` WHERE `tabReceivable Voucher`.debit_to='"+d.account+"' AND `tabReceivable Voucher`.outstanding_amount > 0 AND `tabReceivable Voucher`.docstatus = 1 AND `tabReceivable Voucher`.%(key)s LIKE '%s' ORDER BY `tabReceivable Voucher`.name DESC LIMIT 200";
 }
 
 // TDS Account Head
 cur_frm.fields_dict['tax_code'].get_query = function(doc) {
-  return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
+	return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
 }
 
 //Set debit and credit to zero on adding new row
 //----------------------------------------------
 cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
-  var d = locals[cdt][cdn];
-  if(d.idx == 1){
-    d.debit = 0;
-    d.credit = 0;
-  }
+	var d = locals[cdt][cdn];
+	if(d.idx == 1){
+		d.debit = 0;
+		d.credit = 0;
+	}
 }
 
 // Get Outstanding of Payable & Receivable Voucher
 // -----------------------------------------------
 
 cur_frm.cscript.against_voucher = function(doc,cdt,cdn) {
-  var d = locals[cdt][cdn];
-  if (d.against_voucher && !flt(d.debit)) {
-    args = {'doctype': 'Payable Voucher', 'docname': d.against_voucher }
-    get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
-  }
+	var d = locals[cdt][cdn];
+	if (d.against_voucher && !flt(d.debit)) {
+		args = {'doctype': 'Payable Voucher', 'docname': d.against_voucher }
+		get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
+	}
 }
 
 cur_frm.cscript.against_invoice = function(doc,cdt,cdn) {
-  var d = locals[cdt][cdn];
-  if (d.against_invoice && !flt(d.credit)) {
-    args = {'doctype': 'Receivable Voucher', 'docname': d.against_invoice }
-    get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
-  }
+	var d = locals[cdt][cdn];
+	if (d.against_invoice && !flt(d.credit)) {
+		args = {'doctype': 'Receivable Voucher', 'docname': d.against_invoice }
+		get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
+	}
 }
 
 
 // Update Totals
 // ---------------
 cur_frm.cscript.update_totals = function(doc) {
-  var td=0.0; var tc =0.0;
-  var el = getchildren('Journal Voucher Detail', doc.name, 'entries');
-  for(var i in el) {
-    td += flt(el[i].debit);
-    tc += flt(el[i].credit);
-  }
-  var doc = locals[doc.doctype][doc.name];
-  tc += flt(doc.ded_amount)
-  doc.total_debit = td;
-  doc.total_credit = tc;
-  doc.difference = flt(td - tc);
-  refresh_many(['total_debit','total_credit','difference']);
+	var td=0.0; var tc =0.0;
+	var el = getchildren('Journal Voucher Detail', doc.name, 'entries');
+	for(var i in el) {
+		td += flt(el[i].debit);
+		tc += flt(el[i].credit);
+	}
+	var doc = locals[doc.doctype][doc.name];
+	tc += flt(doc.ded_amount)
+	doc.total_debit = td;
+	doc.total_credit = tc;
+	doc.difference = flt(td - tc);
+	refresh_many(['total_debit','total_credit','difference']);
 }
 
 cur_frm.cscript.debit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
 cur_frm.cscript.credit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
 cur_frm.cscript.ded_amount = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
 cur_frm.cscript.rate = function(doc,dt,dn) {
-  doc.ded_amount = doc.total_debit*doc.rate/100;
-  refresh_field('ded_amount');
-  cur_frm.cscript.update_totals(doc); 
+	doc.ded_amount = doc.total_debit*doc.rate/100;
+	refresh_field('ded_amount');
+	cur_frm.cscript.update_totals(doc); 
 }
 cur_frm.cscript['Get Balance'] = function(doc,dt,dn) {
-  cur_frm.cscript.update_totals(doc); 
-  $c_obj(make_doclist(dt,dn), 'get_balance', '', function(r, rt){
-  cur_frm.refresh();
-  });
+	cur_frm.cscript.update_totals(doc); 
+	$c_obj(make_doclist(dt,dn), 'get_balance', '', function(r, rt){
+	cur_frm.refresh();
+	});
 }
 // Get balance
 // -----------
 
 cur_frm.cscript.account = function(doc,dt,dn) {
-  var d = locals[dt][dn];
-  $c_obj('GL Control','get_bal',d.account+'~~~'+doc.fiscal_year, function(r,rt) { d.balance = r.message; refresh_field('balance',d.name,'entries'); });
+	var d = locals[dt][dn];
+	$c_obj('GL Control','get_bal',d.account+'~~~'+doc.fiscal_year, function(r,rt) { d.balance = r.message; refresh_field('balance',d.name,'entries'); });
 } 
 
 cur_frm.cscript.validate = function(doc,cdt,cdn) {
-  cur_frm.cscript.update_totals(doc);
+	cur_frm.cscript.update_totals(doc);
 }
 
 // TDS
 // --------
 cur_frm.cscript['Get TDS'] = function(doc, dt, dn) {
-  $c_obj(make_doclist(dt,dn), 'get_tds', '', function(r, rt){
-    cur_frm.refresh();
-    cur_frm.cscript.update_totals(doc);
-  });
+	$c_obj(make_doclist(dt,dn), 'get_tds', '', function(r, rt){
+		cur_frm.refresh();
+		cur_frm.cscript.update_totals(doc);
+	});
 }
 
 // ***************** Get Print Heading based on Receivable Voucher *****************
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
 }
 
 
 
 cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
-  if(doc.select_print_heading){
-    // print heading
-    cur_frm.pformat.print_heading = doc.select_print_heading;
-  }
-  else
-    cur_frm.pformat.print_heading = "Journal Voucher";
+	if(doc.select_print_heading){
+		// print heading
+		cur_frm.pformat.print_heading = doc.select_print_heading;
+	}
+	else
+		cur_frm.pformat.print_heading = "Journal Voucher";
 }
 
 /****************** Get Accounting Entry *****************/
 cur_frm.cscript['View Ledger Entry'] = function(doc,cdt,cdn){
-  var callback = function(report){
-    report.set_filter('GL Entry', 'Voucher No',doc.name);
-    report.dt.run();
-  }
-  loadreport('GL Entry','General Ledger', callback);
+	var callback = function(report){
+		report.set_filter('GL Entry', 'Voucher No',doc.name);
+		report.dt.run();
+	}
+	loadreport('GL Entry','General Ledger', callback);
 }
 
 
diff --git a/erpnext/accounts/doctype/payable_voucher/payable_voucher.js b/erpnext/accounts/doctype/payable_voucher/payable_voucher.js
index b3cbd63..44dea8a 100644
--- a/erpnext/accounts/doctype/payable_voucher/payable_voucher.js
+++ b/erpnext/accounts/doctype/payable_voucher/payable_voucher.js
@@ -7,99 +7,102 @@
 // On Load
 // --------
 cur_frm.cscript.onload = function(doc,dt,dn) {
-  var cp = locals['Control Panel']['Control Panel'];
-  
-  if(!doc.voucher_date) set_multiple(dt,dn,{voucher_date:get_today()});
-  if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});  
+	var cp = locals['Control Panel']['Control Panel'];
+	
+	if(!doc.voucher_date) set_multiple(dt,dn,{voucher_date:get_today()});
+	if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});	
 
-  if(cp.country == 'India') {
-    unhide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
-  }
-  else {
-    hide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
-  }  
-  
-  if(doc.__islocal){
-    hide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email']);
-  }
+	if(cp.country == 'India') {
+		unhide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
+	}
+	else {
+		hide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
+	}	
+	
+	if(doc.__islocal){
+		hide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email']);
+	}
+	
+	// defined in purchase_common.js
+	cur_frm.cscript.update_item_details(doc, cdt, cdn);
 }
 
 
 //Onload post render
 //------------------------
 cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
-  if(doc.__islocal && doc.supplier) cur_frm.cscript.supplier(doc,dt,dn);
+	if(doc.__islocal && doc.supplier) cur_frm.cscript.supplier(doc,dt,dn);
 }
 
 // Refresh
 // --------
 cur_frm.cscript.refresh = function(doc, dt, dn) {
-  
-  cur_frm.clear_custom_buttons();
+	
+	cur_frm.clear_custom_buttons();
 
-  // Show / Hide button
-  if(doc.docstatus==1 && doc.outstanding_amount > 0)
-    cur_frm.add_custom_button('Make Payment Entry', cur_frm.cscript['Make Bank Voucher']);
-  
-  if(doc.docstatus==1) { 
-    unhide_field(['Repair Outstanding Amt']); 
-    cur_frm.add_custom_button('View Ledger', cur_frm.cscript['View Ledger Entry']);
-  } else hide_field(['Repair Outstanding Amt']);
-  
-  cur_frm.cscript.is_opening(doc, dt, dn);
+	// Show / Hide button
+	if(doc.docstatus==1 && doc.outstanding_amount > 0)
+		cur_frm.add_custom_button('Make Payment Entry', cur_frm.cscript['Make Bank Voucher']);
+	
+	if(doc.docstatus==1) { 
+		unhide_field(['Repair Outstanding Amt']); 
+		cur_frm.add_custom_button('View Ledger', cur_frm.cscript['View Ledger Entry']);
+	} else hide_field(['Repair Outstanding Amt']);
+	
+	cur_frm.cscript.is_opening(doc, dt, dn);
 }
 
 
 //Supplier
 cur_frm.cscript.supplier = function(doc,dt,dn) {
-  var callback = function(r,rt) {
-      var doc = locals[cur_frm.doctype][cur_frm.docname];    
-      get_server_fields('get_credit_to','','',doc, dt, dn, 0, callback2);
-  }
-  
-  var callback2 = function(r,rt){
-    var doc = locals[cur_frm.doctype][cur_frm.docname];    
-    var el = getchildren('PV Detail',doc.name,'entries');
-    for(var i in el){
-      if(el[i].item_code && (!el[i].expense_head || !el[i].cost_center)){
-        args = "{'item_code':'" + el[i].item_code + "','expense_head':'" + el[i].expense_head + "','cost_center':'" + el[i].cost_center + "'}";
-        get_server_fields('get_default_values', args, 'entries', doc, el[i].doctype, el[i].name, 1);
-      }
-    }
-    cur_frm.cscript.calc_amount(doc, 1);
-  }
+	var callback = function(r,rt) {
+			var doc = locals[cur_frm.doctype][cur_frm.docname];		
+			get_server_fields('get_credit_to','','',doc, dt, dn, 0, callback2);
+	}
+	
+	var callback2 = function(r,rt){
+		var doc = locals[cur_frm.doctype][cur_frm.docname];		
+		var el = getchildren('PV Detail',doc.name,'entries');
+		for(var i in el){
+			if(el[i].item_code && (!el[i].expense_head || !el[i].cost_center)){
+				args = "{'item_code':'" + el[i].item_code + "','expense_head':'" + el[i].expense_head + "','cost_center':'" + el[i].cost_center + "'}";
+				get_server_fields('get_default_values', args, 'entries', doc, el[i].doctype, el[i].name, 1);
+			}
+		}
+		cur_frm.cscript.calc_amount(doc, 1);
+	}
 
-  if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1,callback);
-  if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
+	if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1,callback);
+	if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
 }
 
 cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
-  if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+	if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 
 
 cur_frm.fields_dict.supplier_address.on_new = function(dn) {
-  locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 
 cur_frm.cscript.credit_to = function(doc,dt,dn) {
 
-  var callback = function(r,rt) {
-      var doc = locals[cur_frm.doctype][cur_frm.docname];    
-      if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
-      if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
-      cur_frm.refresh();
-  }
+	var callback = function(r,rt) {
+			var doc = locals[cur_frm.doctype][cur_frm.docname];		
+			if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
+			if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
+			cur_frm.refresh();
+	}
 
-  get_server_fields('get_cust','','',doc,dt,dn,1,callback);  
+	get_server_fields('get_cust','','',doc,dt,dn,1,callback);	
 }
 
 
@@ -107,43 +110,43 @@
 //Set expense_head and cost center on adding new row
 //----------------------------------------------
 cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
-  
-  cl = getchildren('PV Detail', doc.name, cur_frm.cscript.fname, doc.doctype);
-  acc = '';
-  cc = '';
+	
+	cl = getchildren('PV Detail', doc.name, cur_frm.cscript.fname, doc.doctype);
+	acc = '';
+	cc = '';
 
-  for(var i = 0; i<cl.length; i++) {
-    if (cl[i].idx == 1){
-      acc = cl[i].expense_head;
-      cc = cl[i].cost_center;
-    }
-    else{
-      if (! cl[i].expense_head) { cl[i].expense_head = acc; refresh_field('expense_head', cl[i].name, 'entries');}
-      if (! cl[i].cost_center)  {cl[i].cost_center = cc; refresh_field('cost_center', cl[i].name, 'entries');}
-    }
-  }
+	for(var i = 0; i<cl.length; i++) {
+		if (cl[i].idx == 1){
+			acc = cl[i].expense_head;
+			cc = cl[i].cost_center;
+		}
+		else{
+			if (! cl[i].expense_head) { cl[i].expense_head = acc; refresh_field('expense_head', cl[i].name, 'entries');}
+			if (! cl[i].cost_center)	{cl[i].cost_center = cc; refresh_field('cost_center', cl[i].name, 'entries');}
+		}
+	}
 }
 
 cur_frm.cscript.is_opening = function(doc, dt, dn) {
-  hide_field('aging_date');
-  if (doc.is_opening == 'Yes') unhide_field('aging_date');
+	hide_field('aging_date');
+	if (doc.is_opening == 'Yes') unhide_field('aging_date');
 }
 
 // Recalculate Button
 // -------------------
 cur_frm.cscript['Recalculate'] = function(doc, dt, dn) {
-  cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
-  calc_total_advance(doc,cdt,cdn);
+	cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
+	calc_total_advance(doc,cdt,cdn);
 }
 
 // Get Items Button
 // -----------------
 cur_frm.cscript['Get Items'] = function(doc, dt, dn) {
-  var callback = function(r,rt) { 
-	  unhide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile','contact_email']);			  
-	  refresh_many(['credit_to','supplier','supplier_address','contact_person','supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email','entries', 'purchase_receipt_main', 'purchase_order_main', 'purchase_tax_details']);
-  }
-  $c_obj(make_doclist(dt,dn),'pull_details','',callback);
+	var callback = function(r,rt) { 
+		unhide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile','contact_email']);				
+		refresh_many(['credit_to','supplier','supplier_address','contact_person','supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email','entries', 'purchase_receipt_main', 'purchase_order_main', 'purchase_tax_details']);
+	}
+	$c_obj(make_doclist(dt,dn),'pull_details','',callback);
 }
 
 // ========== PV Details Table ============
@@ -151,17 +154,17 @@
 // Item Code
 // ----------
 cur_frm.cscript.item_code = function(doc,cdt,cdn){
-  var d = locals[cdt][cdn];
-  if(d.item_code){
-    get_server_fields('get_item_details',d.item_code,'entries',doc,cdt,cdn,1);
-  }
+	var d = locals[cdt][cdn];
+	if(d.item_code){
+		get_server_fields('get_item_details',d.item_code,'entries',doc,cdt,cdn,1);
+	}
 }
 
 // Rate in Deduct Taxes (TDS)
 // --------------------------
 cur_frm.cscript.rate = function(doc,dt,dn) {
-  //This is done as Purchase tax detail and PV detail both contain the same fieldname 'rate'
-  if(dt != 'Purchase Tax Detail')   cur_frm.cscript.calc_amount(doc, 2);
+	//This is done as Purchase tax detail and PV detail both contain the same fieldname 'rate'
+	if(dt != 'Purchase Tax Detail')	 cur_frm.cscript.calc_amount(doc, 2);
 }
 
 // Amount
@@ -171,41 +174,41 @@
 // Get TDS Button
 // ---------------
 cur_frm.cscript['Get TDS'] = function(doc, dt, dn) {
-  var callback = function(r,rt) {
-    cur_frm.refresh();
-    refresh_field('ded_amount');
-    //cur_frm.cscript.calc_total(locals[dt][dn]);
-  }
-  $c_obj(make_doclist(dt,dn), 'get_tds', '', callback);
+	var callback = function(r,rt) {
+		cur_frm.refresh();
+		refresh_field('ded_amount');
+		//cur_frm.cscript.calc_total(locals[dt][dn]);
+	}
+	$c_obj(make_doclist(dt,dn), 'get_tds', '', callback);
 }
 
 // ===================== Advance Allocation ==================
 cur_frm.cscript.allocated_amount = function(doc,cdt,cdn){
-  var d = locals[cdt][cdn];
-  if (d.allocated_amount && d.tds_amount){
-    d.tds_allocated=flt(d.tds_amount*(d.allocated_amount/d.advance_amount))
-    refresh_field('tds_allocated', d.name, 'advance_allocation_details');
-  }
-  tot_tds=0
-  el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
-  for(var i in el){
-    tot_tds += el[i].tds_allocated
-  }
-  doc.tds_amount_on_advance = tot_tds
-  refresh_field('tds_amount_on_advance');
-  
-  calc_total_advance(doc, cdt, cdn);
+	var d = locals[cdt][cdn];
+	if (d.allocated_amount && d.tds_amount){
+		d.tds_allocated=flt(d.tds_amount*(d.allocated_amount/d.advance_amount))
+		refresh_field('tds_allocated', d.name, 'advance_allocation_details');
+	}
+	tot_tds=0
+	el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
+	for(var i in el){
+		tot_tds += el[i].tds_allocated
+	}
+	doc.tds_amount_on_advance = tot_tds
+	refresh_field('tds_amount_on_advance');
+	
+	calc_total_advance(doc, cdt, cdn);
 }
 
 
 // Make Journal Voucher
 // --------------------
 cur_frm.cscript['Make Bank Voucher'] = function() {
-  $c('accounts.get_default_bank_account', { company: cur_frm.doc.company }, function(r, rt) {
-    if(!r.exc) {
-      cur_frm.cscript.make_jv(cur_frm.doc, null, null, r.message);
+	$c('accounts.get_default_bank_account', { company: cur_frm.doc.company }, function(r, rt) {
+		if(!r.exc) {
+			cur_frm.cscript.make_jv(cur_frm.doc, null, null, r.message);
 	}
-  });
+	});
 }
 
 
@@ -213,49 +216,49 @@
 
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 // Item Code
 // ----------
 cur_frm.fields_dict['entries'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-  return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
+	return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
 }
 
 // Credit To
 // ----------
 cur_frm.fields_dict['credit_to'].get_query = function(doc) {
-  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.is_pl_account="No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.is_pl_account="No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
 }
 
 
 // Purchase Order
 // ---------------
 cur_frm.fields_dict['purchase_order_main'].get_query = function(doc) {
-  if (doc.supplier){
-    return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.supplier = "'+ doc.supplier +'" AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`,0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
-  } else {
-    return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`, 0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
-  }
+	if (doc.supplier){
+		return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.supplier = "'+ doc.supplier +'" AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`,0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
+	} else {
+		return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`, 0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
+	}
 }
 
 // Purchase Receipt
 // -----------------
 cur_frm.fields_dict['purchase_receipt_main'].get_query = function(doc) {
-  if (doc.supplier){
-    return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.supplier = "'+ doc.supplier +'" AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
-  } else {
-    return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
-  }
+	if (doc.supplier){
+		return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.supplier = "'+ doc.supplier +'" AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
+	} else {
+		return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
+	}
 }
 
 // Get Print Heading
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
 }
 
 
@@ -263,45 +266,45 @@
 // Expense Head
 // -------------
 cur_frm.fields_dict['entries'].grid.get_field("expense_head").get_query = function(doc) {
-  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"';
+	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"';
 }
 cur_frm.cscript.expense_head = function(doc, cdt, cdn){
-  var d = locals[cdt][cdn];
-  if(d.idx == 1 && d.expense_head){
-    var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
-    for(var i = 0; i < cl.length; i++){
-      if(!cl[i].expense_head) cl[i].expense_head = d.expense_head;
-    }
-  }
-  refresh_field('entries');
+	var d = locals[cdt][cdn];
+	if(d.idx == 1 && d.expense_head){
+		var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
+		for(var i = 0; i < cl.length; i++){
+			if(!cl[i].expense_head) cl[i].expense_head = d.expense_head;
+		}
+	}
+	refresh_field('entries');
 }
 
 
 // Cost Center
 //-------------
 cur_frm.fields_dict['entries'].grid.get_field("cost_center").get_query = function(doc) {
-  return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50';
+	return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY	`tabCost Center`.`name` ASC LIMIT 50';
 }
 
 cur_frm.cscript.cost_center = function(doc, cdt, cdn){
-  var d = locals[cdt][cdn];
-  if(d.idx == 1 && d.cost_center){
-    var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
-    for(var i = 0; i < cl.length; i++){
-      if(!cl[i].cost_center) cl[i].cost_center = d.cost_center;
-    }
-  }
-  refresh_field('entries');
+	var d = locals[cdt][cdn];
+	if(d.idx == 1 && d.cost_center){
+		var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
+		for(var i = 0; i < cl.length; i++){
+			if(!cl[i].cost_center) cl[i].cost_center = d.cost_center;
+		}
+	}
+	refresh_field('entries');
 }
 
 
 // TDS Account Head
 cur_frm.fields_dict['tax_code'].get_query = function(doc) {
-  return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
+	return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
 }
 
 cur_frm.cscript.tax_code = function(doc, dt, dn) {
-  get_server_fields('get_tds_rate','','',doc, dt, dn, 0);
+	get_server_fields('get_tds_rate','','',doc, dt, dn, 0);
 }
 
 /* ***************************** UTILITY FUNCTIONS ************************ */
@@ -309,69 +312,69 @@
 // Calculate Advance
 // ------------------
 var calc_total_advance = function(doc,cdt,cdn) {
-  var doc = locals[doc.doctype][doc.name];
-  var el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
-  var tot_tds=0;
-  var total_advance = 0;
-  for(var i in el) {
-    if (! el[i].allocated_amount == 0) {
-      total_advance += flt(el[i].allocated_amount);
-      tot_tds += flt(el[i].tds_allocated)
-    }
-  }
-  doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.ded_amount);
-  doc.tds_amount_on_advance = flt(tot_tds);
-  doc.total_advance = flt(total_advance);
-  doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(total_advance);
-  refresh_many(['total_advance','outstanding_amount','tds_amount_on_advance', 'total_amount_to_pay']);
+	var doc = locals[doc.doctype][doc.name];
+	var el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
+	var tot_tds=0;
+	var total_advance = 0;
+	for(var i in el) {
+		if (! el[i].allocated_amount == 0) {
+			total_advance += flt(el[i].allocated_amount);
+			tot_tds += flt(el[i].tds_allocated)
+		}
+	}
+	doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.ded_amount);
+	doc.tds_amount_on_advance = flt(tot_tds);
+	doc.total_advance = flt(total_advance);
+	doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(total_advance);
+	refresh_many(['total_advance','outstanding_amount','tds_amount_on_advance', 'total_amount_to_pay']);
 }
 
 // Make JV
 // --------
 cur_frm.cscript.make_jv = function(doc, dt, dn, bank_account) {
-  var jv = LocalDB.create('Journal Voucher');
-  jv = locals['Journal Voucher'][jv];
-  jv.voucher_type = 'Bank Voucher';
-  jv.remark = repl('Payment against voucher %(vn)s for %(rem)s', {vn:doc.name, rem:doc.remarks});
-  jv.total_debit = doc.outstanding_amount;
-  jv.total_credit = doc.outstanding_amount;
-  jv.fiscal_year = doc.fiscal_year;
-  jv.company = doc.company;
-  
-  // debit to creditor
-  var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
-  d1.account = doc.credit_to;
-  d1.debit = doc.outstanding_amount;
-  d1.against_voucher = doc.name;
-  
-  // credit to bank
-  var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
-  d1.account = bank_account;
-  d1.credit = doc.outstanding_amount;
-  
-  loaddoc('Journal Voucher', jv.name);
+	var jv = LocalDB.create('Journal Voucher');
+	jv = locals['Journal Voucher'][jv];
+	jv.voucher_type = 'Bank Voucher';
+	jv.remark = repl('Payment against voucher %(vn)s for %(rem)s', {vn:doc.name, rem:doc.remarks});
+	jv.total_debit = doc.outstanding_amount;
+	jv.total_credit = doc.outstanding_amount;
+	jv.fiscal_year = doc.fiscal_year;
+	jv.company = doc.company;
+	
+	// debit to creditor
+	var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
+	d1.account = doc.credit_to;
+	d1.debit = doc.outstanding_amount;
+	d1.against_voucher = doc.name;
+	
+	// credit to bank
+	var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
+	d1.account = bank_account;
+	d1.credit = doc.outstanding_amount;
+	
+	loaddoc('Journal Voucher', jv.name);
 }
 
 // ***************** Get project name *****************
 cur_frm.fields_dict['entries'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
 }
 
 
 cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
-  if(doc.select_print_heading){
-    // print heading
-    cur_frm.pformat.print_heading = doc.select_print_heading;
-  }
-  else
-    cur_frm.pformat.print_heading = "Purchase Invoice";
+	if(doc.select_print_heading){
+		// print heading
+		cur_frm.pformat.print_heading = doc.select_print_heading;
+	}
+	else
+		cur_frm.pformat.print_heading = "Purchase Invoice";
 }
 
 /****************** Get Accounting Entry *****************/
 cur_frm.cscript['View Ledger Entry'] = function(){
-  var callback = function(report){
-    report.set_filter('GL Entry', 'Voucher No',cur_frm.doc.name);
-    report.dt.run();
-  }
-  loadreport('GL Entry','General Ledger', callback);
+	var callback = function(report){
+		report.set_filter('GL Entry', 'Voucher No',cur_frm.doc.name);
+		report.dt.run();
+	}
+	loadreport('GL Entry','General Ledger', callback);
 }
diff --git a/erpnext/accounts/doctype/payable_voucher/payable_voucher.py b/erpnext/accounts/doctype/payable_voucher/payable_voucher.py
index a7e128b..e220756 100644
--- a/erpnext/accounts/doctype/payable_voucher/payable_voucher.py
+++ b/erpnext/accounts/doctype/payable_voucher/payable_voucher.py
@@ -92,7 +92,19 @@
 
 	# Get Item Details
 	# -----------------		
-	def get_item_details(self,arg):
+	def get_item_details(self, arg=None):
+		if arg:
+			return self.get_pv_details(arg)
+		else:
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					ret = self.get_pv_details(doc.item_code)
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]
+
+
+	def get_pv_details(self, arg):
 		item_det = sql("select item_name, brand, description, item_group,purchase_account,cost_center from tabItem where name=%s",arg,as_dict=1)
 		tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg)
 		t = {}
@@ -110,6 +122,8 @@
 			'item_tax_rate'			: str(t)
 		}
 		return ret
+
+
 		
 	# Advance Allocation
 	# -------------------
diff --git a/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.js b/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.js
index e56b16c..dcd522b 100644
--- a/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.js
+++ b/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.js
@@ -25,6 +25,9 @@
 		if(doc.is_pos ==1) cur_frm.cscript.is_pos(doc, dt, dn);
 
  			hide_field(['customer_address', 'contact_person', 'customer_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
+
+		// defined in sales_common.js
+		cur_frm.cscript.update_item_details(doc, cdt, cdn);		
 	}
 }
 
diff --git a/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.py b/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.py
index 87d0373..22294c5 100644
--- a/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.py
+++ b/erpnext/accounts/doctype/receivable_voucher/receivable_voucher.py
@@ -147,8 +147,22 @@
 
 	# Item Details
 	# -------------
-	def get_item_details(self, item_code):
-		ret = get_obj('Sales Common').get_item_details(item_code, self)
+	def get_item_details(self, item_code=None):
+		if item_code:
+			ret = get_obj('Sales Common').get_item_details(item_code, self)
+			return self.get_pos_details(item_code, ret)
+		else:
+			obj = get_obj('Sales Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					ret = obj.get_item_details(doc.item_code, self)
+					ret = self.get_pos_details(item_code, ret)
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]					
+
+
+	def get_pos_details(self, item_code, ret):
 		if item_code and cint(self.doc.is_pos) == 1:
 			dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where user = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1)				 
 			if not dtl:
@@ -160,7 +174,8 @@
 				actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse']))		
 				ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0
 		return ret
- 
+
+
 	# Fetch ref rate from item master as per selected price list
 	def get_adj_percent(self, arg=''):
 		get_obj('Sales Common').get_adj_percent(self)
diff --git a/erpnext/buying/doctype/indent/indent.js b/erpnext/buying/doctype/indent/indent.js
index d9008ba..28c5a5a 100644
--- a/erpnext/buying/doctype/indent/indent.js
+++ b/erpnext/buying/doctype/indent/indent.js
@@ -3,76 +3,78 @@
 
 $import(Purchase Common)
 $import(SMS Control)
-cur_frm.cscript.indent_doctype_label =  get_doctype_label('Indent');
-  
+cur_frm.cscript.indent_doctype_label =	get_doctype_label('Indent');
+	
 //========================== On Load =================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
-  if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date())
-  if (!doc.status) doc.status = 'Draft';
-  
+	if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date())
+	if (!doc.status) doc.status = 'Draft';
+
+	// defined in purchase_common.js
+	//cur_frm.cscript.update_item_details(doc, cdt, cdn);
 }
 
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
-  // second call
-  if(doc.__islocal){ 
-    cur_frm.cscript.get_item_defaults(doc);
-  }	
+	// second call
+	if(doc.__islocal){ 
+		cur_frm.cscript.get_item_defaults(doc);
+	}	
 }
 
 cur_frm.cscript.get_item_defaults = function(doc) {
-    var ch = getchildren( 'Indent Detail', doc.name, 'indent_details');
-    if (flt(ch.length) > 0){
-      $c_obj(make_doclist(doc.doctype, doc.name), 'get_item_defaults', '', function(r, rt) {refresh_field('indent_details'); });
-    }
+		var ch = getchildren( 'Indent Detail', doc.name, 'indent_details');
+		if (flt(ch.length) > 0){
+			$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_defaults', '', function(r, rt) {refresh_field('indent_details'); });
+		}
 }
 
 
 //======================= Refresh =====================================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) { 
 
-  // Unhide Fields in Next Steps
-  // ---------------------------------
-  
-  cur_frm.clear_custom_buttons();
+	// Unhide Fields in Next Steps
+	// ---------------------------------
+	
+	cur_frm.clear_custom_buttons();
 
-  if(doc.docstatus == 1 && doc.status != 'Stopped'){
-    var ch = getchildren('Indent Detail',doc.name,'indent_details');
-    var is_closed = 1;
-    for(var i in ch){
-      if(flt(ch[i].qty) > flt(ch[i].ordered_qty)) is_closed = 0;
-    }
-    if(!is_closed) {
-  	  cur_frm.add_custom_button('Make Purchase Order', cur_frm.cscript['Make Purchase Order'])
-  	  cur_frm.add_custom_button('Stop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Stop Purchase Requisition'])
-    }
-    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-  }
+	if(doc.docstatus == 1 && doc.status != 'Stopped'){
+		var ch = getchildren('Indent Detail',doc.name,'indent_details');
+		var is_closed = 1;
+		for(var i in ch){
+			if(flt(ch[i].qty) > flt(ch[i].ordered_qty)) is_closed = 0;
+		}
+		if(!is_closed) {
+			cur_frm.add_custom_button('Make Purchase Order', cur_frm.cscript['Make Purchase Order'])
+			cur_frm.add_custom_button('Stop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Stop Purchase Requisition'])
+		}
+		cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+	}
  
-  if(doc.docstatus == 1 && doc.status == 'Stopped')
-    cur_frm.add_custom_button('Unstop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Unstop Purchase Requisition'])
-    
-  if(doc.docstatus == 1)
-    unhide_field(['Repair Purchase Requisition']);
-  else
-    hide_field(['Repair Purchase Requisition']);
+	if(doc.docstatus == 1 && doc.status == 'Stopped')
+		cur_frm.add_custom_button('Unstop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Unstop Purchase Requisition'])
+		
+	if(doc.docstatus == 1)
+		unhide_field(['Repair Purchase Requisition']);
+	else
+		hide_field(['Repair Purchase Requisition']);
 }
 
 //======================= validation ===================================
 cur_frm.cscript.validate = function(doc,cdt,cdn){
-  is_item_table(doc,cdt,cdn);
+	is_item_table(doc,cdt,cdn);
 }
 //======================= transaction date =============================
 cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
-  if(doc.__islocal){ 
-    cur_frm.cscript.get_default_schedule_date(doc);
-  }
+	if(doc.__islocal){ 
+		cur_frm.cscript.get_default_schedule_date(doc);
+	}
 }
 
 //=================== Quantity ===================================================================
 cur_frm.cscript.qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if (flt(d.qty) < flt(d.min_order_qty))
-    alert("Warning: " + cur_frm.cscript.indent_doctype_label + " Qty is less than Minimum Order Qty");
+	var d = locals[cdt][cdn];
+	if (flt(d.qty) < flt(d.min_order_qty))
+		alert("Warning: " + cur_frm.cscript.indent_doctype_label + " Qty is less than Minimum Order Qty");
 }
 
 // On Button Click Functions
@@ -80,43 +82,43 @@
 
 // Make Purchase Order
 cur_frm.cscript['Make Purchase Order'] = function() {
-  var doc = cur_frm.doc;
-  n = createLocal('Purchase Order');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Purchase Order'][n]]),
-    'from_doctype':doc.doctype,
-    'to_doctype':'Purchase Order',
-    'from_docname':doc.name,
-    'from_to_list':"[['Indent','Purchase Order'],['Indent Detail','PO Detail']]"
-    }, function(r,rt) {
-       loaddoc('Purchase Order', n);
-    }
-  );
+	var doc = cur_frm.doc;
+	n = createLocal('Purchase Order');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Purchase Order'][n]]),
+		'from_doctype':doc.doctype,
+		'to_doctype':'Purchase Order',
+		'from_docname':doc.name,
+		'from_to_list':"[['Indent','Purchase Order'],['Indent Detail','PO Detail']]"
+		}, function(r,rt) {
+			 loaddoc('Purchase Order', n);
+		}
+	);
 }
 
 // Stop INDENT
 // ==================================================================================================
 cur_frm.cscript['Stop Purchase Requisition'] = function() {
-  var doc = cur_frm.doc;
-  var check = confirm("Do you really want to STOP this " + cur_frm.cscript.indent_doctype_label + "?");
+	var doc = cur_frm.doc;
+	var check = confirm("Do you really want to STOP this " + cur_frm.cscript.indent_doctype_label + "?");
 
-  if (check) {
-    $c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-    });
-  }
+	if (check) {
+		$c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+		});
+	}
 }
 
 // Un Stop INDENT
 //====================================================================================================
 cur_frm.cscript['Unstop Purchase Requisition'] = function(){
-  var doc = cur_frm.doc
-  var check = confirm("Do you really want to UNSTOP this " + cur_frm.cscript.indent_doctype_label + "?");
-  
-  if (check) {
-    $c('runserverobj', args={'method':'update_status', 'arg': 'Submitted','docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-      
-    });
-  }
+	var doc = cur_frm.doc
+	var check = confirm("Do you really want to UNSTOP this " + cur_frm.cscript.indent_doctype_label + "?");
+	
+	if (check) {
+		$c('runserverobj', args={'method':'update_status', 'arg': 'Submitted','docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+			
+		});
+	}
 }
diff --git a/erpnext/buying/doctype/indent/indent.py b/erpnext/buying/doctype/indent/indent.py
index 882098f..148d50d 100644
--- a/erpnext/buying/doctype/indent/indent.py
+++ b/erpnext/buying/doctype/indent/indent.py
@@ -90,7 +90,21 @@
 	# get item details
 	# ---------------------------------
 	def get_item_details(self, arg =''):
-		return get_obj(dt='Purchase Common').get_item_details(self,arg)
+		if arg:
+			return get_obj(dt='Purchase Common').get_item_details(self,arg)
+		else:
+			obj = get_obj('Purchase Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					temp = {
+						'item_code': doc.fields.get('item_code'),
+						'warehouse': doc.fields.get('warehouse')
+					}
+					ret = obj.get_item_details(self, json.dumps(temp))
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]
+
 
 	# Get UOM Details
 	# ---------------------------------
diff --git a/erpnext/buying/doctype/purchase_common/purchase_common.js b/erpnext/buying/doctype/purchase_common/purchase_common.js
index 53304b0..541a225 100644
--- a/erpnext/buying/doctype/purchase_common/purchase_common.js
+++ b/erpnext/buying/doctype/purchase_common/purchase_common.js
@@ -7,389 +7,433 @@
 
 
 cur_frm.cscript.get_default_schedule_date = function(doc) {
-    var ch = getchildren( tname, doc.name, fname);
-    if (flt(ch.length) > 0){
-      $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_schedule_date', '', function(r, rt) { refresh_field(fname); });
-    }
+		var ch = getchildren( tname, doc.name, fname);
+		if (flt(ch.length) > 0){
+			$c_obj(make_doclist(doc.doctype, doc.name), 'get_default_schedule_date', '', function(r, rt) { refresh_field(fname); });
+		}
+}
+
+
+// Gets called after existing item details are update to fill in
+// remaining default values
+cur_frm.cscript.load_defaults = function(doc, dt, dn) {
+	if(!cur_frm.doc.__islocal) { return; }
+
+	doc = locals[doc.doctype][doc.name];
+	var fields_to_refresh = LocalDB.set_default_values(doc);
+	if(fields_to_refresh) { refresh_many(fields_to_refresh); }
+
+	fields_to_refresh = null;
+	var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(!children) { return; }
+	for(var i=0; i<children.length; i++) {
+		LocalDB.set_default_values(children[i]);
+	}
+	refresh_field(cur_frm.cscript.fname);
+}
+
+// Update existing item details
+cur_frm.cscript.update_item_details = function(doc, dt, dn) {
+	if(!cur_frm.doc.__islocal) return;
+	var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(children) {
+		$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_details', '',
+		function(r, rt) {
+			if(!r.exc) {
+				refresh_field(cur_frm.cscript.fname);
+				doc = locals[doc.doctype][doc.name];
+				cur_frm.cscript.load_defaults(doc, dt, dn);
+			}
+		});
+	}
 }
 
 
 // ======================== Conversion Rate ==========================================
 cur_frm.cscript.conversion_rate = function(doc,cdt,cdn) {
-  cur_frm.cscript.calc_amount( doc, 1);
+	cur_frm.cscript.calc_amount( doc, 1);
 }
 
 //==================== Item Code Get Query =======================================================
 // Only Is Purchase Item = 'Yes' and Items not moved to trash are allowed.
 cur_frm.fields_dict[fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-  return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
+	return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
 }
 
 //==================== Get Item Code Details =====================================================
 cur_frm.cscript.item_code = function(doc,cdt,cdn) {
-  var d = locals[cdt][cdn];
-  if (d.item_code) {
-    temp = "{'item_code':'"+(d.item_code?d.item_code:'')+"', 'warehouse':'"+(d.warehouse?d.warehouse:'')+"'}"
-    get_server_fields('get_item_details', temp, fname, doc, cdt, cdn, 1);
-  }
+	var d = locals[cdt][cdn];
+	if (d.item_code) {
+		temp = {
+			item_code: d.item_code || '',
+			warehouse: d.warehouse || ''
+		}
+		get_server_fields('get_item_details', JSON.stringify(temp), fname, doc, cdt, cdn, 1);
+	}
 }
 
 //==================== Update Stock Qty ==========================================================
 cur_frm.cscript.update_stock_qty = function(doc,cdt,cdn){
-  d = locals[cdt][cdn]
-  // Step 1:=> Check if qty , uom, conversion_factor
-  if (d.qty && d.uom && d.conversion_factor){
-    // Step 2:=> Set stock_qty = qty * conversion_factor
-    d.stock_qty = flt(flt(d.qty) * flt(d.conversion_factor));
-    // Step 3:=> Refer stock_qty field a that particular row.
-    refresh_field('stock_qty' , d.name,fname);
-  }
+	d = locals[cdt][cdn]
+	// Step 1:=> Check if qty , uom, conversion_factor
+	if (d.qty && d.uom && d.conversion_factor){
+		// Step 2:=> Set stock_qty = qty * conversion_factor
+		d.stock_qty = flt(flt(d.qty) * flt(d.conversion_factor));
+		// Step 3:=> Refer stock_qty field a that particular row.
+		refresh_field('stock_qty' , d.name,fname);
+	}
 }
 
 //==================== UOM ======================================================================
 cur_frm.cscript.uom = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if (d.item_code && d.uom) {
-    call_back = function(doc, cdt, cdn){
-      cur_frm.cscript.calc_amount(doc, 2);
-    }
-    str_arg = {'item_code':d.item_code, 'uom':d.uom, 'stock_qty':flt(d.stock_qty), 'qty': flt(d.qty), 'conversion_rate':doc.conversion_rate}
-    // Updates Conversion Factor, Qty and Purchase Rate
-    get_server_fields('get_uom_details',JSON.stringify(str_arg), fname, doc,cdt,cdn,1, call_back);
-    // don't make mistake of calling update_stock_qty() the get_uom_details returns stock_qty as per conversion factor properly
-  }
+	var d = locals[cdt][cdn];
+	if (d.item_code && d.uom) {
+		call_back = function(doc, cdt, cdn){
+			cur_frm.cscript.calc_amount(doc, 2);
+		}
+		str_arg = {'item_code':d.item_code, 'uom':d.uom, 'stock_qty':flt(d.stock_qty), 'qty': flt(d.qty), 'conversion_rate':doc.conversion_rate}
+		// Updates Conversion Factor, Qty and Purchase Rate
+		get_server_fields('get_uom_details',JSON.stringify(str_arg), fname, doc,cdt,cdn,1, call_back);
+		// don't make mistake of calling update_stock_qty() the get_uom_details returns stock_qty as per conversion factor properly
+	}
 }
 
 
 //==================== Conversion factor =========================================================
 cur_frm.cscript.conversion_factor = function(doc, cdt, cdn) {
-  cur_frm.cscript.uom(doc, cdt, cdn);
+	cur_frm.cscript.uom(doc, cdt, cdn);
 }
 
 //==================== stock qty ======================================================================
 cur_frm.cscript.stock_qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if(d.uom && d.qty){
-    d.conversion_factor = flt(d.stock_qty)/flt(d.qty);
-    refresh_field('conversion_factor', d.name, fname);
-  }
+	var d = locals[cdt][cdn];
+	if(d.uom && d.qty){
+		d.conversion_factor = flt(d.stock_qty)/flt(d.qty);
+		refresh_field('conversion_factor', d.name, fname);
+	}
 }
 
 //==================== Warehouse ================================================================
 cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if (d.item_code && d.warehouse) {
-    str_arg = "{'item_code':'" +  (d.item_code?d.item_code:'') + "', 'warehouse':'" + (d.warehouse?d.warehouse:'') + "'}"
-    get_server_fields('get_bin_details', str_arg, fname, doc, cdt, cdn, 1);
-  }  
+	var d = locals[cdt][cdn];
+	if (d.item_code && d.warehouse) {
+		str_arg = "{'item_code':'" +	(d.item_code?d.item_code:'') + "', 'warehouse':'" + (d.warehouse?d.warehouse:'') + "'}"
+		get_server_fields('get_bin_details', str_arg, fname, doc, cdt, cdn, 1);
+	}	
 }
 
 //=================== Quantity ===================================================================
 cur_frm.cscript.qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  // Step 1: => Update Stock Qty 
-  cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-  // Step 2: => Calculate Amount
-  cur_frm.cscript.calc_amount(doc, 2);
+	var d = locals[cdt][cdn];
+	// Step 1: => Update Stock Qty 
+	cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
+	// Step 2: => Calculate Amount
+	cur_frm.cscript.calc_amount(doc, 2);
 }
 
 
 //=================== Purchase Rate ==============================================================
 cur_frm.cscript.purchase_rate = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 2);
+	cur_frm.cscript.calc_amount(doc, 2);
 }
 
 //==================== Import Rate ================================================================
 cur_frm.cscript.import_rate = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 1);
+	cur_frm.cscript.calc_amount(doc, 1);
 }
 
 //==================== Discount Rate ================================================================
 cur_frm.cscript.discount_rate = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 4);
+	cur_frm.cscript.calc_amount(doc, 4);
 }
 //==================== Purchase Ref Rate ================================================================
 cur_frm.cscript.purchase_ref_rate = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 4);
+	cur_frm.cscript.calc_amount(doc, 4);
 }
 //==================== Import Ref Rate ================================================================
 cur_frm.cscript.import_ref_rate = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 5);
+	cur_frm.cscript.calc_amount(doc, 5);
 }
 
 //==================== check if item table is blank ==============================================
 var is_item_table = function(doc,cdt,cdn) {
-  // Step 1 :=>Get all childrens/ rows from Detail Table
-  var cl = getchildren(tname, doc.name, fname);
-  // Step 2 :=> If there are no rows then set validated = false, I hope this will stop further execution of code.
-  if (cl.length == 0) {
-    alert("There is no item in table"); validated = false;
-  }
+	// Step 1 :=>Get all childrens/ rows from Detail Table
+	var cl = getchildren(tname, doc.name, fname);
+	// Step 2 :=> If there are no rows then set validated = false, I hope this will stop further execution of code.
+	if (cl.length == 0) {
+		alert("There is no item in table"); validated = false;
+	}
 }
 
 //==================== Validate ====================================================================
 cur_frm.cscript.validate = function(doc, cdt, cdn) {
-  // Step 1:=> check if item table is blank
-  is_item_table(doc,cdt,cdn);
-  // Step 2:=> Calculate Amount
-  cur_frm.cscript.calc_amount(doc, 1);
+	// Step 1:=> check if item table is blank
+	is_item_table(doc,cdt,cdn);
+	// Step 2:=> Calculate Amount
+	cur_frm.cscript.calc_amount(doc, 1);
 
-  // calculate advances if pv
-  if(doc.doctype == 'Payable Voucher') calc_total_advance(doc, cdt, cdn);
+	// calculate advances if pv
+	if(doc.doctype == 'Payable Voucher') calc_total_advance(doc, cdt, cdn);
 }
 
 // **************** RE-CALCULATE VALUES ***************************
 
 cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) {
-  cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
+	cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
 }
 
 cur_frm.cscript['Calculate Tax'] = function(doc, cdt, cdn) {
-  var other_fname  = cur_frm.cscript.other_fname;
+	var other_fname	= cur_frm.cscript.other_fname;
 
-  var cl = getchildren('Purchase Tax Detail', doc.name, other_fname, doc.doctype);
-  for(var i = 0; i<cl.length; i++){
-    cl[i].total_tax_amount = 0;
-    cl[i].total_amount = 0;
-    cl[i].tax_amount = 0;                    // this is done to calculate other charges
-    cl[i].total = 0;
-    if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
-      alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
-      validated = false;
-    }
-  }
-  cur_frm.cscript.calc_amount(doc, 1);
+	var cl = getchildren('Purchase Tax Detail', doc.name, other_fname, doc.doctype);
+	for(var i = 0; i<cl.length; i++){
+		cl[i].total_tax_amount = 0;
+		cl[i].total_amount = 0;
+		cl[i].tax_amount = 0;										// this is done to calculate other charges
+		cl[i].total = 0;
+		if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
+			alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
+			validated = false;
+		}
+	}
+	cur_frm.cscript.calc_amount(doc, 1);
 }
 
 
 
 cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) {
-  doc = locals[doc.doctype][doc.name];
-  var detail = '';
-  detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
-  return detail;
+	doc = locals[doc.doctype][doc.name];
+	var detail = '';
+	detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
+	return detail;
 }
 
 cur_frm.cscript.amount = function(doc, cdt, cdn) {
-  cur_frm.cscript.calc_amount(doc, 3);
+	cur_frm.cscript.calc_amount(doc, 3);
 }
 
 
-//====================== Calculate Amount for PO and PR not for PV  ============================================================
+//====================== Calculate Amount for PO and PR not for PV	============================================================
 cur_frm.cscript.calc_amount = function(doc, n) {
-  // Set defaults
-  doc = locals[doc.doctype][doc.name]
-  var other_fname  = cur_frm.cscript.other_fname;
-  if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
-  if(!n) n=0;
-  var net_total = 0;
-  var net_total_import = 0;
-  
-  var cl = getchildren(tname, doc.name, fname);
-  
-  for(var i=0;i<cl.length;i++) 
-  {
+	// Set defaults
+	doc = locals[doc.doctype][doc.name]
+	var other_fname	= cur_frm.cscript.other_fname;
+	if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
+	if(!n) n=0;
+	var net_total = 0;
+	var net_total_import = 0;
+	
+	var cl = getchildren(tname, doc.name, fname);
+	
+	for(var i=0;i<cl.length;i++) 
+	{
 	var rate_fld = (doc.doctype != 'Payable Voucher') ? 'purchase_rate': 'rate';
-    var tmp = {};
+		var tmp = {};
 	if(!cl[i].discount_rate) cl[i].discount_rate = 0;
 
-    if(n == 1){ 
-      set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
-	  set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].import_ref_rate) - flt(cl[i].import_rate) ) * 100 )/flt(cl[i].import_ref_rate)) }, fname);
-	  tmp[rate_fld] = flt(doc.conversion_rate) * flt(cl[i].import_rate);
-      set_multiple(tname, cl[i].name, tmp, fname);
+		if(n == 1){ 
+			set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
+		set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].import_ref_rate) - flt(cl[i].import_rate) ) * 100 )/flt(cl[i].import_ref_rate)) }, fname);
+		tmp[rate_fld] = flt(doc.conversion_rate) * flt(cl[i].import_rate);
+			set_multiple(tname, cl[i].name, tmp, fname);
 
-      set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(doc.conversion_rate) * flt(cl[i].import_rate))}, fname);
-      set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i].import_rate))}, fname);
+			set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(doc.conversion_rate) * flt(cl[i].import_rate))}, fname);
+			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i].import_rate))}, fname);
 
-    }else if(n == 2){
-	  set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
-	  set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].purchase_ref_rate) - flt(cl[i][rate_fld]) ) * 100 )/flt(cl[i].purchase_ref_rate)) }, fname);
-      set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld])),}, fname);
-	  set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate)) }, fname);
-      set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *  flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
+		}else if(n == 2){
+		set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
+		set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].purchase_ref_rate) - flt(cl[i][rate_fld]) ) * 100 )/flt(cl[i].purchase_ref_rate)) }, fname);
+			set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld])),}, fname);
+		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate)) }, fname);
+			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
 
 	}else if(n == 3){
-	  tmp[rate_fld] = flt(flt(cl[i].amount) / flt(cl[i].qty));
-      set_multiple(tname, cl[i].name, tmp, fname);
-      set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-      set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *  flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
+		tmp[rate_fld] = flt(flt(cl[i].amount) / flt(cl[i].qty));
+			set_multiple(tname, cl[i].name, tmp, fname);
+			set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
+			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
 
-    }else if( n==4){	  
+		}else if( n==4){		
 
-	  set_multiple(tname, cl[i].name, {'import_ref_rate': flt(flt(cl[i].purchase_ref_rate) / flt(doc.conversion_rate))}, fname);
+		set_multiple(tname, cl[i].name, {'import_ref_rate': flt(flt(cl[i].purchase_ref_rate) / flt(doc.conversion_rate))}, fname);
 
-      tmp[rate_fld] = flt( flt(cl[i].purchase_ref_rate) - flt(flt(cl[i].purchase_ref_rate)*flt(cl[i].discount_rate)/100) )
-	  set_multiple(tname, cl[i].name, tmp, fname);
+			tmp[rate_fld] = flt( flt(cl[i].purchase_ref_rate) - flt(flt(cl[i].purchase_ref_rate)*flt(cl[i].discount_rate)/100) )
+		set_multiple(tname, cl[i].name, tmp, fname);
 
-	  set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-	  set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
-	  set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *  flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
+		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
+		set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
+		set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
 
 	}else if( n==5){	
-	  tmp[rate_fld] = flt( flt(cl[i].import_ref_rate) - flt(flt(cl[i].import_ref_rate)*flt(cl[i].discount_rate)/100) ) * flt(doc.conversion_rate);
-	  set_multiple(tname, cl[i].name, {'purchase_ref_rate': flt(flt(cl[i].import_ref_rate) * flt(doc.conversion_rate))}, fname);
-	  set_multiple(tname, cl[i].name, tmp, fname);
-	  set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-	  set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
-	  set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *  flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
+		tmp[rate_fld] = flt( flt(cl[i].import_ref_rate) - flt(flt(cl[i].import_ref_rate)*flt(cl[i].discount_rate)/100) ) * flt(doc.conversion_rate);
+		set_multiple(tname, cl[i].name, {'purchase_ref_rate': flt(flt(cl[i].import_ref_rate) * flt(doc.conversion_rate))}, fname);
+		set_multiple(tname, cl[i].name, tmp, fname);
+		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
+		set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
+		set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
 	}
 	
-    if (n != 3){
-      net_total += flt(flt(cl[i].qty) * flt(cl[i][rate_fld]));
-      net_total_import += flt(flt(cl[i].qty) * flt(cl[i].import_rate));
-    } else if(n == 3){
-      net_total += flt(cl[i].amount);
-      net_total_import += flt(cl[i].amount) / flt(doc.conversion_rate);
-    }
-    //update stock uom
-    cur_frm.cscript.update_stock_qty(doc, tname, cl[i].name);
-  }
-  doc.net_total = flt(net_total) ;
-  doc.net_total_import = flt(net_total_import) ;
-  refresh_field('net_total');
-  refresh_field('net_total_import');
-  
-  cur_frm.cscript.val_cal_charges(doc, cdt, cdn, tname, fname, other_fname);
+		if (n != 3){
+			net_total += flt(flt(cl[i].qty) * flt(cl[i][rate_fld]));
+			net_total_import += flt(flt(cl[i].qty) * flt(cl[i].import_rate));
+		} else if(n == 3){
+			net_total += flt(cl[i].amount);
+			net_total_import += flt(cl[i].amount) / flt(doc.conversion_rate);
+		}
+		//update stock uom
+		cur_frm.cscript.update_stock_qty(doc, tname, cl[i].name);
+	}
+	doc.net_total = flt(net_total) ;
+	doc.net_total_import = flt(net_total_import) ;
+	refresh_field('net_total');
+	refresh_field('net_total_import');
+	
+	cur_frm.cscript.val_cal_charges(doc, cdt, cdn, tname, fname, other_fname);
 }
 
 
 //======== Function was broken away from cur_frm.cscript.calc_amount as PV has fieldname 'rate' instead of 'purchase_rate'===========
 cur_frm.cscript.val_cal_charges = function(doc, cdt, cdn, tname, fname, other_fname){
 
-  doc = locals[doc.doctype][doc.name]
-  if(flt(doc.net_total) > 0) {
-    var cl = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
-    for(var i = 0; i<cl.length; i++){
-      cl[i].total_tax_amount = 0;
-      cl[i].total_amount = 0;
-      cl[i].tax_amount = 0;                    // this is done to calculate other charges
-      cl[i].total = 0;
-      cl[i].item_wise_tax_detail = "";
-      if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
-        alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
-        validated = false;
-      }
-    }
-    cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
-  }
-  cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
+	doc = locals[doc.doctype][doc.name]
+	if(flt(doc.net_total) > 0) {
+		var cl = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
+		for(var i = 0; i<cl.length; i++){
+			cl[i].total_tax_amount = 0;
+			cl[i].total_amount = 0;
+			cl[i].tax_amount = 0;										// this is done to calculate other charges
+			cl[i].total = 0;
+			cl[i].item_wise_tax_detail = "";
+			if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
+				alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
+				validated = false;
+			}
+		}
+		cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
+	}
+	cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
 
-  refresh_many(['net_total', 'grand_total', 'rounded_total', 'grand_total_import', 'rounded_total_import', 'in_words', 'in_words_import', 'purchase_tax_details', 'total_tax', 'other_charges_added', 'other_charges_deducted', 'net_total_import', 'other_charges_added_import', 'other_charges_deducted_import']);
+	refresh_many(['net_total', 'grand_total', 'rounded_total', 'grand_total_import', 'rounded_total_import', 'in_words', 'in_words_import', 'purchase_tax_details', 'total_tax', 'other_charges_added', 'other_charges_deducted', 'net_total_import', 'other_charges_added_import', 'other_charges_deducted_import']);
 
 }
 
 
 // ******************************* OTHER CHARGES *************************************
 cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname) {
-  doc = locals[doc.doctype][doc.name];
-  // make display area
-  // ------------------
+	doc = locals[doc.doctype][doc.name];
+	// make display area
+	// ------------------
 
-  
-  cur_frm.fields_dict['Tax Calculation'].disp_area.innerHTML = '<b style="padding: 8px 0px;">Calculation Details for Other Charges and Landed cost:</b>';
-  var cl = getchildren(tname, doc.name, fname);
-  var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
-  // make display table
-  // ------------------
-  var otc = make_table(cur_frm.fields_dict['Tax Calculation'].disp_area, cl.length + 1, tax.length + 1, '90%',[],{border:'1px solid #AAA',padding:'2px'});
-  $y(otc,{marginTop:'8px'});
-  
-  var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
-  
-  
-  for(var i=0;i<cl.length;i++) {
-    var item_tax = 0;
-    if(doc.doctype != 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].purchase_rate));
-    else if(doc.doctype == 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].rate));
+	
+	cur_frm.fields_dict['Tax Calculation'].disp_area.innerHTML = '<b style="padding: 8px 0px;">Calculation Details for Other Charges and Landed cost:</b>';
+	var cl = getchildren(tname, doc.name, fname);
+	var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
+	// make display table
+	// ------------------
+	var otc = make_table(cur_frm.fields_dict['Tax Calculation'].disp_area, cl.length + 1, tax.length + 1, '90%',[],{border:'1px solid #AAA',padding:'2px'});
+	$y(otc,{marginTop:'8px'});
+	
+	var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
+	
+	
+	for(var i=0;i<cl.length;i++) {
+		var item_tax = 0;
+		if(doc.doctype != 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].purchase_rate));
+		else if(doc.doctype == 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].rate));
 
-    var prev_total = flt(cl[i].amount);
-    if(cl[i].item_tax_rate)
-      var check_tax = eval('var a='+cl[i].item_tax_rate+';a');        //to get in dictionary
-    
-    // Add Item Code in new Row 
-    //--------------------------
-    $td(otc,i+1,0).innerHTML = cl[i].item_code;
-    
-    var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
-    var total = net_total;
-    for(var t=0;t<tax.length;t++){
+		var prev_total = flt(cl[i].amount);
+		if(cl[i].item_tax_rate) {
+			try {
+				var check_tax = JSON.parse(cl[i].item_tax_rate);				//to get in dictionary
+			} catch(exception) {
+				var check_tax = eval('var a='+cl[i].item_tax_rate+';a');        //to get in dictionary				 
+			}
+		}
+		
+		// Add Item Code in new Row 
+		//--------------------------
+		$td(otc,i+1,0).innerHTML = cl[i].item_code;
+		
+		var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
+		var total = net_total;
+		for(var t=0;t<tax.length;t++){
  
-      var account = tax[t].account_head;
-      $td(otc,0,t+1).innerHTML = account?account:'';
-      //Check For Rate
-      if(cl[i].item_tax_rate && check_tax[account]!=null)  {rate = flt(check_tax[account]);}
-      else               // if particular item doesn't have particular rate it will take other charges rate
-        rate = flt(tax[t].rate);
-      //Check For Rate and get tax amount
-      var tax_amount = cur_frm.cscript.check_charge_type_and_get_tax_amount(doc,tax,t, cl[i], rate);
-      
-      //enter item_wise_tax_detail i.e. tax rate on each item
-      
-      item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail( doc, rate, cl, i, tax, t);
-      
-      
-      if(tax[t].add_deduct_tax == 'Add'){
-        // this is calculation part for all types
-        if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
-        tax[t].total_amount = flt(tax_amount.toFixed(2));     //stores actual tax amount in virtual field
-        tax[t].total_tax_amount = flt(prev_total.toFixed(2));      //stores total amount in virtual field
-        tax[t].tax_amount += flt(tax_amount.toFixed(2));       
-        var total_amount = flt(tax[t].tax_amount);
-        total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
-        if(tax[t].category != "For Valuation"){
-          set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)+flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
-          prev_total += flt(tax[t].total_amount);
-          total += flt(tax[t].tax_amount);  // for adding total to previous amount       
-        }
-        else{
-          set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
-          prev_total = prev_total;
-        }
-        //prev_total += flt(tax[t].total_amount);   // for previous row total
+			var account = tax[t].account_head;
+			$td(otc,0,t+1).innerHTML = account?account:'';
+			//Check For Rate
+			if(cl[i].item_tax_rate && check_tax[account]!=null)	{rate = flt(check_tax[account]);}
+			else							 // if particular item doesn't have particular rate it will take other charges rate
+				rate = flt(tax[t].rate);
 
-        if(tax[t].charge_type == 'Actual')
-          $td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
-        else
-          $td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
+			//Check For Rate and get tax amount
+			var tax_amount = cur_frm.cscript.check_charge_type_and_get_tax_amount(doc,tax,t, cl[i], rate);
+			
+			//enter item_wise_tax_detail i.e. tax rate on each item
+			
+			item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail( doc, rate, cl, i, tax, t);
+			
+			
+			if(tax[t].add_deduct_tax == 'Add'){
+				// this is calculation part for all types
+				if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
+				tax[t].total_amount = flt(tax_amount.toFixed(2));		 //stores actual tax amount in virtual field
+				tax[t].total_tax_amount = flt(prev_total.toFixed(2));			//stores total amount in virtual field
+				tax[t].tax_amount += flt(tax_amount.toFixed(2));			 
+				var total_amount = flt(tax[t].tax_amount);
+				total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
+				if(tax[t].category != "For Valuation"){
+					set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)+flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
+					prev_total += flt(tax[t].total_amount);
+					total += flt(tax[t].tax_amount);	// for adding total to previous amount			 
+				}
+				else{
+					set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
+					prev_total = prev_total;
+				}
+				//prev_total += flt(tax[t].total_amount);	 // for previous row total
 
-        if (tax[t].category != "For Total"){
-          item_tax += tax[t].total_amount;
-        }
-      }
-      else if(tax[t].add_deduct_tax == 'Deduct'){
-        // this is calculation part for all types
-        if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
-        tax[t].total_amount = flt(tax_amount.toFixed(2));     //stores actual tax amount in virtual field
-        tax[t].total_tax_amount = flt(prev_total.toFixed(2));      //stores total amount in virtual field
-        tax[t].tax_amount += flt(tax_amount.toFixed(2));
-        var total_amount = flt(tax[t].tax_amount);
-        total_tax_amount = flt(tax[t].total_tax_amount) - flt(total_amount);
-        if(tax[t].category != "For Valuation"){
-          set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)-flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
-          prev_total -= flt(tax[t].total_amount); 
-          total -= flt(tax[t].tax_amount);  // for adding total to previous amount       
-        }
-        else{
-          set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
-          prev_total = prev_total;
-        }
-        //prev_total += flt(tax[t].total_amount);   // for previous row total
+				if(tax[t].charge_type == 'Actual')
+					$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
+				else
+					$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
 
-        if(tax[t].charge_type == 'Actual')
-          $td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
-        else
-          $td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
+				if (tax[t].category != "For Total"){
+					item_tax += tax[t].total_amount;
+				}
+			}
+			else if(tax[t].add_deduct_tax == 'Deduct'){
+				// this is calculation part for all types
+				if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
+				tax[t].total_amount = flt(tax_amount.toFixed(2));		 //stores actual tax amount in virtual field
+				tax[t].total_tax_amount = flt(prev_total.toFixed(2));			//stores total amount in virtual field
+				tax[t].tax_amount += flt(tax_amount.toFixed(2));
+				var total_amount = flt(tax[t].tax_amount);
+				total_tax_amount = flt(tax[t].total_tax_amount) - flt(total_amount);
+				if(tax[t].category != "For Valuation"){
+					set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)-flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
+					prev_total -= flt(tax[t].total_amount); 
+					total -= flt(tax[t].tax_amount);	// for adding total to previous amount			 
+				}
+				else{
+					set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
+					prev_total = prev_total;
+				}
+				//prev_total += flt(tax[t].total_amount);	 // for previous row total
 
-        if (tax[t].category != "For Total"){
-          item_tax -= tax[t].total_amount;
-        }
-      }      
-      
-      
-    }
-    set_multiple(tname, cl[i].name, {'item_tax_amount': item_tax }, fname);
-  }
+				if(tax[t].charge_type == 'Actual')
+					$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
+				else
+					$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
+
+				if (tax[t].category != "For Total"){
+					item_tax -= tax[t].total_amount;
+				}
+			}			
+			
+			
+		}
+		set_multiple(tname, cl[i].name, {'item_tax_amount': item_tax }, fname);
+	}
 }
 
 
@@ -397,45 +441,45 @@
 
 // ******* Calculation of total amounts of document (item amount + other charges)****************
 cur_frm.cscript.calc_doc_values = function(doc, cdt, cdn, tname, fname, other_fname) {
-  doc = locals[doc.doctype][doc.name];
-  var net_total = 0; var total_tax = 0; var other_charges_added = 0; var other_charges_deducted = 0;
-  var cl = getchildren(tname, doc.name, fname);
-  for(var i = 0; i<cl.length; i++){
-    net_total += flt(cl[i].amount);
-  }
-  var d = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
-  for(var j = 0; j<d.length; j++){
-    if(d[j].category != 'For Valuation'){
-      
-      if(d[j].add_deduct_tax == 'Add'){
-        other_charges_added += flt(d[j].tax_amount);
-        total_tax += flt(d[j].tax_amount);
-      }
-      if(d[j].add_deduct_tax == 'Deduct'){
-        other_charges_deducted += flt(d[j].tax_amount);
-        total_tax -= flt(d[j].tax_amount);
-      }
-    }
-  }
-  doc.net_total = flt(net_total);
-  doc.total_tax = flt(total_tax);
+	doc = locals[doc.doctype][doc.name];
+	var net_total = 0; var total_tax = 0; var other_charges_added = 0; var other_charges_deducted = 0;
+	var cl = getchildren(tname, doc.name, fname);
+	for(var i = 0; i<cl.length; i++){
+		net_total += flt(cl[i].amount);
+	}
+	var d = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
+	for(var j = 0; j<d.length; j++){
+		if(d[j].category != 'For Valuation'){
+			
+			if(d[j].add_deduct_tax == 'Add'){
+				other_charges_added += flt(d[j].tax_amount);
+				total_tax += flt(d[j].tax_amount);
+			}
+			if(d[j].add_deduct_tax == 'Deduct'){
+				other_charges_deducted += flt(d[j].tax_amount);
+				total_tax -= flt(d[j].tax_amount);
+			}
+		}
+	}
+	doc.net_total = flt(net_total);
+	doc.total_tax = flt(total_tax);
 
-  doc.other_charges_added = flt(other_charges_added);
-  doc.other_charges_deducted = flt(other_charges_deducted);
-  doc.grand_total = flt(flt(net_total) + flt(other_charges_added) - flt(other_charges_deducted));
-  doc.rounded_total = Math.round(doc.grand_total);
-  doc.net_total_import = flt(flt(net_total) / flt(doc.conversion_rate));
-  doc.other_charges_added_import = flt(flt(other_charges_added) / flt(doc.conversion_rate));
-  doc.other_charges_deducted_import = flt(flt(other_charges_deducted) / flt(doc.conversion_rate));
-  doc.grand_total_import = flt(flt(doc.grand_total) / flt(doc.conversion_rate));
-  doc.rounded_total_import = Math.round(doc.grand_total_import);
+	doc.other_charges_added = flt(other_charges_added);
+	doc.other_charges_deducted = flt(other_charges_deducted);
+	doc.grand_total = flt(flt(net_total) + flt(other_charges_added) - flt(other_charges_deducted));
+	doc.rounded_total = Math.round(doc.grand_total);
+	doc.net_total_import = flt(flt(net_total) / flt(doc.conversion_rate));
+	doc.other_charges_added_import = flt(flt(other_charges_added) / flt(doc.conversion_rate));
+	doc.other_charges_deducted_import = flt(flt(other_charges_deducted) / flt(doc.conversion_rate));
+	doc.grand_total_import = flt(flt(doc.grand_total) / flt(doc.conversion_rate));
+	doc.rounded_total_import = Math.round(doc.grand_total_import);
 
-  refresh_many(['net_total','total_taxes','grand_total']);
+	refresh_many(['net_total','total_taxes','grand_total']);
 
 
-  if(doc.doctype == 'Payable Voucher'){
-    calculate_outstanding(doc);
-  }
+	if(doc.doctype == 'Payable Voucher'){
+		calculate_outstanding(doc);
+	}
 }
 
 var calculate_outstanding = function(doc) {
@@ -453,41 +497,41 @@
 
 
 cur_frm.cscript.check_charge_type_and_get_tax_amount = function(doc, tax, t, cl, rate, print_amt) {
-  doc = locals[doc.doctype][doc.name];
+	doc = locals[doc.doctype][doc.name];
 
-  var tax_amount = 0;
-  if(tax[t].charge_type == 'Actual') {
-    var value = flt(tax[t].rate) / flt(doc.net_total);   // this give the ratio in which all items are divided           
-    return tax_amount = flt(value) * flt(cl.amount);
-   }   
-  else if(tax[t].charge_type == 'On Net Total') {
-    return tax_amount = (flt(rate) * flt(cl.amount) / 100);
-  }
-  else if(tax[t].charge_type == 'On Previous Row Amount'){
-    var row_no = (tax[t].row_id).toString();
-    var row = (row_no).split("+");      // splits the values and stores in an array
-    for(var r = 0;r<row.length;r++){
-      var id = cint(row[r].replace(/^\s+|\s+$/g,""));
-      tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
-    }
-    var row_id = row_no.indexOf("/");
-    if(row_id != -1) {
-      rate = '';
-      var row = (row_no).split("/");      // splits the values and stores in an array
-      if(row.length>2) alert("You cannot enter more than 2 nos. for division");
-      var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
-      var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
-      tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
-    }
-    return tax_amount
-  }
-  else if(tax[t].charge_type == 'On Previous Row Total') {
-    var row = cint(tax[t].row_id);
-    if(tax[row-1].add_deduct_tax == 'Add'){
-      return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
-     }
-    else if(tax[row-1].add_deduct_tax == 'Deduct'){
-      return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)-flt(tax[row-1].total_amount)) / 100;
-     }
-  }
+	var tax_amount = 0;
+	if(tax[t].charge_type == 'Actual') {
+		var value = flt(tax[t].rate) / flt(doc.net_total);	 // this give the ratio in which all items are divided					 
+		return tax_amount = flt(value) * flt(cl.amount);
+	 }	 
+	else if(tax[t].charge_type == 'On Net Total') {
+		return tax_amount = (flt(rate) * flt(cl.amount) / 100);
+	}
+	else if(tax[t].charge_type == 'On Previous Row Amount'){
+		var row_no = (tax[t].row_id).toString();
+		var row = (row_no).split("+");			// splits the values and stores in an array
+		for(var r = 0;r<row.length;r++){
+			var id = cint(row[r].replace(/^\s+|\s+$/g,""));
+			tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
+		}
+		var row_id = row_no.indexOf("/");
+		if(row_id != -1) {
+			rate = '';
+			var row = (row_no).split("/");			// splits the values and stores in an array
+			if(row.length>2) alert("You cannot enter more than 2 nos. for division");
+			var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
+			var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
+			tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
+		}
+		return tax_amount
+	}
+	else if(tax[t].charge_type == 'On Previous Row Total') {
+		var row = cint(tax[t].row_id);
+		if(tax[row-1].add_deduct_tax == 'Add'){
+			return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
+		 }
+		else if(tax[row-1].add_deduct_tax == 'Deduct'){
+			return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)-flt(tax[row-1].total_amount)) / 100;
+		 }
+	}
 }
diff --git a/erpnext/buying/doctype/purchase_common/purchase_common.py b/erpnext/buying/doctype/purchase_common/purchase_common.py
index 5bade92..4a49373 100644
--- a/erpnext/buying/doctype/purchase_common/purchase_common.py
+++ b/erpnext/buying/doctype/purchase_common/purchase_common.py
@@ -96,9 +96,9 @@
 		if r: obj.doc.terms = r[0][0]
 
 	# Get Item Details
-	def get_item_details( self, obj, arg =''):
-
-		arg = eval(arg)
+	def get_item_details(self, obj, arg =''):
+		import json
+		arg = json.loads(arg)
 		item = sql("select item_name,item_group, brand, description, min_order_qty, stock_uom, default_warehouse,lead_time_days, last_purchase_rate from `tabItem` where name = %s and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life >	now())", (arg['item_code']), as_dict = 1)
 		tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg['item_code'])
 		t = {}
@@ -119,7 +119,7 @@
 			'stock_uom'					: item and item[0]['stock_uom'] or '',
 			'conversion_factor'	: '1',
 			'warehouse'					: wh,
-			'item_tax_rate'			: str(t),
+			'item_tax_rate'			: json.dumps(t),
 			'batch_no'					 : '',
 			'discount_rate'			: 0		
 		}
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.js b/erpnext/buying/doctype/purchase_order/purchase_order.js
index 05fe049..8435c02 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.js
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.js
@@ -8,86 +8,89 @@
 //========================== On Load =================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
 
-  if(!doc.fiscal_year && doc.__islocal){ //set_default_values(doc);
-    doc.fiscal_year = sys_defaults.fiscal_year;
-  }
-  if(!doc.conversion_rate) doc.conversion_rate = 1;
-  if(!doc.currency) doc.currency = sys_defaults.currency;
-  if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-  if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
-  
-  if(doc.__islocal){
-    hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
-  }
+	if(!doc.fiscal_year && doc.__islocal){ //set_default_values(doc);
+		doc.fiscal_year = sys_defaults.fiscal_year;
+	}
+	if(!doc.conversion_rate) doc.conversion_rate = 1;
+	if(!doc.currency) doc.currency = sys_defaults.currency;
+	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
+	if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
+	
+	if(doc.__islocal){
+		hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
+	}
+
+	// defined in purchase_common.js
+	//cur_frm.cscript.update_item_details(doc, cdt, cdn);		
 }
 
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
-  if(doc.__islocal){ 
-    cur_frm.cscript.get_default_schedule_date(doc);
-  }	
+	if(doc.__islocal){ 
+		cur_frm.cscript.get_default_schedule_date(doc);
+	}	
 }
 
 // ================================== Refresh ==========================================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) { 
 
-  // Show buttons
-  // ---------------------------------
-  cur_frm.clear_custom_buttons();
-  if(doc.docstatus == 1 && doc.status != 'Stopped'){
-    var ch = getchildren('PO Detail',doc.name,'po_details');
-    var allow_billing = 0; var allow_receipt = 0;
-    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+	// Show buttons
+	// ---------------------------------
+	cur_frm.clear_custom_buttons();
+	if(doc.docstatus == 1 && doc.status != 'Stopped'){
+		var ch = getchildren('PO Detail',doc.name,'po_details');
+		var allow_billing = 0; var allow_receipt = 0;
+		cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
 
-    for(var i in ch){
-      if(ch[i].qty > ch[i].received_qty) allow_receipt = 1; 
-      if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
-    }
-    if(allow_receipt)
-      cur_frm.add_custom_button('Make Purchase Receipt', cur_frm.cscript['Make Purchase Receipt']);
-	    
+		for(var i in ch){
+			if(ch[i].qty > ch[i].received_qty) allow_receipt = 1; 
+			if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
+		}
+		if(allow_receipt)
+			cur_frm.add_custom_button('Make Purchase Receipt', cur_frm.cscript['Make Purchase Receipt']);
+			
 	if(allow_billing)
-      cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Purchase Invoice']);
+			cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Purchase Invoice']);
 
-    if(allow_billing || allow_receipt)
-      cur_frm.add_custom_button('Stop', cur_frm.cscript['Stop Purchase Order']);
-  }
-    
-  if(doc.docstatus == 1 && doc.status == 'Stopped')
-    cur_frm.add_custom_button('Unstop Purchase Order', cur_frm.cscript['Unstop Purchase Order']);
+		if(allow_billing || allow_receipt)
+			cur_frm.add_custom_button('Stop', cur_frm.cscript['Stop Purchase Order']);
+	}
+		
+	if(doc.docstatus == 1 && doc.status == 'Stopped')
+		cur_frm.add_custom_button('Unstop Purchase Order', cur_frm.cscript['Unstop Purchase Order']);
 
-  if(doc.docstatus == 1) unhide_field(['Repair Purchase Order']);
-  else hide_field(['Repair Purchase Order']);
+	if(doc.docstatus == 1) unhide_field(['Repair Purchase Order']);
+	else hide_field(['Repair Purchase Order']);
 }
 
 
 
 //Supplier
 cur_frm.cscript.supplier = function(doc,dt,dn) {
-  if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
-  if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
+	if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
+	if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
 }
 
-cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {    
-  if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
+	if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 
 cur_frm.fields_dict.supplier_address.on_new = function(dn) {
-  locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 
@@ -96,154 +99,154 @@
 
 //================ create new contact ============================================================================
 cur_frm.cscript.new_contact = function(){
-  tn = createLocal('Contact');
-  locals['Contact'][tn].is_supplier = 1;
-  if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
-  loaddoc('Contact', tn);
+	tn = createLocal('Contact');
+	locals['Contact'][tn].is_supplier = 1;
+	if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
+	loaddoc('Contact', tn);
 }
 
 //======================= transaction date =============================
 cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
-  if(doc.__islocal){ 
-    cur_frm.cscript.get_default_schedule_date(doc);
-  }
+	if(doc.__islocal){ 
+		cur_frm.cscript.get_default_schedule_date(doc);
+	}
 }
 
 
 // ---------------------- Get project name --------------------------
 cur_frm.fields_dict['po_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
 }
 
 //==================== Indent No Get Query =======================================================
 //===== Only those Indents status != 'Completed' and docstatus = 1 i.e. submitted=================
 cur_frm.fields_dict['indent_no'].get_query = function(doc) {
-  return 'SELECT DISTINCT `tabIndent`.`name` FROM `tabIndent` WHERE `tabIndent`.company = "' + doc.company + '" and `tabIndent`.`docstatus` = 1 and `tabIndent`.`status` != "Stopped" and ifnull(`tabIndent`.`per_ordered`,0) < 100 and `tabIndent`.%(key)s LIKE "%s" ORDER BY `tabIndent`.`name` DESC LIMIT 50';
+	return 'SELECT DISTINCT `tabIndent`.`name` FROM `tabIndent` WHERE `tabIndent`.company = "' + doc.company + '" and `tabIndent`.`docstatus` = 1 and `tabIndent`.`status` != "Stopped" and ifnull(`tabIndent`.`per_ordered`,0) < 100 and `tabIndent`.%(key)s LIKE "%s" ORDER BY `tabIndent`.`name` DESC LIMIT 50';
 }
 
 /*
 //*********** get approved supplier quotation ********************
 cur_frm.fields_dict['supplier_qtn'].get_query = function(doc) {
-  var cond='';
-  if(doc.supplier) cond = 'ifnull(`tabSupplier Quotation`.supplier, "") = "'+doc.supplier+'" and';
-  
-  return repl('SELECT DISTINCT `tabSupplier Quotation`.`name` FROM `tabSupplier Quotation` WHERE `tabSupplier Quotation`.company = "%(company)s" and`tabSupplier Quotation`.`docstatus` = 1 and `tabSupplier Quotation`.`approval_status` = "Approved" and %(cond)s `tabSupplier Quotation`.%(key)s LIKE "%s" ORDER BY `tabSupplier Quotation`.`name` DESC LIMIT 50', {company:doc.company,cond:cond});
+	var cond='';
+	if(doc.supplier) cond = 'ifnull(`tabSupplier Quotation`.supplier, "") = "'+doc.supplier+'" and';
+	
+	return repl('SELECT DISTINCT `tabSupplier Quotation`.`name` FROM `tabSupplier Quotation` WHERE `tabSupplier Quotation`.company = "%(company)s" and`tabSupplier Quotation`.`docstatus` = 1 and `tabSupplier Quotation`.`approval_status` = "Approved" and %(cond)s `tabSupplier Quotation`.%(key)s LIKE "%s" ORDER BY `tabSupplier Quotation`.`name` DESC LIMIT 50', {company:doc.company,cond:cond});
 }
 */
 
 
 //========================= Get Last Purhase Rate =====================================
 cur_frm.cscript['Get Last Purchase Rate'] = function(doc, cdt, cdn){
-  $c_obj(make_doclist(doc.doctype, doc.name), 'get_last_purchase_rate', '', 
-      function(r, rt) { 
-        refresh_field(cur_frm.cscript.fname);
-        var doc = locals[cdt][cdn];
-        cur_frm.cscript.calc_amount( doc, 2);
-      }
-  );
+	$c_obj(make_doclist(doc.doctype, doc.name), 'get_last_purchase_rate', '', 
+			function(r, rt) { 
+				refresh_field(cur_frm.cscript.fname);
+				var doc = locals[cdt][cdn];
+				cur_frm.cscript.calc_amount( doc, 2);
+			}
+	);
 
 }
 
 //========================= Make Purchase Receipt =======================================================
 cur_frm.cscript['Make Purchase Receipt'] = function() {
-  n = createLocal('Purchase Receipt');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Purchase Receipt'][n]]),
-    'from_doctype': cur_frm.doc.doctype,
-    'to_doctype':'Purchase Receipt',
-    'from_docname':cur_frm.doc.name,
-    'from_to_list':"[['Purchase Order','Purchase Receipt'],['PO Detail','Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
-    }, function(r,rt) {
-       loaddoc('Purchase Receipt', n);
-    }
-  );
+	n = createLocal('Purchase Receipt');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Purchase Receipt'][n]]),
+		'from_doctype': cur_frm.doc.doctype,
+		'to_doctype':'Purchase Receipt',
+		'from_docname':cur_frm.doc.name,
+		'from_to_list':"[['Purchase Order','Purchase Receipt'],['PO Detail','Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
+		}, function(r,rt) {
+			 loaddoc('Purchase Receipt', n);
+		}
+	);
 }
 
 //========================== Make Purchase Invoice =====================================================
 cur_frm.cscript['Make Purchase Invoice'] = function() {
-  n = createLocal('Payable Voucher');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Payable Voucher'][n]]),
-    'from_doctype':cur_frm.doc.doctype,
-    'to_doctype':'Payable Voucher',
-    'from_docname': cur_frm.doc.name,
-    'from_to_list':"[['Purchase Order','Payable Voucher'],['PO Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
-    }, function(r,rt) {
-       loaddoc('Payable Voucher', n);
-    }
-  );
+	n = createLocal('Payable Voucher');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Payable Voucher'][n]]),
+		'from_doctype':cur_frm.doc.doctype,
+		'to_doctype':'Payable Voucher',
+		'from_docname': cur_frm.doc.name,
+		'from_to_list':"[['Purchase Order','Payable Voucher'],['PO Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
+		}, function(r,rt) {
+			 loaddoc('Payable Voucher', n);
+		}
+	);
 }
 
 
 // Stop PURCHASE ORDER
 // ==================================================================================================
 cur_frm.cscript['Stop Purchase Order'] = function() {
-  var doc = cur_frm.doc;
-  var check = confirm("Do you really want to STOP " + doc.name);
+	var doc = cur_frm.doc;
+	var check = confirm("Do you really want to STOP " + doc.name);
 
-  if (check) {
-    $c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-    });	
-  }
+	if (check) {
+		$c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+		});	
+	}
 }
 
 // Unstop PURCHASE ORDER
 // ==================================================================================================
 cur_frm.cscript['Unstop Purchase Order'] = function() {
-  var doc = cur_frm.doc;
-  var check = confirm("Do you really want to UNSTOP " + doc.name);
+	var doc = cur_frm.doc;
+	var check = confirm("Do you really want to UNSTOP " + doc.name);
 
-  if (check) {
-    $c('runserverobj', args={'method':'update_status', 'arg': 'Submitted', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-    });	
-  }
+	if (check) {
+		$c('runserverobj', args={'method':'update_status', 'arg': 'Submitted', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+		});	
+	}
 }
 
-// ***************** Get Print Heading  *****************
+// ***************** Get Print Heading	*****************
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
 }
 //****************** For print sales order no and date*************************
 cur_frm.pformat.indent_no = function(doc, cdt, cdn){
-  //function to make row of table
-  
-  var make_row = function(title,val1, val2, bold){
-    var bstart = '<b>'; var bend = '</b>';
+	//function to make row of table
+	
+	var make_row = function(title,val1, val2, bold){
+		var bstart = '<b>'; var bend = '</b>';
 
-    return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
-     +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
-     +'</tr>'
-  }
+		return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+		 +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+		 +'</tr>'
+	}
 
-  out ='';
-  
-  var cl = getchildren('PO Detail',doc.name,'po_details');
+	out ='';
+	
+	var cl = getchildren('PO Detail',doc.name,'po_details');
 
-  // outer table  
-  var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
-  
-  // main table
-  out +='<table class="noborder" style="width:100%">';
+	// outer table	
+	var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
+	
+	// main table
+	out +='<table class="noborder" style="width:100%">';
 
-  // add rows
-  if(cl.length){
-    prevdoc_list = new Array();
-    for(var i=0;i<cl.length;i++){
-      if(cl[i].prevdoc_doctype == 'Indent' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
-        prevdoc_list.push(cl[i].prevdoc_docname);
-        if(prevdoc_list.length ==1)
-          out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-        else
-          out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-      }
-    }
-  }
+	// add rows
+	if(cl.length){
+		prevdoc_list = new Array();
+		for(var i=0;i<cl.length;i++){
+			if(cl[i].prevdoc_doctype == 'Indent' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
+				prevdoc_list.push(cl[i].prevdoc_docname);
+				if(prevdoc_list.length ==1)
+					out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+				else
+					out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+			}
+		}
+	}
 
-  out +='</table></td></tr></table></div>';
+	out +='</table></td></tr></table></div>';
 
-  return out;
+	return out;
 }
 
 $import(Notification Control)
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index 752e348..d4c308d 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -19,325 +19,340 @@
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
-  def __init__(self, doc, doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
-    self.defaults = get_defaults()
-    self.tname = 'PO Detail'
-    self.fname = 'po_details'
+	def __init__(self, doc, doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		self.defaults = get_defaults()
+		self.tname = 'PO Detail'
+		self.fname = 'po_details'
 
-  # Autoname
-  # ---------
-  def autoname(self):
-    self.doc.name = make_autoname(self.doc.naming_series+'.#####')
+	# Autoname
+	# ---------
+	def autoname(self):
+		self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
-  def get_default_schedule_date(self):
-    get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
-    
-  def validate_fiscal_year(self):
-    get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date')
+	def get_default_schedule_date(self):
+		get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
+		
+	def validate_fiscal_year(self):
+		get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date')
 
 
-  # Get Item Details
-  def get_item_details(self, arg =''):
-    return get_obj(dt='Purchase Common').get_item_details(self,arg)
-
-  # Get UOM Details
-  def get_uom_details(self, arg = ''):
-    return get_obj(dt='Purchase Common').get_uom_details(arg)
-
-  # get available qty at warehouse
-  def get_bin_details(self, arg = ''):
-    return get_obj(dt='Purchase Common').get_bin_details(arg)
-
-  # Pull Indent
-  def get_indent_details(self):
-    #self.validate_prev_docname() 
-    if self.doc.indent_no:
-      get_obj('DocType Mapper','Indent-Purchase Order').dt_map('Indent','Purchase Order',self.doc.indent_no, self.doc, self.doclist, "[['Indent','Purchase Order'],['Indent Detail', 'PO Detail']]")
-      for d in getlist(self.doclist, 'po_details'):			
-        if d.item_code:
-          item = sql("select last_purchase_rate from tabItem where name = '%s'" %(d.item_code), as_dict=1)
-          d.purchase_rate = item and flt(item[0]['last_purchase_rate']) or 0
-          d.import_rate = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(self.doc.fields.has_key('conversion_rate') and flt(self.doc.conversion_rate) or 1)
-    if self.doc.supplier_qtn:
-      get_obj('DocType Mapper','Supplier Quotation-Purchase Order').dt_map('Supplier Quotation','Purchase Order',self.doc.supplier_qtn, self.doc, self.doclist, "[['Supplier Quotation','Purchase Order'],['Supplier Quotation Detail', 'PO Detail']]")
-  
-  # GET TERMS & CONDITIONS
-  # =====================================================================================
-  def get_tc_details(self):
-    return get_obj('Purchase Common').get_tc_details(self)
-
-  # validate if indent has been pulled twice
-  def validate_prev_docname(self):
-    for d in getlist(self.doclist, 'po_details'): 
-      if d.prevdoc_docname and self.doc.indent_no == d.prevdoc_docname:
-        msgprint(cstr(self.doc.indent_no) + " indent details have already been pulled. ")
-        raise Exception
-
-  # get last purchase rate
-  def get_last_purchase_rate(self):
-    get_obj('Purchase Common').get_last_purchase_rate(self)
-    
-  # validation
-  #-------------------------------------------------------------------------------------------------------------
-  def validate_doc(self,pc_obj):
-    # Please Check Supplier Quotation - Purchase ORder Transaction , it has to be discussed
-    if self.doc.supp_quo_no:
-      pc_obj.validate_doc(obj = self, prevdoc_doctype = 'Supplier Quotation', prevdoc_docname = cstr(self.doc.supp_quo_no))
-    else:
-      # Validate values with reference document
-      pc_obj.validate_reference_value(obj = self)
-
-  # Check for Stopped status 
-  def check_for_stopped_status(self, pc_obj):
-    check_list =[]
-    for d in getlist(self.doclist, 'po_details'):
-      if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
-        check_list.append(d.prevdoc_docname)
-        pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
-
-    
-  # Validate
-  def validate(self):
-    self.validate_fiscal_year()
-    # Step 1:=> set status as "Draft"
-    set(self.doc, 'status', 'Draft')
-    
-    # Step 2:=> get Purchase Common Obj
-    pc_obj = get_obj(dt='Purchase Common')
-    
-    # Step 3:=> validate mandatory
-    pc_obj.validate_mandatory(self)
-
-    # Step 4:=> validate for items
-    pc_obj.validate_for_items(self)
-
-    # Step 5:=> validate conversion rate
-    pc_obj.validate_conversion_rate(self)
-    
-    # Get po date
-    pc_obj.get_prevdoc_date(self)
-    
-    # validate_doc
-    self.validate_doc(pc_obj)
-    
-    # Check for stopped status
-    self.check_for_stopped_status(pc_obj)
-    
-      
-     # get total in words
-    dcc = TransactionBase().get_company_currency(self.doc.company)
-    self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
-    self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
-  
-  # update bin
-  # ----------
-  def update_bin(self, is_submit, is_stopped = 0):
-    pc_obj = get_obj('Purchase Common')
-    for d in getlist(self.doclist, 'po_details'):
-      #1. Check if is_stock_item == 'Yes'
-      if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
-        
-        ind_qty, po_qty = 0, flt(d.qty) * flt(d.conversion_factor)
-        if is_stopped:
-          po_qty = flt(d.qty) > flt(d.received_qty) and flt( flt(flt(d.qty) - flt(d.received_qty)) * flt(d.conversion_factor))or 0 
-        
-        # No updates in Indent on Stop / Unstop
-        if cstr(d.prevdoc_doctype) == 'Indent' and not is_stopped:
-          # get qty and pending_qty of prevdoc 
-          curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'Indent Detail', 'Indent - Purchase Order', self.doc.name)
-          max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
-          
-          if flt(qty) + flt(po_qty) > flt(max_qty):
-            curr_qty = flt(max_qty) - flt(qty)
-            # special case as there is no restriction for Indent - Purchase Order 
-            curr_qty = (curr_qty > 0) and curr_qty or 0
-          else:
-            curr_qty = flt(po_qty)
-          
-          ind_qty = -flt(curr_qty)
-
-        #==> Update Bin's Indent Qty by +- ind_qty and Ordered Qty by +- qty
-        get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(po_qty), (is_submit and 1 or -1) * flt(ind_qty), 0, d.item_code, self.doc.transaction_date)
-
-  def check_modified_date(self):
-    mod_db = sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
-    date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
-    
-    if date_diff and date_diff[0][0]:
-      msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
-      raise Exception
-
-  # On Close
-  #-------------------------------------------------------------------------------------------------
-  def update_status(self, status):
-    self.check_modified_date()
-    # step 1:=> Set Status
-    set(self.doc,'status',cstr(status))
-
-    # step 2:=> Update Bin
-    self.update_bin(is_submit = (status == 'Submitted') and 1 or 0, is_stopped = 1)
-
-    # step 3:=> Acknowledge user
-    msgprint(self.doc.doctype + ": " + self.doc.name + " has been %s." % ((status == 'Submitted') and 'Unstopped' or cstr(status)))
+	# Get Item Details
+	def get_item_details(self, arg =''):
+		if arg:
+			return get_obj(dt='Purchase Common').get_item_details(self,arg)
+		else:
+			obj = get_obj('Purchase Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					temp = {
+						'item_code': doc.fields.get('item_code'),
+						'warehouse': doc.fields.get('warehouse')
+					}
+					ret = obj.get_item_details(self, json.dumps(temp))
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]
 
 
-  # On Submit
-  def on_submit(self):
-    pc_obj = get_obj(dt ='Purchase Common')
-    
-    # Step 1 :=> Update Previous Doc i.e. update pending_qty and Status accordingly
-    pc_obj.update_prevdoc_detail(self, is_submit = 1)
 
-    # Step 2 :=> Update Bin 
-    self.update_bin(is_submit = 1, is_stopped = 0)
-    
-    # Step 3 :=> Check For Approval Authority
-    get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
-    
-    # Step 4 :=> Update Current PO No. in Supplier as last_purchase_order.
-    update_supplier = sql("update `tabSupplier` set last_purchase_order = '%s' where name = '%s'" % (self.doc.name, self.doc.supplier))
+	# Get UOM Details
+	def get_uom_details(self, arg = ''):
+		return get_obj(dt='Purchase Common').get_uom_details(arg)
 
-    # Step 5 :=> Update last purchase rate
-    pc_obj.update_last_purchase_rate(self, is_submit = 1)
+	# get available qty at warehouse
+	def get_bin_details(self, arg = ''):
+		return get_obj(dt='Purchase Common').get_bin_details(arg)
 
-    # Step 6 :=> Set Status
-    set(self.doc,'status','Submitted')
-    
-    self.doc.indent_no = '';
-  
-   
-  # On Cancel
-  # -------------------------------------------------------------------------------------------------------
-  def on_cancel(self):
-    pc_obj = get_obj(dt = 'Purchase Common')
-    
-    # 1.Check if PO status is stopped
-    pc_obj.check_for_stopped_status(cstr(self.doc.doctype), cstr(self.doc.name))
-    
-    self.check_for_stopped_status(pc_obj)
-    
-    # 2.Check if Purchase Receipt has been submitted against current Purchase Order
-    pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Detail')
+	# Pull Indent
+	def get_indent_details(self):
+		#self.validate_prev_docname() 
+		if self.doc.indent_no:
+			get_obj('DocType Mapper','Indent-Purchase Order').dt_map('Indent','Purchase Order',self.doc.indent_no, self.doc, self.doclist, "[['Indent','Purchase Order'],['Indent Detail', 'PO Detail']]")
+			for d in getlist(self.doclist, 'po_details'):			
+				if d.item_code:
+					item = sql("select last_purchase_rate from tabItem where name = '%s'" %(d.item_code), as_dict=1)
+					d.purchase_rate = item and flt(item[0]['last_purchase_rate']) or 0
+					d.import_rate = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(self.doc.fields.has_key('conversion_rate') and flt(self.doc.conversion_rate) or 1)
+		if self.doc.supplier_qtn:
+			get_obj('DocType Mapper','Supplier Quotation-Purchase Order').dt_map('Supplier Quotation','Purchase Order',self.doc.supplier_qtn, self.doc, self.doclist, "[['Supplier Quotation','Purchase Order'],['Supplier Quotation Detail', 'PO Detail']]")
+	
+	# GET TERMS & CONDITIONS
+	# =====================================================================================
+	def get_tc_details(self):
+		return get_obj('Purchase Common').get_tc_details(self)
 
-    # 3.Check if Payable Voucher has been submitted against current Purchase Order
-    #pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
-    
-    submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
-    if submitted:
-      msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
-      raise Exception
+	# validate if indent has been pulled twice
+	def validate_prev_docname(self):
+		for d in getlist(self.doclist, 'po_details'): 
+			if d.prevdoc_docname and self.doc.indent_no == d.prevdoc_docname:
+				msgprint(cstr(self.doc.indent_no) + " indent details have already been pulled. ")
+				raise Exception
 
-    # 4.Set Status as Cancelled
-    set(self.doc,'status','Cancelled')
+	# get last purchase rate
+	def get_last_purchase_rate(self):
+		get_obj('Purchase Common').get_last_purchase_rate(self)
+		
+	# validation
+	#-------------------------------------------------------------------------------------------------------------
+	def validate_doc(self,pc_obj):
+		# Please Check Supplier Quotation - Purchase ORder Transaction , it has to be discussed
+		if self.doc.supp_quo_no:
+			pc_obj.validate_doc(obj = self, prevdoc_doctype = 'Supplier Quotation', prevdoc_docname = cstr(self.doc.supp_quo_no))
+		else:
+			# Validate values with reference document
+			pc_obj.validate_reference_value(obj = self)
 
-    # 5.Update Indents Pending Qty and accordingly it's Status 
-    pc_obj.update_prevdoc_detail(self,is_submit = 0)
-    
-    # 6.Update Bin  
-    self.update_bin( is_submit = 0, is_stopped = 0)
-    
-    # Step 7 :=> Update last purchase rate 
-    pc_obj.update_last_purchase_rate(self, is_submit = 0)
-    
+	# Check for Stopped status 
+	def check_for_stopped_status(self, pc_obj):
+		check_list =[]
+		for d in getlist(self.doclist, 'po_details'):
+			if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
+				check_list.append(d.prevdoc_docname)
+				pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
+
+		
+	# Validate
+	def validate(self):
+		self.validate_fiscal_year()
+		# Step 1:=> set status as "Draft"
+		set(self.doc, 'status', 'Draft')
+		
+		# Step 2:=> get Purchase Common Obj
+		pc_obj = get_obj(dt='Purchase Common')
+		
+		# Step 3:=> validate mandatory
+		pc_obj.validate_mandatory(self)
+
+		# Step 4:=> validate for items
+		pc_obj.validate_for_items(self)
+
+		# Step 5:=> validate conversion rate
+		pc_obj.validate_conversion_rate(self)
+		
+		# Get po date
+		pc_obj.get_prevdoc_date(self)
+		
+		# validate_doc
+		self.validate_doc(pc_obj)
+		
+		# Check for stopped status
+		self.check_for_stopped_status(pc_obj)
+		
+			
+		 # get total in words
+		dcc = TransactionBase().get_company_currency(self.doc.company)
+		self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
+		self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
+	
+	# update bin
+	# ----------
+	def update_bin(self, is_submit, is_stopped = 0):
+		pc_obj = get_obj('Purchase Common')
+		for d in getlist(self.doclist, 'po_details'):
+			#1. Check if is_stock_item == 'Yes'
+			if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
+				
+				ind_qty, po_qty = 0, flt(d.qty) * flt(d.conversion_factor)
+				if is_stopped:
+					po_qty = flt(d.qty) > flt(d.received_qty) and flt( flt(flt(d.qty) - flt(d.received_qty)) * flt(d.conversion_factor))or 0 
+				
+				# No updates in Indent on Stop / Unstop
+				if cstr(d.prevdoc_doctype) == 'Indent' and not is_stopped:
+					# get qty and pending_qty of prevdoc 
+					curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'Indent Detail', 'Indent - Purchase Order', self.doc.name)
+					max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
+					
+					if flt(qty) + flt(po_qty) > flt(max_qty):
+						curr_qty = flt(max_qty) - flt(qty)
+						# special case as there is no restriction for Indent - Purchase Order 
+						curr_qty = (curr_qty > 0) and curr_qty or 0
+					else:
+						curr_qty = flt(po_qty)
+					
+					ind_qty = -flt(curr_qty)
+
+				#==> Update Bin's Indent Qty by +- ind_qty and Ordered Qty by +- qty
+				get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(po_qty), (is_submit and 1 or -1) * flt(ind_qty), 0, d.item_code, self.doc.transaction_date)
+
+	def check_modified_date(self):
+		mod_db = sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
+		date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
+		
+		if date_diff and date_diff[0][0]:
+			msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
+			raise Exception
+
+	# On Close
+	#-------------------------------------------------------------------------------------------------
+	def update_status(self, status):
+		self.check_modified_date()
+		# step 1:=> Set Status
+		set(self.doc,'status',cstr(status))
+
+		# step 2:=> Update Bin
+		self.update_bin(is_submit = (status == 'Submitted') and 1 or 0, is_stopped = 1)
+
+		# step 3:=> Acknowledge user
+		msgprint(self.doc.doctype + ": " + self.doc.name + " has been %s." % ((status == 'Submitted') and 'Unstopped' or cstr(status)))
+
+
+	# On Submit
+	def on_submit(self):
+		pc_obj = get_obj(dt ='Purchase Common')
+		
+		# Step 1 :=> Update Previous Doc i.e. update pending_qty and Status accordingly
+		pc_obj.update_prevdoc_detail(self, is_submit = 1)
+
+		# Step 2 :=> Update Bin 
+		self.update_bin(is_submit = 1, is_stopped = 0)
+		
+		# Step 3 :=> Check For Approval Authority
+		get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
+		
+		# Step 4 :=> Update Current PO No. in Supplier as last_purchase_order.
+		update_supplier = sql("update `tabSupplier` set last_purchase_order = '%s' where name = '%s'" % (self.doc.name, self.doc.supplier))
+
+		# Step 5 :=> Update last purchase rate
+		pc_obj.update_last_purchase_rate(self, is_submit = 1)
+
+		# Step 6 :=> Set Status
+		set(self.doc,'status','Submitted')
+		
+		self.doc.indent_no = '';
+	
+	 
+	# On Cancel
+	# -------------------------------------------------------------------------------------------------------
+	def on_cancel(self):
+		pc_obj = get_obj(dt = 'Purchase Common')
+		
+		# 1.Check if PO status is stopped
+		pc_obj.check_for_stopped_status(cstr(self.doc.doctype), cstr(self.doc.name))
+		
+		self.check_for_stopped_status(pc_obj)
+		
+		# 2.Check if Purchase Receipt has been submitted against current Purchase Order
+		pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Detail')
+
+		# 3.Check if Payable Voucher has been submitted against current Purchase Order
+		#pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
+		
+		submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
+		if submitted:
+			msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
+			raise Exception
+
+		# 4.Set Status as Cancelled
+		set(self.doc,'status','Cancelled')
+
+		# 5.Update Indents Pending Qty and accordingly it's Status 
+		pc_obj.update_prevdoc_detail(self,is_submit = 0)
+		
+		# 6.Update Bin	
+		self.update_bin( is_submit = 0, is_stopped = 0)
+		
+		# Step 7 :=> Update last purchase rate 
+		pc_obj.update_last_purchase_rate(self, is_submit = 0)
+		
 #----------- code for Sub-contracted Items -------------------
-  #--------check for sub-contracted items and accordingly update PO raw material detail table--------
-  def update_rw_material_detail(self):
-    for d in getlist(self.doclist,'po_details'):
-      item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
-      
-      if item_det[0][0] == 'Yes':
-        if item_det[0][1] == 'Yes':
-          if not self.doc.is_subcontracted:
-            msgprint("Please enter whether purchase order to be made for subcontracting or for purchasing in 'Is Subcontracted' field .")
-            raise Exception
-          if self.doc.is_subcontracted == 'Yes':
-            self.add_bom(d)
-          else:
-            self.doc.clear_table(self.doclist,'po_raw_material_details',1)
-            self.doc.save()
-        elif item_det[0][1] == 'No':
-          self.add_bom(d)
-        
-      self.delete_irrelevant_raw_material()
-      #---------------calculate amt in  PO Raw Material Detail-------------
-      self.calculate_amount(d)
-      
-  def add_bom(self, d):
-    #----- fetching default bom from Bill of Materials instead of Item Master --
-    bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.parent from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1" % d.item_code)
-    
-    if not bom_det:
-      msgprint("No default BOM exists for item: %s" % d.item_code)
-      raise Exception
-    else:
-      #-------------- add child function--------------------
-      chgd_rqd_qty = []
-      for i in bom_det:
-        if i and not sql("select name from `tabPO Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
+	#--------check for sub-contracted items and accordingly update PO raw material detail table--------
+	def update_rw_material_detail(self):
+		for d in getlist(self.doclist,'po_details'):
+			item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
+			
+			if item_det[0][0] == 'Yes':
+				if item_det[0][1] == 'Yes':
+					if not self.doc.is_subcontracted:
+						msgprint("Please enter whether purchase order to be made for subcontracting or for purchasing in 'Is Subcontracted' field .")
+						raise Exception
+					if self.doc.is_subcontracted == 'Yes':
+						self.add_bom(d)
+					else:
+						self.doc.clear_table(self.doclist,'po_raw_material_details',1)
+						self.doc.save()
+				elif item_det[0][1] == 'No':
+					self.add_bom(d)
+				
+			self.delete_irrelevant_raw_material()
+			#---------------calculate amt in	PO Raw Material Detail-------------
+			self.calculate_amount(d)
+			
+	def add_bom(self, d):
+		#----- fetching default bom from Bill of Materials instead of Item Master --
+		bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.parent from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1" % d.item_code)
+		
+		if not bom_det:
+			msgprint("No default BOM exists for item: %s" % d.item_code)
+			raise Exception
+		else:
+			#-------------- add child function--------------------
+			chgd_rqd_qty = []
+			for i in bom_det:
+				if i and not sql("select name from `tabPO Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
 
-          rm_child = addchild(self.doc, 'po_raw_material_details', 'PO Raw Material Detail', 1, self.doclist)
+					rm_child = addchild(self.doc, 'po_raw_material_details', 'PO Raw Material Detail', 1, self.doclist)
 
-          rm_child.reference_name = d.name
-          rm_child.bom_detail_no = i and i[6] or ''
-          rm_child.main_item_code = i and i[0] or ''
-          rm_child.rm_item_code = i and i[1] or ''
-          rm_child.stock_uom = i and i[5] or ''
-          rm_child.rate = i and flt(i[3]) or flt(i[4])
-          rm_child.conversion_factor = d.conversion_factor
-          rm_child.required_qty = flt(i  and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
-          rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
-          rm_child.save()
-          chgd_rqd_qty.append(cstr(i[1]))
-        else:
-          act_qty = flt(i  and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
-          for po_rmd in getlist(self.doclist, 'po_raw_material_details'):
-            if i and i[6] == po_rmd.bom_detail_no and (flt(act_qty) != flt(po_rmd.required_qty) or i[1] != po_rmd.rm_item_code):
-              chgd_rqd_qty.append(cstr(i[1]))
-              po_rmd.main_item_code = i[0]
-              po_rmd.rm_item_code = i[1]
-              po_rmd.stock_uom = i[5]
-              po_rmd.required_qty = flt(act_qty)
-              po_rmd.rate = i and flt(i[3]) or flt(i[4])
-              po_rmd.amount = flt(flt(po_rmd.consumed_qty)*flt(po_rmd.rate))
-              
+					rm_child.reference_name = d.name
+					rm_child.bom_detail_no = i and i[6] or ''
+					rm_child.main_item_code = i and i[0] or ''
+					rm_child.rm_item_code = i and i[1] or ''
+					rm_child.stock_uom = i and i[5] or ''
+					rm_child.rate = i and flt(i[3]) or flt(i[4])
+					rm_child.conversion_factor = d.conversion_factor
+					rm_child.required_qty = flt(i	and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
+					rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
+					rm_child.save()
+					chgd_rqd_qty.append(cstr(i[1]))
+				else:
+					act_qty = flt(i	and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
+					for po_rmd in getlist(self.doclist, 'po_raw_material_details'):
+						if i and i[6] == po_rmd.bom_detail_no and (flt(act_qty) != flt(po_rmd.required_qty) or i[1] != po_rmd.rm_item_code):
+							chgd_rqd_qty.append(cstr(i[1]))
+							po_rmd.main_item_code = i[0]
+							po_rmd.rm_item_code = i[1]
+							po_rmd.stock_uom = i[5]
+							po_rmd.required_qty = flt(act_qty)
+							po_rmd.rate = i and flt(i[3]) or flt(i[4])
+							po_rmd.amount = flt(flt(po_rmd.consumed_qty)*flt(po_rmd.rate))
+							
 
-  # Delete irrelevant raw material from PR Raw material details
-  #--------------------------------------------------------------  
-  def delete_irrelevant_raw_material(self):
-    for d in getlist(self.doclist,'po_raw_material_details'):
-      if not sql("select name from `tabPO Detail` where name = '%s' and parent = '%s'and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
-        d.parent = 'old_par:'+self.doc.name
-        d.save()
-    
-  def calculate_amount(self, d):
-    amt = 0
-    for i in getlist(self.doclist,'po_raw_material_details'):
-      
-      if(i.reference_name == d.name):
-        i.amount = flt(i.required_qty)* flt(i.rate)
-        amt += i.amount
-    d.rm_supp_cost = amt
+	# Delete irrelevant raw material from PR Raw material details
+	#--------------------------------------------------------------	
+	def delete_irrelevant_raw_material(self):
+		for d in getlist(self.doclist,'po_raw_material_details'):
+			if not sql("select name from `tabPO Detail` where name = '%s' and parent = '%s'and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
+				d.parent = 'old_par:'+self.doc.name
+				d.save()
+		
+	def calculate_amount(self, d):
+		amt = 0
+		for i in getlist(self.doclist,'po_raw_material_details'):
+			
+			if(i.reference_name == d.name):
+				i.amount = flt(i.required_qty)* flt(i.rate)
+				amt += i.amount
+		d.rm_supp_cost = amt
 
-  # On Update
-  # ----------------------------------------------------------------------------------------------------    
-  def on_update(self):
-    self.update_rw_material_detail()
-    
+	# On Update
+	# ----------------------------------------------------------------------------------------------------		
+	def on_update(self):
+		self.update_rw_material_detail()
+		
 
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
-  
-  # *********** Get Tax rate if account type is TAX ********************
-  def get_rate(self,arg):
-    return get_obj('Purchase Common').get_rate(arg,self)
+	
+	# *********** Get Tax rate if account type is TAX ********************
+	def get_rate(self,arg):
+		return get_obj('Purchase Common').get_rate(arg,self)
 
-  # **** Pull details from other charges master (Get Other Charges) ****
-  def get_purchase_tax_details(self):
-    return get_obj('Purchase Common').get_purchase_tax_details(self)
+	# **** Pull details from other charges master (Get Other Charges) ****
+	def get_purchase_tax_details(self):
+		return get_obj('Purchase Common').get_purchase_tax_details(self)
 
-  # Repair Purchase Order
-  # ===========================================
-  def repair_purchase_order(self):
-    get_obj('Purchase Common', 'Purchase Common').repair_curr_doctype_details(self)
+	# Repair Purchase Order
+	# ===========================================
+	def repair_purchase_order(self):
+		get_obj('Purchase Common', 'Purchase Common').repair_curr_doctype_details(self)
diff --git a/erpnext/hr/doctype/attendance_control_panel/attendance_control_panel.py b/erpnext/hr/doctype/attendance_control_panel/attendance_control_panel.py
index febcd91..eb22179 100644
--- a/erpnext/hr/doctype/attendance_control_panel/attendance_control_panel.py
+++ b/erpnext/hr/doctype/attendance_control_panel/attendance_control_panel.py
@@ -94,8 +94,9 @@
       
     from webnotes.utils import file_manager
     fn, content = file_manager.get_file(filename[1])
-    
-    if not type(content) == str:
+ 
+	# NOTE: Don't know why this condition exists
+    if not isinstance(content, basestring) and hasattr(content, 'tostring'):
       content = content.tostring()
 
     import webnotes.model.import_docs
diff --git a/erpnext/selling/doctype/enquiry/enquiry.js b/erpnext/selling/doctype/enquiry/enquiry.js
index 499e6c6..f7159ab 100644
--- a/erpnext/selling/doctype/enquiry/enquiry.js
+++ b/erpnext/selling/doctype/enquiry/enquiry.js
@@ -2,49 +2,49 @@
 
 cur_frm.cscript.refresh = function(doc, cdt, cdn){
 
-  // 
+	// 
 
-  if(!doc.docstatus){
-    hide_field(['Update Follow up']);
-    hide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
-  }
-  else{
-    unhide_field(['Update Follow up']);
-    unhide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
-  }
+	if(!doc.docstatus){
+		hide_field(['Update Follow up']);
+		hide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
+	}
+	else{
+		unhide_field(['Update Follow up']);
+		unhide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
+	}
 
-  
-  cur_frm.clear_custom_buttons();
-  if(doc.docstatus == 1) {
-    cur_frm.add_custom_button('Create Quotation', cur_frm.cscript['Create Quotation']);
-    cur_frm.add_custom_button('Enquiry Lost', cur_frm.cscript['Declare Enquiry Lost']);
-    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-  }
+	
+	cur_frm.clear_custom_buttons();
+	if(doc.docstatus == 1) {
+		cur_frm.add_custom_button('Create Quotation', cur_frm.cscript['Create Quotation']);
+		cur_frm.add_custom_button('Enquiry Lost', cur_frm.cscript['Declare Enquiry Lost']);
+		cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+	}
 
-  //cur_frm.cscript.clear_values(doc,cdt,cdn);
+	//cur_frm.cscript.clear_values(doc,cdt,cdn);
 }
 
 // ONLOAD
 // ===============================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
 
-  if(!doc.enquiry_from) hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
-  if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-  if(!doc.date) doc.transaction_date = date.obj_to_str(new Date());
-  if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
-  if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});    
-  
-  if(doc.enquiry_from) {
-    if(doc.enquiry_from == 'Customer') {
-      hide_field(['lead', 'lead_name']);
-    }
-    else if (doc.enquiry_from == 'Lead') {
-      hide_field(['customer', 'customer_address', 'contact_person', 'customer_name', 'contact_display', 'customer_group']);
-    }
-  } 
+	if(!doc.enquiry_from) hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
+	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
+	if(!doc.date) doc.transaction_date = date.obj_to_str(new Date());
+	if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
+	if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});		
+	
+	if(doc.enquiry_from) {
+		if(doc.enquiry_from == 'Customer') {
+			hide_field(['lead', 'lead_name']);
+		}
+		else if (doc.enquiry_from == 'Lead') {
+			hide_field(['customer', 'customer_address', 'contact_person', 'customer_name', 'contact_display', 'customer_group']);
+		}
+	} 
 
-  // setup fetch
-  cur_frm.cscript.set_fetch();
+	// setup fetch
+	cur_frm.cscript.set_fetch();
 }
 
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
@@ -57,119 +57,119 @@
 // ===============================================================
 cur_frm.cscript.set_fetch = function() {
 
-  // item
-  cur_frm.add_fetch('item_code', 'item_name', 'item_name');
-  cur_frm.add_fetch('item_code', 'stock_uom', 'uom');
-  cur_frm.add_fetch('item_code', 'description', 'description');
-  cur_frm.add_fetch('item_code', 'item_group', 'item_group');
-  cur_frm.add_fetch('item_code', 'brand', 'brand');
+	// item
+	cur_frm.add_fetch('item_code', 'item_name', 'item_name');
+	cur_frm.add_fetch('item_code', 'stock_uom', 'uom');
+	cur_frm.add_fetch('item_code', 'description', 'description');
+	cur_frm.add_fetch('item_code', 'item_group', 'item_group');
+	cur_frm.add_fetch('item_code', 'brand', 'brand');
 
-  // customer
+	// customer
 
 }
 
 // hide - unhide fields on basis of enquiry_from lead or customer
 cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){
-  cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
+	cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
 }
 
 // hide - unhide fields based on lead or customer
 cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
-  if(doc.enquiry_from == 'Lead'){
-    unhide_field(['lead']);
-    hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
-    doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
-  }
-  else if(doc.enquiry_from == 'Customer'){    
-    unhide_field(['customer']);
-    hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);    
-    doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
-  }
+	if(doc.enquiry_from == 'Lead'){
+		unhide_field(['lead']);
+		hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+		doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
+	}
+	else if(doc.enquiry_from == 'Customer'){		
+		unhide_field(['customer']);
+		hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);		
+		doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
+	}
 }
 
 // customer
 cur_frm.cscript.customer = function(doc,dt,dn) {
-  if(doc.customer) get_server_fields('get_default_customer_address', JSON.stringify({customer: doc.customer}),'', doc, dt, dn, 1);
-  if(doc.customer) unhide_field(['customer_name','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+	if(doc.customer) get_server_fields('get_default_customer_address', JSON.stringify({customer: doc.customer}),'', doc, dt, dn, 1);
+	if(doc.customer) unhide_field(['customer_name','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
 }
 
-cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {    
-  if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
+	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict.customer_address.on_new = function(dn) {
-  locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 // lead
 cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
-  return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s"  ORDER BY  `tabLead`.`name` ASC LIMIT 50';
+	return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s"	ORDER BY	`tabLead`.`name` ASC LIMIT 50';
 }
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
-  if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
-  if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);  
+	if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
+	if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);	
 }
 
 
 //item getquery
 //=======================================
 cur_frm.fields_dict['enquiry_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
-  if (doc.enquiry_type == 'Maintenance')
-    return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
-  else 
-    return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+	if (doc.enquiry_type == 'Maintenance')
+		return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+	else 
+		return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
 }
-  
+	
  //Fetch Item Details
 //====================================================================================================================
 cur_frm.cscript.item_code = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if (d.item_code) {
-    get_server_fields('get_item_details',d.item_code,'enquiry_details',doc,cdt,cdn,1);
-  }
+	var d = locals[cdt][cdn];
+	if (d.item_code) {
+		get_server_fields('get_item_details',d.item_code,'enquiry_details',doc,cdt,cdn,1);
+	}
 }
 
 /*
  //Fetch Customer Details
 //======================================================================================================================
 cur_frm.cscript.customer = function(doc, cdt, cdn){
-  if (doc.customer) {
-    get_server_fields('get_cust_address',doc.customer,'',doc,cdt,cdn,1);
-  }
+	if (doc.customer) {
+		get_server_fields('get_cust_address',doc.customer,'',doc,cdt,cdn,1);
+	}
 }
 */
 
 /*
 //=======================================================================================================================
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE `tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'" AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
+	return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE `tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'" AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
 }
 */
 
 /*
 //=======================================================================================================================
 cur_frm.cscript.contact_person = function(doc, cdt, cdn){
-  if (doc.contact_person) {
-    arg = {};
-    arg.contact_person = doc.contact_person;
-    arg.customer = doc.customer;
-    get_server_fields('get_contact_details',docstring(arg),'',doc,cdt,cdn,1);
-  }
+	if (doc.contact_person) {
+		arg = {};
+		arg.contact_person = doc.contact_person;
+		arg.customer = doc.customer;
+		get_server_fields('get_contact_details',docstring(arg),'',doc,cdt,cdn,1);
+	}
 }
 */
 
@@ -177,159 +177,159 @@
 // hide - unhide fields based on lead or customer..
 //=======================================================================================================================
 cur_frm.cscript.clear_values = function(doc,cdt,cdn) {
-  if(doc.enquiry_from == 'Lead') {
-    doc.customer = doc.customer_name = doc.contact_person = doc.customer_group = "";
-  }
-  else if(doc.enquiry_from == 'Customer') {
-    doc.lead =  doc.lead_name = "";
-  }
-  refresh_many(['lead','lead_name','customer','customer_name','contact_person','customer_group']);
+	if(doc.enquiry_from == 'Lead') {
+		doc.customer = doc.customer_name = doc.contact_person = doc.customer_group = "";
+	}
+	else if(doc.enquiry_from == 'Customer') {
+		doc.lead =	doc.lead_name = "";
+	}
+	refresh_many(['lead','lead_name','customer','customer_name','contact_person','customer_group']);
 }
 */
 
 /*
 //================ hide - unhide fields on basis of enquiry from either lead or customer =============================== 
 cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){
-  cur_frm.cscript.clear_values(doc,cdt,cdn);
-   doc.address = doc.territory = doc.contact_no = doc.email_id = "";
-   refresh_many(['territory','address','contact_no','email_id']);
+	cur_frm.cscript.clear_values(doc,cdt,cdn);
+	 doc.address = doc.territory = doc.contact_no = doc.email_id = "";
+	 refresh_many(['territory','address','contact_no','email_id']);
 }
 */
 
 /*
 //================ create new contact ============================================================================
 cur_frm.cscript.new_contact = function(){
-  tn = createLocal('Contact');
-  locals['Contact'][tn].is_customer = 1;
-  if(doc.customer) locals['Contact'][tn].customer = doc.customer;
-  loaddoc('Contact', tn);
+	tn = createLocal('Contact');
+	locals['Contact'][tn].is_customer = 1;
+	if(doc.customer) locals['Contact'][tn].customer = doc.customer;
+	loaddoc('Contact', tn);
 }
 */
 
 //=======================================================================================================================
 cur_frm.cscript['Create New File'] = function(doc){
-  var fl = LocalDB.create('File');
-  fl = locals['File'][fl];
-  loaddoc('File', fl.name);
+	var fl = LocalDB.create('File');
+	fl = locals['File'][fl];
+	loaddoc('File', fl.name);
 }
 
 //update follow up
 //=================================================================================
 cur_frm.cscript['Update Follow up'] = function(doc,cdt,cdn){
 
-  $c_obj(make_doclist(doc.doctype, doc.name),'update_follow_up','',function(r, rt){
-    refresh_field('follow_up');
-    doc.__unsaved = 0;
-    cur_frm.refresh_header();
-  });
+	$c_obj(make_doclist(doc.doctype, doc.name),'update_follow_up','',function(r, rt){
+		refresh_field('follow_up');
+		doc.__unsaved = 0;
+		cur_frm.refresh_header();
+	});
 }
 
  // Create New Quotation
 // =======================================================================================================================
 cur_frm.cscript['Create Quotation'] = function(){
-  n = createLocal("Quotation");
-  $c('dt_map', args={
-	  'docs':compress_doclist([locals["Quotation"][n]]),
-	  'from_doctype':'Enquiry',
-	  'to_doctype':'Quotation',
-	  'from_docname':cur_frm.docname,
-    'from_to_list':"[['Enquiry', 'Quotation'],['Enquiry Detail','Quotation Detail']]"
-  }
-  , function(r,rt) {
-    loaddoc("Quotation", n);
-    }
-  );
+	n = createLocal("Quotation");
+	$c('dt_map', args={
+		'docs':compress_doclist([locals["Quotation"][n]]),
+		'from_doctype':'Enquiry',
+		'to_doctype':'Quotation',
+		'from_docname':cur_frm.docname,
+		'from_to_list':"[['Enquiry', 'Quotation'],['Enquiry Detail','Quotation Detail']]"
+	}
+	, function(r,rt) {
+		loaddoc("Quotation", n);
+		}
+	);
 }
 
 
-// declare enquiry  lost
+// declare enquiry	lost
 //-------------------------
 cur_frm.cscript['Declare Enquiry Lost'] = function(){
-  var e_lost_dialog;
+	var e_lost_dialog;
 
-  set_e_lost_dialog = function(){
-    e_lost_dialog = new Dialog(400,150,'Add Enquiry Lost Reason');
-    e_lost_dialog.make_body([
-      ['HTML', 'Message', '<div class="comment">Please add enquiry lost reason</div>'],
-      ['Text', 'Enquiry Lost Reason'],
-      ['HTML', 'Response', '<div class = "comment" id="update_enquiry_dialog_response"></div>'],
-      ['HTML', 'Add Reason', '<div></div>']
-    ]);
-    
-    var add_reason_btn1 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
-    add_reason_btn1.innerHTML = 'Add';
-    add_reason_btn1.onclick = function(){ e_lost_dialog.add(); }
-    
-    var add_reason_btn2 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
-    add_reason_btn2.innerHTML = 'Cancel';
-    $y(add_reason_btn2,{marginLeft:'4px'});
-    add_reason_btn2.onclick = function(){ e_lost_dialog.hide();}
-    
-    e_lost_dialog.onshow = function() {
-      e_lost_dialog.widgets['Enquiry Lost Reason'].value = '';
-      $i('update_enquiry_dialog_response').innerHTML = '';
-    }
-    
-    e_lost_dialog.add = function() {
-      // sending...
-      $i('update_enquiry_dialog_response').innerHTML = 'Processing...';
-      var arg =  strip(e_lost_dialog.widgets['Enquiry Lost Reason'].value);
-      var call_back = function(r,rt) { 
-        if(r.message == 'true'){
-          $i('update_enquiry_dialog_response').innerHTML = 'Done';
-          e_lost_dialog.hide();
-        }
-      }
-      if(arg) {
-        $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_enquiry_lost',arg,call_back);
-      }
-      else{
-        msgprint("Please add enquiry lost reason");
-      }
-      
-    }
-  }  
-  
-  if(!e_lost_dialog){
-    set_e_lost_dialog();
-  }  
-  e_lost_dialog.show();
+	set_e_lost_dialog = function(){
+		e_lost_dialog = new Dialog(400,150,'Add Enquiry Lost Reason');
+		e_lost_dialog.make_body([
+			['HTML', 'Message', '<div class="comment">Please add enquiry lost reason</div>'],
+			['Text', 'Enquiry Lost Reason'],
+			['HTML', 'Response', '<div class = "comment" id="update_enquiry_dialog_response"></div>'],
+			['HTML', 'Add Reason', '<div></div>']
+		]);
+		
+		var add_reason_btn1 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
+		add_reason_btn1.innerHTML = 'Add';
+		add_reason_btn1.onclick = function(){ e_lost_dialog.add(); }
+		
+		var add_reason_btn2 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
+		add_reason_btn2.innerHTML = 'Cancel';
+		$y(add_reason_btn2,{marginLeft:'4px'});
+		add_reason_btn2.onclick = function(){ e_lost_dialog.hide();}
+		
+		e_lost_dialog.onshow = function() {
+			e_lost_dialog.widgets['Enquiry Lost Reason'].value = '';
+			$i('update_enquiry_dialog_response').innerHTML = '';
+		}
+		
+		e_lost_dialog.add = function() {
+			// sending...
+			$i('update_enquiry_dialog_response').innerHTML = 'Processing...';
+			var arg =	strip(e_lost_dialog.widgets['Enquiry Lost Reason'].value);
+			var call_back = function(r,rt) { 
+				if(r.message == 'true'){
+					$i('update_enquiry_dialog_response').innerHTML = 'Done';
+					e_lost_dialog.hide();
+				}
+			}
+			if(arg) {
+				$c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_enquiry_lost',arg,call_back);
+			}
+			else{
+				msgprint("Please add enquiry lost reason");
+			}
+			
+		}
+	}	
+	
+	if(!e_lost_dialog){
+		set_e_lost_dialog();
+	}	
+	e_lost_dialog.show();
 }
 
 //get query select Territory
 //=======================================================================================================================
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"  ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';}
+	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';}
 
 /*
 //===================== Enquiry From validation - either customer or lead is mandatory =====================================
 cur_frm.cscript.enq_frm_validate = function(doc,cdt,cdn){
-  
-  if(doc.enquiry_from == 'Lead'){
-    if(!doc.lead){
-      alert("Lead is mandatory.");  
-      validated = false; 
-    }
-  }
-  else if(doc.enquiry_from == 'Customer'){
-      if(!doc.customer){
-      alert("Customer is mandatory.");
-      validated = false;
-    }
-    else if(!doc.contact_person){
-      alert("Contact Person is mandatory.");
-      validated = false;
-    }
-    else if(!doc.customer_group){
-      alert("Customer Group is mandatory.");
-      validated = false;
-    }
-  } 
+	
+	if(doc.enquiry_from == 'Lead'){
+		if(!doc.lead){
+			alert("Lead is mandatory.");	
+			validated = false; 
+		}
+	}
+	else if(doc.enquiry_from == 'Customer'){
+			if(!doc.customer){
+			alert("Customer is mandatory.");
+			validated = false;
+		}
+		else if(!doc.contact_person){
+			alert("Contact Person is mandatory.");
+			validated = false;
+		}
+		else if(!doc.customer_group){
+			alert("Customer Group is mandatory.");
+			validated = false;
+		}
+	} 
 }
 */
 
 //===================validation function ==============================================================================
 
 cur_frm.cscript.validate = function(doc,cdt,cdn){
-  //cur_frm.cscript.enq_frm_validate(doc,cdt,cdn);
+	//cur_frm.cscript.enq_frm_validate(doc,cdt,cdn);
 }
diff --git a/erpnext/selling/doctype/quotation/quotation.js b/erpnext/selling/doctype/quotation/quotation.js
index 9ff676f..9ba743d 100644
--- a/erpnext/selling/doctype/quotation/quotation.js
+++ b/erpnext/selling/doctype/quotation/quotation.js
@@ -12,53 +12,57 @@
 // ONLOAD
 // ===================================================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
-  if(!doc.quotation_to) hide_field(['customer','customer_address','contact_person','customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
-  if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
-  if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-  if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
-  if(!doc.conversion_rate) set_multiple(cdt,cdn,{conversion_rate:'1.00'});
-  if(!doc.currency && sys_defaults.currency) set_multiple(cdt,cdn,{currency:sys_defaults.currency});
-  if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
+	if(!doc.quotation_to) hide_field(['customer','customer_address','contact_person','customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
+	if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
+	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
+	if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
+	if(!doc.conversion_rate) set_multiple(cdt,cdn,{conversion_rate:'1.00'});
+	if(!doc.currency && sys_defaults.currency) set_multiple(cdt,cdn,{currency:sys_defaults.currency});
+	if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
 
-  if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
-  if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
+	if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
+	if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
 
-  if(doc.quotation_to) {
-    if(doc.quotation_to == 'Customer') {
-      hide_field(['lead', 'lead_name']);
-    }
-    else if (doc.quotation_to == 'Lead') {
-      hide_field(['customer','customer_address','contact_person', 'customer_name','contact_display', 'customer_group']);
-    }
-  }
+	if(doc.quotation_to) {
+		if(doc.quotation_to == 'Customer') {
+			hide_field(['lead', 'lead_name']);
+		}
+		else if (doc.quotation_to == 'Lead') {
+			hide_field(['customer','customer_address','contact_person', 'customer_name','contact_display', 'customer_group']);
+		}
+	}
+
+	// defined in sales_common.js
+	cur_frm.cscript.update_item_details(doc, cdt, cdn);
+
 }
 
 cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
-  // load default charges
-  if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
-    cur_frm.cscript.load_taxes(doc, cdt, cdn);
+	// load default charges
+	if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
+		cur_frm.cscript.load_taxes(doc, cdt, cdn);
 }
 
 // hide - unhide fields based on lead or customer..
 // =======================================================================================================================
 cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
-  if(doc.quotation_to == 'Lead'){
-    unhide_field(['lead']);
-    hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
-    doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
-  }
-  else if(doc.quotation_to == 'Customer'){
-    unhide_field(['customer']);
-    hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);
-    doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
-  }
+	if(doc.quotation_to == 'Lead'){
+		unhide_field(['lead']);
+		hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+		doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
+	}
+	else if(doc.quotation_to == 'Customer'){
+		unhide_field(['customer']);
+		hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);
+		doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
+	}
 }
 
 
 
 //================ hide - unhide fields on basis of quotation to either lead or customer ===============================
 cur_frm.cscript.quotation_to = function(doc,cdt,cdn){
-  cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
+	cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
 }
 
 
@@ -66,111 +70,111 @@
 // ===================================================================================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
 
-  cur_frm.clear_custom_buttons();
+	cur_frm.clear_custom_buttons();
 
-  if(doc.docstatus == 1 && doc.status!='Order Lost') {
-    cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']);
-    cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
-    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-  }
+	if(doc.docstatus == 1 && doc.status!='Order Lost') {
+		cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']);
+		cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
+		cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+	}
 
-  if (!doc.docstatus) hide_field(['Update Follow up']);
-  else unhide_field(['Update Follow up']);
+	if (!doc.docstatus) hide_field(['Update Follow up']);
+	else unhide_field(['Update Follow up']);
 }
 
 
 //customer
 cur_frm.cscript.customer = function(doc,dt,dn) {
-  var callback = function(r,rt) {
-      var doc = locals[cur_frm.doctype][cur_frm.docname];
-      cur_frm.refresh();
-  }
+	var callback = function(r,rt) {
+			var doc = locals[cur_frm.doctype][cur_frm.docname];
+			cur_frm.refresh();
+	}
 
-  if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
-  if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
+	if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
 }
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
-  if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict.customer_address.on_new = function(dn) {
-  locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 //lead
 cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
-  return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s"  ORDER BY  `tabLead`.`name` ASC LIMIT 50';
+	return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s"	ORDER BY	`tabLead`.`name` ASC LIMIT 50';
 }
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
-  if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
-  if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);
+	if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
+	if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);
 }
 
 
 // =====================================================================================
 cur_frm.fields_dict['enq_no'].get_query = function(doc,cdt,cdn){
-  var cond='';
-  var cond1='';
-  if(doc.order_type) cond = 'ifnull(`tabEnquiry`.enquiry_type, "") = "'+doc.order_type+'" AND';
-  if(doc.customer) cond1 = '`tabEnquiry`.customer = "'+doc.customer+'" AND';
-  else if(doc.lead) cond1 = '`tabEnquiry`.lead = "'+doc.lead+'" AND';
+	var cond='';
+	var cond1='';
+	if(doc.order_type) cond = 'ifnull(`tabEnquiry`.enquiry_type, "") = "'+doc.order_type+'" AND';
+	if(doc.customer) cond1 = '`tabEnquiry`.customer = "'+doc.customer+'" AND';
+	else if(doc.lead) cond1 = '`tabEnquiry`.lead = "'+doc.lead+'" AND';
 
-  return repl('SELECT `tabEnquiry`.`name` FROM `tabEnquiry` WHERE `tabEnquiry`.`docstatus` = 1 AND `tabEnquiry`.status = "Submitted" AND %(cond)s %(cond1)s `tabEnquiry`.`name` LIKE "%s" ORDER BY `tabEnquiry`.`name` ASC LIMIT 50', {cond:cond, cond1:cond1});
+	return repl('SELECT `tabEnquiry`.`name` FROM `tabEnquiry` WHERE `tabEnquiry`.`docstatus` = 1 AND `tabEnquiry`.status = "Submitted" AND %(cond)s %(cond1)s `tabEnquiry`.`name` LIKE "%s" ORDER BY `tabEnquiry`.`name` ASC LIMIT 50', {cond:cond, cond1:cond1});
 }
 
 // Make Sales Order
 // =====================================================================================
 cur_frm.cscript['Make Sales Order'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  if (doc.docstatus == 1) {
-    var n = createLocal("Sales Order");
-    $c('dt_map', args={
-      'docs':compress_doclist([locals["Sales Order"][n]]),
-      'from_doctype':'Quotation',
-      'to_doctype':'Sales Order',
-      'from_docname':doc.name,
-      'from_to_list':"[['Quotation', 'Sales Order'], ['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'], ['Sales Team', 'Sales Team'], ['TC Detail', 'TC Detail']]"
-    }, function(r,rt) {
-      loaddoc("Sales Order", n);
-    });
-  }
+	if (doc.docstatus == 1) {
+		var n = createLocal("Sales Order");
+		$c('dt_map', args={
+			'docs':compress_doclist([locals["Sales Order"][n]]),
+			'from_doctype':'Quotation',
+			'to_doctype':'Sales Order',
+			'from_docname':doc.name,
+			'from_to_list':"[['Quotation', 'Sales Order'], ['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'], ['Sales Team', 'Sales Team'], ['TC Detail', 'TC Detail']]"
+		}, function(r,rt) {
+			loaddoc("Sales Order", n);
+		});
+	}
 }
 
 //pull enquiry details
 cur_frm.cscript['Pull Enquiry Detail'] = function(doc,cdt,cdn){
 
-  var callback = function(r,rt){
-    if(r.message){
-      doc.quotation_to = r.message;
+	var callback = function(r,rt){
+		if(r.message){
+			doc.quotation_to = r.message;
 
-		  if(doc.quotation_to == 'Lead') {
-  			  unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']);
-		  }
-		  else if(doc.quotation_to == 'Customer') {
-			  unhide_field(['customer','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
-		  }
-		  refresh_many(['quotation_details','quotation_to','customer','customer_address','contact_person','lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','order_type']);
-    }
-  }
+			if(doc.quotation_to == 'Lead') {
+					unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']);
+			}
+			else if(doc.quotation_to == 'Customer') {
+				unhide_field(['customer','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+			}
+			refresh_many(['quotation_details','quotation_to','customer','customer_address','contact_person','lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','order_type']);
+		}
+	}
 
-  $c_obj(make_doclist(doc.doctype, doc.name),'pull_enq_details','',callback);
+	$c_obj(make_doclist(doc.doctype, doc.name),'pull_enq_details','',callback);
 
 }
 
@@ -178,70 +182,70 @@
 //=================================================================================
 cur_frm.cscript['Update Follow up'] = function(doc){
 
-  $c_obj(make_doclist(doc.doctype, doc.name),'update_followup_details','',function(r, rt){
-    refresh_field('follow_up');
-    doc.__unsaved = 0;
-    cur_frm.refresh_header();
-  });
+	$c_obj(make_doclist(doc.doctype, doc.name),'update_followup_details','',function(r, rt){
+		refresh_field('follow_up');
+		doc.__unsaved = 0;
+		cur_frm.refresh_header();
+	});
 }
 
 
 // declare order lost
 //-------------------------
 cur_frm.cscript['Declare Order Lost'] = function(){
-  var qtn_lost_dialog;
+	var qtn_lost_dialog;
 
-  set_qtn_lost_dialog = function(doc,cdt,cdn){
-    qtn_lost_dialog = new Dialog(400,400,'Add Quotation Lost Reason');
-    qtn_lost_dialog.make_body([
-      ['HTML', 'Message', '<div class="comment">Please add quotation lost reason</div>'],
-      ['Text', 'Quotation Lost Reason'],
-      ['HTML', 'Response', '<div class = "comment" id="update_quotation_dialog_response"></div>'],
-      ['HTML', 'Add Reason', '<div></div>']
-    ]);
+	set_qtn_lost_dialog = function(doc,cdt,cdn){
+		qtn_lost_dialog = new Dialog(400,400,'Add Quotation Lost Reason');
+		qtn_lost_dialog.make_body([
+			['HTML', 'Message', '<div class="comment">Please add quotation lost reason</div>'],
+			['Text', 'Quotation Lost Reason'],
+			['HTML', 'Response', '<div class = "comment" id="update_quotation_dialog_response"></div>'],
+			['HTML', 'Add Reason', '<div></div>']
+		]);
 
-    var add_reason_btn1 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
-    add_reason_btn1.innerHTML = 'Add';
-    add_reason_btn1.onclick = function(){ qtn_lost_dialog.add(); }
+		var add_reason_btn1 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
+		add_reason_btn1.innerHTML = 'Add';
+		add_reason_btn1.onclick = function(){ qtn_lost_dialog.add(); }
 
-    var add_reason_btn2 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
-    add_reason_btn2.innerHTML = 'Cancel';
-    $y(add_reason_btn2,{marginLeft:'4px'});
-    add_reason_btn2.onclick = function(){ qtn_lost_dialog.hide();}
+		var add_reason_btn2 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
+		add_reason_btn2.innerHTML = 'Cancel';
+		$y(add_reason_btn2,{marginLeft:'4px'});
+		add_reason_btn2.onclick = function(){ qtn_lost_dialog.hide();}
 
-    qtn_lost_dialog.onshow = function() {
-      qtn_lost_dialog.widgets['Quotation Lost Reason'].value = '';
-      $i('update_quotation_dialog_response').innerHTML = '';
-    }
+		qtn_lost_dialog.onshow = function() {
+			qtn_lost_dialog.widgets['Quotation Lost Reason'].value = '';
+			$i('update_quotation_dialog_response').innerHTML = '';
+		}
 
-    qtn_lost_dialog.add = function() {
-      // sending...
-      $i('update_quotation_dialog_response').innerHTML = 'Processing...';
-      var arg =  strip(qtn_lost_dialog.widgets['Quotation Lost Reason'].value);
-      var call_back = function(r,rt) {
-        if(r.message == 'true'){
-          $i('update_quotation_dialog_response').innerHTML = 'Done';
-          qtn_lost_dialog.hide();
-        }
-      }
-      if(arg) $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_order_lost',arg,call_back);
-      else msgprint("Please add Quotation lost reason");
-    }
-  }
+		qtn_lost_dialog.add = function() {
+			// sending...
+			$i('update_quotation_dialog_response').innerHTML = 'Processing...';
+			var arg =	strip(qtn_lost_dialog.widgets['Quotation Lost Reason'].value);
+			var call_back = function(r,rt) {
+				if(r.message == 'true'){
+					$i('update_quotation_dialog_response').innerHTML = 'Done';
+					qtn_lost_dialog.hide();
+				}
+			}
+			if(arg) $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_order_lost',arg,call_back);
+			else msgprint("Please add Quotation lost reason");
+		}
+	}
 
-  if(!qtn_lost_dialog){
-    set_qtn_lost_dialog(doc,cdt,cdn);
-  }
-  qtn_lost_dialog.show();
+	if(!qtn_lost_dialog){
+		set_qtn_lost_dialog(doc,cdt,cdn);
+	}
+	qtn_lost_dialog.show();
 }
 
 
 // GET REPORT
 // ========================================================================================
 cur_frm.cscript['Get Report'] = function(doc,cdt,cdn) {
-  var callback = function(report){
-  report.set_filter('Sales Order Detail', 'Quotation No.',doc.name)
-  report.dt.run();
+	var callback = function(report){
+	report.set_filter('Sales Order Detail', 'Quotation No.',doc.name)
+	report.dt.run();
  }
  loadreport('Sales Order Detail','Itemwise Sales Details', callback);
 }
@@ -250,33 +254,34 @@
 //===================== Quotation to validation - either customer or lead mandatory ====================
 cur_frm.cscript.quot_to_validate = function(doc,cdt,cdn){
 
-  if(doc.quotation_to == 'Lead'){
+	if(doc.quotation_to == 'Lead'){
 
-    if(!doc.lead){
-      alert("Lead is mandatory.");
-      validated = false;
-    }
-  }
-  else if(doc.quotation_to == 'Customer'){
-    if(!doc.customer){
-      alert("Customer is mandatory.");
-      validated = false;
-    }
-  }
+		if(!doc.lead){
+			alert("Lead is mandatory.");
+			validated = false;
+		}
+	}
+	else if(doc.quotation_to == 'Customer'){
+		if(!doc.customer){
+			alert("Customer is mandatory.");
+			validated = false;
+		}
+	}
 }
 
 //===================validation function =================================
 
 cur_frm.cscript.validate = function(doc,cdt,cdn){
-  cur_frm.cscript.quot_to_validate(doc,cdt,cdn);
+	cur_frm.cscript['Re-Calculate Values'](doc, cdt, cdn);
+	cur_frm.cscript.quot_to_validate(doc,cdt,cdn);
 }
 
 //================ Last Quoted Price and Last Sold Price suggestion ======================
 cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query= function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  var cond = (doc.order_type == 'Maintenance')? " and tabItem.is_service_item = 'Yes'" : " and tabItem.is_sales_item = 'Yes'"
-  if(doc.customer)
-    return repl("SELECT i.name,i.item_code,concat('Last quoted at - ',cast(quote_rate as char)) as quote_rate,concat('Last sold at - ',cast(sales_rate as char)) as sales_rate, i.item_name, i.description FROM\
+	var d = locals[cdt][cdn];
+	var cond = (doc.order_type == 'Maintenance')? " and tabItem.is_service_item = 'Yes'" : " and tabItem.is_sales_item = 'Yes'"
+	if(doc.customer)
+		return repl("SELECT i.name,i.item_code,concat('Last quoted at - ',cast(quote_rate as char)) as quote_rate,concat('Last sold at - ',cast(sales_rate as char)) as sales_rate, i.item_name, i.description FROM\
 		(\
 			select item_code,name, item_name, description from tabItem where tabItem.%(key)s like '%s' %(cond)s\
 		)i\
@@ -300,8 +305,8 @@
 				select rd.item_code,max(voucher_date) as voucher_date from `tabRV Detail` rd, `tabReceivable Voucher` r where r.name=rd.parent and r.docstatus=1 and customer='%(cust)s' group by rd.item_code\
 			)m where r.item_code=m.item_code and r.voucher_date=m.voucher_date\
 		)s on i.item_code=s.item_code ORDER BY item_code LIMIT 50",{cust:doc.customer, cond:cond});
-  else
-    return repl("SELECT name, item_name, description FROM tabItem WHERE `tabItem`.%(key)s LIKE '%s' %(cond)s ORDER BY tabItem.item_code DESC LIMIT 50", {cond:cond});
+	else
+		return repl("SELECT name, item_name, description FROM tabItem WHERE `tabItem`.%(key)s LIKE '%s' %(cond)s ORDER BY tabItem.item_code DESC LIMIT 50", {cond:cond});
 }
 
 $import(Notification Control)
diff --git a/erpnext/selling/doctype/quotation/quotation.py b/erpnext/selling/doctype/quotation/quotation.py
index 01e67eb..795ef79 100644
--- a/erpnext/selling/doctype/quotation/quotation.py
+++ b/erpnext/selling/doctype/quotation/quotation.py
@@ -19,324 +19,334 @@
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
-  def __init__(self, doc, doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
-    self.tname = 'Quotation Detail'
-    self.fname = 'quotation_details'
-    
-  # Autoname
-  # ---------
-  def autoname(self):
-    self.doc.name = make_autoname(self.doc.naming_series+'.#####')
+	def __init__(self, doc, doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		self.tname = 'Quotation Detail'
+		self.fname = 'quotation_details'
+		
+	# Autoname
+	# ---------
+	def autoname(self):
+		self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
 
 # DOCTYPE TRIGGER FUNCTIONS
-# ==============================================================================    
+# ==============================================================================		
  
-  # Pull Enquiry Details
-  # --------------------
-  def pull_enq_details(self):
-    self.doc.clear_table(self.doclist, 'quotation_details')
-    get_obj('DocType Mapper', 'Enquiry-Quotation').dt_map('Enquiry', 'Quotation', self.doc.enq_no, self.doc, self.doclist, "[['Enquiry', 'Quotation'],['Enquiry Detail', 'Quotation Detail']]")
+	# Pull Enquiry Details
+	# --------------------
+	def pull_enq_details(self):
+		self.doc.clear_table(self.doclist, 'quotation_details')
+		get_obj('DocType Mapper', 'Enquiry-Quotation').dt_map('Enquiry', 'Quotation', self.doc.enq_no, self.doc, self.doclist, "[['Enquiry', 'Quotation'],['Enquiry Detail', 'Quotation Detail']]")
 
-    self.get_adj_percent()
+		self.get_adj_percent()
 
-    return self.doc.quotation_to
+		return self.doc.quotation_to
 
-  # Get contact person details based on customer selected
-  # ------------------------------------------------------
-  def get_contact_details(self):
-    return get_obj('Sales Common').get_contact_details(self,0)
-  
-  # Clear Quotation Details
-  # -----------------------
-  def clear_quotation_details(self):
-    self.doc.clear_table(self.doclist, 'quotation_details')  
-  
-    
+	# Get contact person details based on customer selected
+	# ------------------------------------------------------
+	def get_contact_details(self):
+		return get_obj('Sales Common').get_contact_details(self,0)
+	
+	# Clear Quotation Details
+	# -----------------------
+	def clear_quotation_details(self):
+		self.doc.clear_table(self.doclist, 'quotation_details')	
+	
+		
 # QUOTATION DETAILS TRIGGER FUNCTIONS
-# ================================================================================    
+# ================================================================================		
 
-  # Get Item Details
-  # -----------------
-  def get_item_details(self, item_code):
-    return get_obj('Sales Common').get_item_details(item_code, self)
-  
-  # Re-calculates Basic Rate & amount based on Price List Selected
-  # --------------------------------------------------------------
-  def get_adj_percent(self, arg=''):
-    get_obj('Sales Common').get_adj_percent(self)
-    
+	# Get Item Details
+	# -----------------
+	def get_item_details(self, item_code=None):
+		if item_code:
+			return get_obj('Sales Common').get_item_details(item_code, self)
+		else:
+			obj = get_obj('Sales Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					ret = obj.get_item_details(doc.item_code, self)
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]					
+
+
+	# Re-calculates Basic Rate & amount based on Price List Selected
+	# --------------------------------------------------------------
+	def get_adj_percent(self, arg=''):
+		get_obj('Sales Common').get_adj_percent(self)
+		
 
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
-  
-  # Get Tax rate if account type is TAX
-  # -----------------------------------
-  def get_rate(self,arg):
-    return get_obj('Sales Common').get_rate(arg)
+	
+	# Get Tax rate if account type is TAX
+	# -----------------------------------
+	def get_rate(self,arg):
+		return get_obj('Sales Common').get_rate(arg)
 
-  # Load Default Charges
-  # ----------------------------------------------------------
-  def load_default_taxes(self):
-    return get_obj('Sales Common').load_default_taxes(self)
+	# Load Default Charges
+	# ----------------------------------------------------------
+	def load_default_taxes(self):
+		return get_obj('Sales Common').load_default_taxes(self)
 
-  # Pull details from other charges master (Get Other Charges)
-  # ----------------------------------------------------------
-  def get_other_charges(self):
-    return get_obj('Sales Common').get_other_charges(self)
-  
-  # Get Lead Details along with its details
-  # ==============================================================
-  def get_lead_details1(self, name):    
-    details = sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1)   
-    ret = {
-      'lead_name' : details and details[0]['lead_name'] or '',
-      'address_display' : (details and details[0]['address_line1']
-				     + (details[0]['address_line2'] and '\n' + details[0]['address_line2'] or '') + '\n' 
-				     + details[0]['city'] 
-				     + (details[0]['pincode'] and ', ' + details[0]['pincode'] or '') + '\n' 
-				     + (details[0]['state'] and details[0]['state']+', ' or '') 
-				     + details[0]['country'] + '\nTel: ' + details[0]['contact_no'] + '\n' or '-'),
-      'territory' : details and details[0]['territory'] or '',
-      'contact_mobile' : details and details[0]['mobile_no'] or '-',
-      'contact_email' : details and details[0]['email_id'] or '-'      
-    }
-    return ret
+	# Pull details from other charges master (Get Other Charges)
+	# ----------------------------------------------------------
+	def get_other_charges(self):
+		return get_obj('Sales Common').get_other_charges(self)
+	
+	# Get Lead Details along with its details
+	# ==============================================================
+	def get_lead_details1(self, name):		
+		details = sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1)	 
+		ret = {
+			'lead_name' : details and details[0]['lead_name'] or '',
+			'address_display' : (details and details[0]['address_line1']
+						 + (details[0]['address_line2'] and '\n' + details[0]['address_line2'] or '') + '\n' 
+						 + details[0]['city'] 
+						 + (details[0]['pincode'] and ', ' + details[0]['pincode'] or '') + '\n' 
+						 + (details[0]['state'] and details[0]['state']+', ' or '') 
+						 + details[0]['country'] + '\nTel: ' + details[0]['contact_no'] + '\n' or '-'),
+			'territory' : details and details[0]['territory'] or '',
+			'contact_mobile' : details and details[0]['mobile_no'] or '-',
+			'contact_email' : details and details[0]['email_id'] or '-'			
+		}
+		return ret
 
-     
+		 
 # GET TERMS AND CONDITIONS
 # ====================================================================================
-  def get_tc_details(self):
-    return get_obj('Sales Common').get_tc_details(self)
+	def get_tc_details(self):
+		return get_obj('Sales Common').get_tc_details(self)
 
-    
+		
 # VALIDATE
 # ==============================================================================================
-  
-  # Amendment date is necessary if document is amended
-  # --------------------------------------------------
-  def validate_mandatory(self):
-    if self.doc.amended_from and not self.doc.amendment_date:
-      msgprint("Please Enter Amendment Date")
-      raise Exception
+	
+	# Amendment date is necessary if document is amended
+	# --------------------------------------------------
+	def validate_mandatory(self):
+		if self.doc.amended_from and not self.doc.amendment_date:
+			msgprint("Please Enter Amendment Date")
+			raise Exception
 
-  # Fiscal Year Validation
-  # ----------------------
-  def validate_fiscal_year(self):
-    get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Quotation Date')
-  
-  # Does not allow same item code to be entered twice
-  # -------------------------------------------------
-  def validate_for_items(self):
-    chk_dupl_itm = []
-    for d in getlist(self.doclist,'quotation_details'):
-      if [cstr(d.item_code),cstr(d.description)] in chk_dupl_itm:
-        msgprint("Item %s has been entered twice. Please change description atleast to continue" % d.item_code)
-        raise Exception
-      else:
-        chk_dupl_itm.append([cstr(d.item_code),cstr(d.description)])
+	# Fiscal Year Validation
+	# ----------------------
+	def validate_fiscal_year(self):
+		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Quotation Date')
+	
+	# Does not allow same item code to be entered twice
+	# -------------------------------------------------
+	def validate_for_items(self):
+		chk_dupl_itm = []
+		for d in getlist(self.doclist,'quotation_details'):
+			if [cstr(d.item_code),cstr(d.description)] in chk_dupl_itm:
+				msgprint("Item %s has been entered twice. Please change description atleast to continue" % d.item_code)
+				raise Exception
+			else:
+				chk_dupl_itm.append([cstr(d.item_code),cstr(d.description)])
 
 
-  #do not allow sales item in maintenance quotation and service item in sales quotation
-  #-----------------------------------------------------------------------------------------------
-  def validate_order_type(self):
-    if self.doc.order_type == 'Maintenance':
-      for d in getlist(self.doclist, 'quotation_details'):
-        is_service_item = sql("select is_service_item from `tabItem` where name=%s", d.item_code)
-        is_service_item = is_service_item and is_service_item[0][0] or 'No'
-        
-        if is_service_item == 'No':
-          msgprint("You can not select non service item "+d.item_code+" in Maintenance Quotation")
-          raise Exception
-    else:
-      for d in getlist(self.doclist, 'quotation_details'):
-        is_sales_item = sql("select is_sales_item from `tabItem` where name=%s", d.item_code)
-        is_sales_item = is_sales_item and is_sales_item[0][0] or 'No'
-        
-        if is_sales_item == 'No':
-          msgprint("You can not select non sales item "+d.item_code+" in Sales Quotation")
-          raise Exception
-  
-  #--------------Validation For Last Contact Date-----------------
-  # ====================================================================================================================
-  def set_last_contact_date(self):
-    #if not self.doc.contact_date_ref:
-      #self.doc.contact_date_ref=self.doc.contact_date
-      #self.doc.last_contact_date=self.doc.contact_date_ref
-    if self.doc.contact_date_ref and self.doc.contact_date_ref != self.doc.contact_date:
-      if getdate(self.doc.contact_date_ref) < getdate(self.doc.contact_date):
-        self.doc.last_contact_date=self.doc.contact_date_ref
-      else:
-        msgprint("Contact Date Cannot be before Last Contact Date")
-        raise Exception
-      #set(self.doc, 'contact_date_ref',self.doc.contact_date)
-  
+	#do not allow sales item in maintenance quotation and service item in sales quotation
+	#-----------------------------------------------------------------------------------------------
+	def validate_order_type(self):
+		if self.doc.order_type == 'Maintenance':
+			for d in getlist(self.doclist, 'quotation_details'):
+				is_service_item = sql("select is_service_item from `tabItem` where name=%s", d.item_code)
+				is_service_item = is_service_item and is_service_item[0][0] or 'No'
+				
+				if is_service_item == 'No':
+					msgprint("You can not select non service item "+d.item_code+" in Maintenance Quotation")
+					raise Exception
+		else:
+			for d in getlist(self.doclist, 'quotation_details'):
+				is_sales_item = sql("select is_sales_item from `tabItem` where name=%s", d.item_code)
+				is_sales_item = is_sales_item and is_sales_item[0][0] or 'No'
+				
+				if is_sales_item == 'No':
+					msgprint("You can not select non sales item "+d.item_code+" in Sales Quotation")
+					raise Exception
+	
+	#--------------Validation For Last Contact Date-----------------
+	# ====================================================================================================================
+	def set_last_contact_date(self):
+		#if not self.doc.contact_date_ref:
+			#self.doc.contact_date_ref=self.doc.contact_date
+			#self.doc.last_contact_date=self.doc.contact_date_ref
+		if self.doc.contact_date_ref and self.doc.contact_date_ref != self.doc.contact_date:
+			if getdate(self.doc.contact_date_ref) < getdate(self.doc.contact_date):
+				self.doc.last_contact_date=self.doc.contact_date_ref
+			else:
+				msgprint("Contact Date Cannot be before Last Contact Date")
+				raise Exception
+			#set(self.doc, 'contact_date_ref',self.doc.contact_date)
+	
 
-  # Validate
-  # --------
-  def validate(self):
-    self.validate_fiscal_year()
-    self.validate_mandatory()
-    self.set_last_contact_date()
-    self.validate_order_type()
-    self.validate_for_items()
-    sales_com_obj = get_obj('Sales Common')
-    sales_com_obj.check_active_sales_items(self)
-    sales_com_obj.validate_max_discount(self,'quotation_details') #verify whether rate is not greater than max_discount
-    sales_com_obj.check_conversion_rate(self)
-    
-    # Get total in words
-    dcc = TransactionBase().get_company_currency(self.doc.company)
-    self.doc.in_words = sales_com_obj.get_total_in_words(dcc, self.doc.rounded_total)
-    self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export)
+	# Validate
+	# --------
+	def validate(self):
+		self.validate_fiscal_year()
+		self.validate_mandatory()
+		self.set_last_contact_date()
+		self.validate_order_type()
+		self.validate_for_items()
+		sales_com_obj = get_obj('Sales Common')
+		sales_com_obj.check_active_sales_items(self)
+		sales_com_obj.validate_max_discount(self,'quotation_details') #verify whether rate is not greater than max_discount
+		sales_com_obj.check_conversion_rate(self)
+		
+		# Get total in words
+		dcc = TransactionBase().get_company_currency(self.doc.company)
+		self.doc.in_words = sales_com_obj.get_total_in_words(dcc, self.doc.rounded_total)
+		self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export)
 
-  def on_update(self):
-    # Add to calendar
-    #if self.doc.contact_date and self.doc.last_contact_date != self.doc.contact_date:
-    if self.doc.contact_date and self.doc.contact_date_ref != self.doc.contact_date:
-      if self.doc.contact_by:
-        self.add_calendar_event()
-      set(self.doc, 'contact_date_ref',self.doc.contact_date)
-    
-    # Set Quotation Status
-    set(self.doc, 'status', 'Draft')
+	def on_update(self):
+		# Add to calendar
+		#if self.doc.contact_date and self.doc.last_contact_date != self.doc.contact_date:
+		if self.doc.contact_date and self.doc.contact_date_ref != self.doc.contact_date:
+			if self.doc.contact_by:
+				self.add_calendar_event()
+			set(self.doc, 'contact_date_ref',self.doc.contact_date)
+		
+		# Set Quotation Status
+		set(self.doc, 'status', 'Draft')
 
-    # subject for follow
-    self.doc.subject = '[%(status)s] To %(customer)s worth %(currency)s %(grand_total)s' % self.doc.fields
+		# subject for follow
+		self.doc.subject = '[%(status)s] To %(customer)s worth %(currency)s %(grand_total)s' % self.doc.fields
 
-  
-  # Add to Calendar
-  # ====================================================================================================================
-  def add_calendar_event(self):
-    desc=''
-    user_lst =[]
-    if self.doc.customer:
-      if self.doc.contact_person:
-        desc = 'Contact '+cstr(self.doc.contact_person)
-      else:
-        desc = 'Contact customer '+cstr(self.doc.customer)
-    elif self.doc.lead:
-      if self.doc.lead_name:
-        desc = 'Contact '+cstr(self.doc.lead_name)
-      else:
-        desc = 'Contact lead '+cstr(self.doc.lead)
-    desc = desc+ '.By : ' + cstr(self.doc.contact_by)
-    
-    if self.doc.to_discuss:
-      desc = desc+' To Discuss : ' + cstr(self.doc.to_discuss)
-    
-    ev = Document('Event')
-    ev.description = desc
-    ev.event_date = self.doc.contact_date
-    ev.event_hour = '10:00'
-    ev.event_type = 'Private'
-    ev.ref_type = 'Enquiry'
-    ev.ref_name = self.doc.name
-    ev.save(1)
-    
-    user_lst.append(self.doc.owner)
-    
-    chk = sql("select t1.name from `tabProfile` t1, `tabSales Person` t2 where t2.email_id = t1.name and t2.name=%s",self.doc.contact_by)
-    if chk:
-      user_lst.append(chk[0][0])
-    
-    for d in user_lst:
-      ch = addchild(ev, 'event_individuals', 'Event User', 0)
-      ch.person = d
-      ch.save(1)
-  
-  #update enquiry
-  #------------------
-  def update_enquiry(self, flag):
-    prevdoc=''
-    for d in getlist(self.doclist, 'quotation_details'):
-      if d.prevdoc_docname:
-        prevdoc = d.prevdoc_docname
-    
-    if prevdoc:
-      if flag == 'submit': #on submit
-        sql("update `tabEnquiry` set status = 'Quotation Sent' where name = %s", prevdoc)
-      elif flag == 'cancel': #on cancel
-        sql("update `tabEnquiry` set status = 'Open' where name = %s", prevdoc)
-      elif flag == 'order lost': #order lost
-        sql("update `tabEnquiry` set status = 'Enquiry Lost' where name=%s", prevdoc)
-      elif flag == 'order confirm': #order confirm
-        sql("update `tabEnquiry` set status='Order Confirmed' where name=%s", prevdoc)
-  
-  # declare as order lost
-  #-------------------------
-  def declare_order_lost(self,arg):
-    chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name)
-    if chk:
-      msgprint("Sales Order No. "+cstr(chk[0][0])+" is submitted against this Quotation. Thus 'Order Lost' can not be declared against it.")
-      raise Exception
-    else:
-      set(self.doc, 'status', 'Order Lost')
-      set(self.doc, 'order_lost_reason', arg)
-      self.update_enquiry('order lost')
-      return 'true'
-  
-  #check if value entered in item table
-  #--------------------------------------
-  def check_item_table(self):
-    if not getlist(self.doclist, 'quotation_details'):
-      msgprint("Please enter item details")
-      raise Exception
-    
-  # ON SUBMIT
-  # =========================================================================
-  def on_submit(self):
-    self.check_item_table()
-    if not self.doc.amended_from:
-      set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been sent')
-    else:
-      set(self.doc, 'message', 'Quotation has been amended. New Quotation no:'+self.doc.name)
-    
-    # Check for Approving Authority
-    get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)
+	
+	# Add to Calendar
+	# ====================================================================================================================
+	def add_calendar_event(self):
+		desc=''
+		user_lst =[]
+		if self.doc.customer:
+			if self.doc.contact_person:
+				desc = 'Contact '+cstr(self.doc.contact_person)
+			else:
+				desc = 'Contact customer '+cstr(self.doc.customer)
+		elif self.doc.lead:
+			if self.doc.lead_name:
+				desc = 'Contact '+cstr(self.doc.lead_name)
+			else:
+				desc = 'Contact lead '+cstr(self.doc.lead)
+		desc = desc+ '.By : ' + cstr(self.doc.contact_by)
+		
+		if self.doc.to_discuss:
+			desc = desc+' To Discuss : ' + cstr(self.doc.to_discuss)
+		
+		ev = Document('Event')
+		ev.description = desc
+		ev.event_date = self.doc.contact_date
+		ev.event_hour = '10:00'
+		ev.event_type = 'Private'
+		ev.ref_type = 'Enquiry'
+		ev.ref_name = self.doc.name
+		ev.save(1)
+		
+		user_lst.append(self.doc.owner)
+		
+		chk = sql("select t1.name from `tabProfile` t1, `tabSales Person` t2 where t2.email_id = t1.name and t2.name=%s",self.doc.contact_by)
+		if chk:
+			user_lst.append(chk[0][0])
+		
+		for d in user_lst:
+			ch = addchild(ev, 'event_individuals', 'Event User', 0)
+			ch.person = d
+			ch.save(1)
+	
+	#update enquiry
+	#------------------
+	def update_enquiry(self, flag):
+		prevdoc=''
+		for d in getlist(self.doclist, 'quotation_details'):
+			if d.prevdoc_docname:
+				prevdoc = d.prevdoc_docname
+		
+		if prevdoc:
+			if flag == 'submit': #on submit
+				sql("update `tabEnquiry` set status = 'Quotation Sent' where name = %s", prevdoc)
+			elif flag == 'cancel': #on cancel
+				sql("update `tabEnquiry` set status = 'Open' where name = %s", prevdoc)
+			elif flag == 'order lost': #order lost
+				sql("update `tabEnquiry` set status = 'Enquiry Lost' where name=%s", prevdoc)
+			elif flag == 'order confirm': #order confirm
+				sql("update `tabEnquiry` set status='Order Confirmed' where name=%s", prevdoc)
+	
+	# declare as order lost
+	#-------------------------
+	def declare_order_lost(self,arg):
+		chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name)
+		if chk:
+			msgprint("Sales Order No. "+cstr(chk[0][0])+" is submitted against this Quotation. Thus 'Order Lost' can not be declared against it.")
+			raise Exception
+		else:
+			set(self.doc, 'status', 'Order Lost')
+			set(self.doc, 'order_lost_reason', arg)
+			self.update_enquiry('order lost')
+			return 'true'
+	
+	#check if value entered in item table
+	#--------------------------------------
+	def check_item_table(self):
+		if not getlist(self.doclist, 'quotation_details'):
+			msgprint("Please enter item details")
+			raise Exception
+		
+	# ON SUBMIT
+	# =========================================================================
+	def on_submit(self):
+		self.check_item_table()
+		if not self.doc.amended_from:
+			set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been sent')
+		else:
+			set(self.doc, 'message', 'Quotation has been amended. New Quotation no:'+self.doc.name)
+		
+		# Check for Approving Authority
+		get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)
 
-    # Set Quotation Status
-    set(self.doc, 'status', 'Submitted')
-    
-    #update enquiry status
-    self.update_enquiry('submit')
-    
-    
+		# Set Quotation Status
+		set(self.doc, 'status', 'Submitted')
+		
+		#update enquiry status
+		self.update_enquiry('submit')
+		
+		
 # ON CANCEL
 # ==========================================================================
-  def on_cancel(self):
-    set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been cancelled')
-    
-    #update enquiry status
-    self.update_enquiry('cancel')
-    
-    set(self.doc,'status','Cancelled')
-    
-  
+	def on_cancel(self):
+		set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been cancelled')
+		
+		#update enquiry status
+		self.update_enquiry('cancel')
+		
+		set(self.doc,'status','Cancelled')
+		
+	
 # SEND SMS
 # =============================================================================
-  def send_sms(self):
-    if not self.doc.customer_mobile_no:
-      msgprint("Please enter customer mobile no")
-    elif not self.doc.message:
-      msgprint("Please enter the message you want to send")
-    else:
-      msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.contact_mobile,], self.doc.message))
-  
+	def send_sms(self):
+		if not self.doc.customer_mobile_no:
+			msgprint("Please enter customer mobile no")
+		elif not self.doc.message:
+			msgprint("Please enter the message you want to send")
+		else:
+			msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.contact_mobile,], self.doc.message))
+	
 # Print other charges
 # ===========================================================================
-  def print_other_charges(self,docname):
-    print_lst = []
-    for d in getlist(self.doclist,'other_charges'):
-      lst1 = []
-      lst1.append(d.description)
-      lst1.append(d.total)
-      print_lst.append(lst1)
-    return print_lst
-  
-  def update_followup_details(self):
-    sql("delete from `tabFollow up` where parent = '%s'"%self.doc.name)
-    for d in getlist(self.doclist, 'follow_up'):
-      d.save()
+	def print_other_charges(self,docname):
+		print_lst = []
+		for d in getlist(self.doclist,'other_charges'):
+			lst1 = []
+			lst1.append(d.description)
+			lst1.append(d.total)
+			print_lst.append(lst1)
+		return print_lst
+	
+	def update_followup_details(self):
+		sql("delete from `tabFollow up` where parent = '%s'"%self.doc.name)
+		for d in getlist(self.doclist, 'follow_up'):
+			d.save()
diff --git a/erpnext/selling/doctype/sales_common/sales_common.js b/erpnext/selling/doctype/sales_common/sales_common.js
index 5039fcd..57f379c 100644
--- a/erpnext/selling/doctype/sales_common/sales_common.js
+++ b/erpnext/selling/doctype/sales_common/sales_common.js
@@ -7,11 +7,47 @@
 
 // ============== Load Default Taxes ===================
 cur_frm.cscript.load_taxes = function(doc, cdt, cdn) {
-  // run if this is not executed from dt_map...
-  if(doc.customer) return;
-  $c_obj([doc],'load_default_taxes','',function(r,rt){
-     refresh_field('other_charges');
-  });
+	// run if this is not executed from dt_map...
+	if(doc.customer) return;
+	$c_obj([doc],'load_default_taxes','',function(r,rt){
+		 refresh_field('other_charges');
+	});
+}
+
+
+// Gets called after existing item details are update to fill in
+// remaining default values
+cur_frm.cscript.load_defaults = function(doc, dt, dn) {
+	if(!cur_frm.doc.__islocal) { return; }
+
+	doc = locals[doc.doctype][doc.name];
+	var fields_to_refresh = LocalDB.set_default_values(doc);
+	if(fields_to_refresh) { refresh_many(fields_to_refresh); }
+
+	fields_to_refresh = null;
+	var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(!children) { return; }
+	for(var i=0; i<children.length; i++) {
+		LocalDB.set_default_values(children[i]);
+	}
+	refresh_field(cur_frm.cscript.fname);
+}
+
+
+// Update existing item details
+cur_frm.cscript.update_item_details = function(doc, dt, dn) {
+	if(!cur_frm.doc.__islocal) return;
+	var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(children) {
+		$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_details', '',
+		function(r, rt) {
+			if(!r.exc) {
+				refresh_field(cur_frm.cscript.fname);
+				doc = locals[doc.doctype][doc.name];
+				cur_frm.cscript.load_defaults(doc, dt, dn);
+			}
+		});
+	}
 }
 
 
@@ -26,28 +62,28 @@
 
 // ============== Customer and its primary contact Details ============================
 cur_frm.cscript.customer = function(doc, cdt, cdn) {
-  if(doc.customer){
-    if (!doc.company) {
-      msgprint("Please select company to proceed");
-      doc.customer = '';
-      refresh_field('customer');
-    } else {
-      var callback = function(r, rt){
-	    	cur_frm.refresh();
-      }
-      $c_obj(make_doclist(doc.doctype, doc.name), 'get_customer_details', '',callback);
-    }
-  }
+	if(doc.customer){
+		if (!doc.company) {
+			msgprint("Please select company to proceed");
+			doc.customer = '';
+			refresh_field('customer');
+		} else {
+			var callback = function(r, rt){
+				cur_frm.refresh();
+			}
+			$c_obj(make_doclist(doc.doctype, doc.name), 'get_customer_details', '',callback);
+		}
+	}
 }
 
 //====================opens territory tree page ==================
 cur_frm.cscript.TerritoryHelp = function(doc,dt,dn){
-  var call_back = function(){
+	var call_back = function(){
 
-    var sb_obj = new SalesBrowser();        
-    sb_obj.set_val('Territory');
-  }
-  loadpage('Sales Browser',call_back);
+		var sb_obj = new SalesBrowser();				
+		sb_obj.set_val('Territory');
+	}
+	loadpage('Sales Browser',call_back);
 }
 
 //====================opens customer group tree page ==================
@@ -64,7 +100,7 @@
 // =====================================================================================================
 
 // ********************* CURRENCY ******************************
-cur_frm.cscript.currency = function(doc, cdt, cdn) {     
+cur_frm.cscript.currency = function(doc, cdt, cdn) {		 
 	cur_frm.cscript.price_list_name(doc, cdt, cdn);
 }
 
@@ -76,54 +112,54 @@
 
 // ******************** PRICE LIST ******************************
 cur_frm.cscript.price_list_name = function(doc, cdt, cdn) {
-  var fname = cur_frm.cscript.fname;
-  var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
-  if(doc.price_list_name && doc.currency && doc.price_list_currency && doc.conversion_rate && doc.plc_conversion_rate && cl.length) {
-    $c_obj(make_doclist(doc.doctype, doc.name), 'get_adj_percent', '',
-      function(r, rt) {
-        refresh_field(fname);
-        var doc = locals[cdt][cdn];
-        cur_frm.cscript.recalc(doc,3);    //this is to re-calculate BASIC RATE and AMOUNT on basis of changed REF RATE
-      }
-    );
-  }
+	var fname = cur_frm.cscript.fname;
+	var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(doc.price_list_name && doc.currency && doc.price_list_currency && doc.conversion_rate && doc.plc_conversion_rate && cl.length) {
+		$c_obj(make_doclist(doc.doctype, doc.name), 'get_adj_percent', '',
+			function(r, rt) {
+				refresh_field(fname);
+				var doc = locals[cdt][cdn];
+				cur_frm.cscript.recalc(doc,3);		//this is to re-calculate BASIC RATE and AMOUNT on basis of changed REF RATE
+			}
+		);
+	}
 }
 
 
 
 // ******************** ITEM CODE ******************************** 
 cur_frm.fields_dict[cur_frm.cscript.fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-  if (doc.order_type == 'Maintenance')
-    return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
-  else 
-    return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+	if (doc.order_type == 'Maintenance')
+		return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+	else 
+		return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
 }
 
 
 cur_frm.cscript.item_code = function(doc, cdt, cdn) {
-  var fname = cur_frm.cscript.fname;
-  var d = locals[cdt][cdn];
-  if (d.item_code) {
-    if (!doc.company) {
-      msgprint("Please select company to proceed");
-      d.item_code = '';
-      refresh_field('item_code', d.name, fname);
-    } else {
-      var callback = function(r, rt){
-        cur_frm.cscript.recalc(doc, 1);
-      }
-      get_server_fields('get_item_details',d.item_code, fname,doc,cdt,cdn,1,callback);
-    }
-  }
-  if(cur_frm.cscript.custom_item_code){
-  	cur_frm.cscript.custom_item_code(doc, cdt, cdn);
-  }
+	var fname = cur_frm.cscript.fname;
+	var d = locals[cdt][cdn];
+	if (d.item_code) {
+		if (!doc.company) {
+			msgprint("Please select company to proceed");
+			d.item_code = '';
+			refresh_field('item_code', d.name, fname);
+		} else {
+			var callback = function(r, rt){
+				cur_frm.cscript.recalc(doc, 1);
+			}
+			get_server_fields('get_item_details',d.item_code, fname,doc,cdt,cdn,1,callback);
+		}
+	}
+	if(cur_frm.cscript.custom_item_code){
+		cur_frm.cscript.custom_item_code(doc, cdt, cdn);
+	}
 }
 
 
 // *********************** QUANTITY ***************************
 cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); }
-  
+	
 // ************************ DISCOUNT (%) ***********************
 cur_frm.cscript.adj_rate = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); }
 
@@ -171,7 +207,7 @@
 	var cur_rec = locals[cdt][cdn];
 	var fname = cur_frm.cscript.fname;
 	var tname = cur_frm.cscript.tname;
-	if(flt(cur_rec.ref_rate)>0 && flt(cur_rec.export_rate)>0 && !flt(cur_rec.adj_rate)) {
+	if(flt(cur_rec.ref_rate)>0 && flt(cur_rec.export_rate)>0) {
 		var adj_rate = 100 * (1 - (flt(cur_rec.export_rate) / flt(cur_rec.ref_rate)));
 		set_multiple(tname, cur_rec.name, { 'adj_rate': adj_rate }, fname);
 	}
@@ -183,59 +219,59 @@
 
 // ************* GET OTHER CHARGES BASED ON COMPANY *************
 cur_frm.fields_dict.charge.get_query = function(doc) {
-  return 'SELECT DISTINCT `tabOther Charges`.name FROM `tabOther Charges` WHERE `tabOther Charges`.company = "'+doc.company+'" AND `tabOther Charges`.company is not NULL AND `tabOther Charges`.docstatus != 2 AND `tabOther Charges`.%(key)s LIKE "%s" ORDER BY `tabOther Charges`.name LIMIT 50';
+	return 'SELECT DISTINCT `tabOther Charges`.name FROM `tabOther Charges` WHERE `tabOther Charges`.company = "'+doc.company+'" AND `tabOther Charges`.company is not NULL AND `tabOther Charges`.docstatus != 2 AND `tabOther Charges`.%(key)s LIKE "%s" ORDER BY `tabOther Charges`.name LIMIT 50';
 }
 
 // ********************* Get Charges ****************************
 cur_frm.cscript['Get Charges'] = function(doc, cdt, cdn) {
-   $c_obj(make_doclist(doc.doctype,doc.name),'get_other_charges','', function(r, rt) { cur_frm.cscript['Calculate Charges'](doc, cdt, cdn);});
+	$c_obj(make_doclist(doc.doctype,doc.name),'get_other_charges','', function(r, rt) { cur_frm.cscript['Calculate Charges'](doc, cdt, cdn);});
 }
 
 
 // CALCULATION OF TOTAL AMOUNTS
 // ======================================================================================================== 
 cur_frm.cscript.recalc = function(doc, n) {
-  if(!n)n=0;
-  doc = locals[doc.doctype][doc.name];
-  var tname = cur_frm.cscript.tname;
-  var fname = cur_frm.cscript.fname;
-  var sales_team = cur_frm.cscript.sales_team_fname;
-  var other_fname  = cur_frm.cscript.other_fname;
-  
-  if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
-  if(!flt(doc.plc_conversion_rate)) { doc.plc_conversion_rate = 1; refresh_field('plc_conversion_rate'); }
+	if(!n)n=0;
+	doc = locals[doc.doctype][doc.name];
+	var tname = cur_frm.cscript.tname;
+	var fname = cur_frm.cscript.fname;
+	var sales_team = cur_frm.cscript.sales_team_fname;
+	var other_fname	= cur_frm.cscript.other_fname;
+	
+	if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
+	if(!flt(doc.plc_conversion_rate)) { doc.plc_conversion_rate = 1; refresh_field('plc_conversion_rate'); }
 
-  if(n > 0) cur_frm.cscript.update_fname_table(doc , tname , fname , n, other_fname); // updates all values in table (i.e. amount, export amount, net total etc.)
-  
-  if(flt(doc.net_total) > 0) {
-    var cl = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
-    for(var i = 0; i<cl.length; i++){
-      cl[i].total_tax_amount = 0;
-      cl[i].total_amount = 0;
-      cl[i].tax_amount = 0;                    // this is done to calculate other charges
-      cl[i].total = 0;
-      cl[i].item_wise_tax_detail = "";
-      if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
-        alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
-        validated = false;
-      }
-    }
-    cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
-  }
-  cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
+	if(n > 0) cur_frm.cscript.update_fname_table(doc , tname , fname , n, other_fname); // updates all values in table (i.e. amount, export amount, net total etc.)
+	
+	if(flt(doc.net_total) > 0) {
+		var cl = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
+		for(var i = 0; i<cl.length; i++){
+			cl[i].total_tax_amount = 0;
+			cl[i].total_amount = 0;
+			cl[i].tax_amount = 0;										// this is done to calculate other charges
+			cl[i].total = 0;
+			cl[i].item_wise_tax_detail = "";
+			if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
+				alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
+				validated = false;
+			}
+		}
+		cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
+	}
+	cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
 
-  // ******************* calculate allocated amount of sales person ************************
-  cl = getchildren('Sales Team', doc.name, sales_team);
-  for(var i=0;i<cl.length;i++) {
-    if (cl[i].allocated_percentage) {
-      cl[i].allocated_amount = flt(flt(doc.net_total)*flt(cl[i].allocated_percentage)/100);
-      refresh_field('allocated_amount', cl[i].name, sales_team);
-    }
-  }
-  doc.in_words = '';
-  doc.in_words_export = '';
-  refresh_many(['total_discount_rate','total_discount','net_total','total_commission','grand_total','rounded_total','grand_total_export','rounded_total_export','in_words','in_words_export','other_charges','other_charges_total']);
-  if(cur_frm.cscript.custom_recalc)cur_frm.cscript.custom_recalc(doc);
+	// ******************* calculate allocated amount of sales person ************************
+	cl = getchildren('Sales Team', doc.name, sales_team);
+	for(var i=0;i<cl.length;i++) {
+		if (cl[i].allocated_percentage) {
+			cl[i].allocated_amount = flt(flt(doc.net_total)*flt(cl[i].allocated_percentage)/100);
+			refresh_field('allocated_amount', cl[i].name, sales_team);
+		}
+	}
+	doc.in_words = '';
+	doc.in_words_export = '';
+	refresh_many(['total_discount_rate','total_discount','net_total','total_commission','grand_total','rounded_total','grand_total_export','rounded_total_export','in_words','in_words_export','other_charges','other_charges_total']);
+	if(cur_frm.cscript.custom_recalc)cur_frm.cscript.custom_recalc(doc);
 }
 
 // ******* Calculation of total amounts of document (item amount + other charges)****************
@@ -282,27 +318,32 @@
 
 	var cl = getchildren(tname, doc.name, fname);
 	var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
-  
+	
 	// Make display table
 	var otc = make_table(cur_frm.fields_dict['Other Charges Calculation'].disp_area,
 		cl.length + 1, tax.length + 1, '90%', [], { border:'1px solid #AAA', padding:'2px' });
 	$y(otc,{marginTop:'8px'});
 
 	var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
-  
+	
 	for(var i=0;i<cl.length;i++) {
 		net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate));
 		var prev_total = flt(cl[i].amount);
-		if(cl[i].item_tax_rate)
-			var check_tax = eval('var a='+cl[i].item_tax_rate+';a');        //to get in dictionary
-    
+		if(cl[i].item_tax_rate) {
+			try {
+				var check_tax = JSON.parse(cl[i].item_tax_rate);				//to get in dictionary
+			} catch(exception) {
+				var check_tax = eval('var a='+cl[i].item_tax_rate+';a');        //to get in dictionary
+			}
+		}
+		
 		// Add Item Code in new Row
 		$td(otc,i+1,0).innerHTML = cl[i].item_code ? cl[i].item_code : cl[i].description;
-    
+		
 		//var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
 		var total = net_total;
-    
-    
+		
+		
 		for(var t=0;t<tax.length;t++){
 			var account = tax[t].account_head;
 			$td(otc,0,t+1).innerHTML = account?account:'';
@@ -320,14 +361,14 @@
 			//enter item_wise_tax_detail i.e. tax rate on each item
 			var item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail(doc, rate, cl, i, tax, t);
 			if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
-			tax[t].total_amount = flt(tax_amount);     //stores actual tax amount in virtual field
-			tax[t].total_tax_amount = flt(prev_total);      //stores total amount in virtual field
-			tax[t].tax_amount += flt(tax_amount);       
+			tax[t].total_amount = flt(tax_amount);		 //stores actual tax amount in virtual field
+			tax[t].total_tax_amount = flt(prev_total);			//stores total amount in virtual field
+			tax[t].tax_amount += flt(tax_amount);			 
 			var total_amount = flt(tax[t].tax_amount);
 			total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
 			set_multiple('RV Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':roundNumber(flt(total_amount), 2), 'total':roundNumber(flt(total)+flt(tax[t].tax_amount), 2)}, other_fname);
-			prev_total += flt(tax[t].total_amount);   // for previous row total
-			total += flt(tax[t].tax_amount);     // for adding total to previous amount
+			prev_total += flt(tax[t].total_amount);	 // for previous row total
+			total += flt(tax[t].tax_amount);		 // for adding total to previous amount
 
 			if(tax[t].charge_type == 'Actual')
 				$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
@@ -342,55 +383,55 @@
 	}
 }
 cur_frm.cscript.check_charge_type_and_get_tax_amount = function( doc, tax, t, cl, rate, print_amt) {
-  doc = locals[doc.doctype][doc.name];
-  if (! print_amt) print_amt = 0;
-  var tax_amount = 0;
-  if(tax[t].charge_type == 'Actual') {
-    var value = flt(tax[t].rate) / flt(doc.net_total);   // this give the ratio in which all items are divided           
-    return tax_amount = flt(value) * flt(cl.amount);
-   }   
-  else if(tax[t].charge_type == 'On Net Total') {
-    if (flt(print_amt) == 1) {
-      doc.excise_rate = flt(rate);
-      doc.total_excise_rate += flt(rate);
-      refresh_field('excise_rate');
-      refresh_field('total_excise_rate');
-      return
-    }
+	doc = locals[doc.doctype][doc.name];
+	if (! print_amt) print_amt = 0;
+	var tax_amount = 0;
+	if(tax[t].charge_type == 'Actual') {
+		var value = flt(tax[t].rate) / flt(doc.net_total);	 // this give the ratio in which all items are divided					 
+		return tax_amount = flt(value) * flt(cl.amount);
+	 }	 
+	else if(tax[t].charge_type == 'On Net Total') {
+		if (flt(print_amt) == 1) {
+			doc.excise_rate = flt(rate);
+			doc.total_excise_rate += flt(rate);
+			refresh_field('excise_rate');
+			refresh_field('total_excise_rate');
+			return
+		}
 	return tax_amount = (flt(rate) * flt(cl.amount) / 100);
-  }
-  else if(tax[t].charge_type == 'On Previous Row Amount'){
-    if(flt(print_amt) == 1) {
-      doc.total_excise_rate += flt(flt(doc.excise_rate) * 0.01 * flt(rate));
-      refresh_field('total_excise_rate');
-      return
-    }
-    var row_no = (tax[t].row_id).toString();
-    var row = (row_no).split("+");      // splits the values and stores in an array
-    for(var r = 0;r<row.length;r++){
-      var id = cint(row[r].replace(/^\s+|\s+$/g,""));
-      tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
-    }
-    var row_id = row_no.indexOf("/");
-    if(row_id != -1) {
-      rate = '';
-      var row = (row_no).split("/");      // splits the values and stores in an array
-      if(row.length>2) alert("You cannot enter more than 2 nos. for division");
-      var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
-      var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
-      tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
-    }
-    return tax_amount
-  }
-  else if(tax[t].charge_type == 'On Previous Row Total') {
-    if(flt(print_amt) == 1) {
-      doc.sales_tax_rate += flt(rate);
-      refresh_field('sales_tax_rate');
-      return
-    }
-    var row = cint(tax[t].row_id);
-    return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
-  }
+	}
+	else if(tax[t].charge_type == 'On Previous Row Amount'){
+		if(flt(print_amt) == 1) {
+			doc.total_excise_rate += flt(flt(doc.excise_rate) * 0.01 * flt(rate));
+			refresh_field('total_excise_rate');
+			return
+		}
+		var row_no = (tax[t].row_id).toString();
+		var row = (row_no).split("+");			// splits the values and stores in an array
+		for(var r = 0;r<row.length;r++){
+			var id = cint(row[r].replace(/^\s+|\s+$/g,""));
+			tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
+		}
+		var row_id = row_no.indexOf("/");
+		if(row_id != -1) {
+			rate = '';
+			var row = (row_no).split("/");			// splits the values and stores in an array
+			if(row.length>2) alert("You cannot enter more than 2 nos. for division");
+			var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
+			var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
+			tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
+		}
+		return tax_amount
+	}
+	else if(tax[t].charge_type == 'On Previous Row Total') {
+		if(flt(print_amt) == 1) {
+			doc.sales_tax_rate += flt(rate);
+			refresh_field('sales_tax_rate');
+			return
+		}
+		var row = cint(tax[t].row_id);
+		return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
+	}
 }
 
 // ********************** Functions for inclusive value calc ******************************
@@ -409,8 +450,11 @@
 cur_frm.cscript.back_calc_basic_rate = function(doc, tname, fname, child, other_fname) {	
 	var get_item_tax_rate = function(item, tax) {
 		if(item.item_tax_rate) {
-			// Should to replace eval with JSON.parse when item_tax_rate is converted to json string notation
-			var item_tax = eval('var a='+item.item_tax_rate+';a');
+			try {
+				var item_tax = JSON.parse(item.item_tax_rate);
+			} catch(exception) {
+				var item_tax = eval('var a='+item.item_tax_rate+';a');
+			}
 			if(item_tax[tax.account_head]!=null) {
 				return flt(item_tax[tax.account_head]);
 			}
@@ -524,45 +568,45 @@
 				'base_ref_rate': flt(base_ref_rate)
 			}, fname);
 		}
-    }
-    else if(n == 2){
-      if(flt(cl[i].ref_rate) > 0)
-        set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].basic_rate)  * 100 / (flt(cl[i].ref_rate) * flt(doc.conversion_rate)))}, fname);
-      set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i].basic_rate)), 'export_rate': flt(flt(cl[i].basic_rate) / flt(doc.conversion_rate)), 'export_amount': flt((flt(cl[i].basic_rate) / flt(doc.conversion_rate)) * flt(cl[i].qty)) }, fname);
-    }
-    /*else if(n == 3){
-      set_multiple(tname, cl[i].name, {'basic_rate': flt(flt(cl[i].export_rate) * flt(doc.conversion_rate))}, fname);
-      set_multiple(tname, cl[i].name, {'amount' : flt(flt(cl[i].basic_rate) * flt(cl[i].qty)), 'export_amount': flt(flt(cl[i].export_rate) * flt(cl[i].qty))}, fname);
-      if(cl[i].ref_rate > 0)
+		}
+		else if(n == 2){
+			if(flt(cl[i].ref_rate) > 0)
+				set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].basic_rate)	* 100 / (flt(cl[i].ref_rate) * flt(doc.conversion_rate)))}, fname);
+			set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i].basic_rate)), 'export_rate': flt(flt(cl[i].basic_rate) / flt(doc.conversion_rate)), 'export_amount': flt((flt(cl[i].basic_rate) / flt(doc.conversion_rate)) * flt(cl[i].qty)) }, fname);
+		}
+		/*else if(n == 3){
+			set_multiple(tname, cl[i].name, {'basic_rate': flt(flt(cl[i].export_rate) * flt(doc.conversion_rate))}, fname);
+			set_multiple(tname, cl[i].name, {'amount' : flt(flt(cl[i].basic_rate) * flt(cl[i].qty)), 'export_amount': flt(flt(cl[i].export_rate) * flt(cl[i].qty))}, fname);
+			if(cl[i].ref_rate > 0)
 		set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].export_rate) * 100 / flt(cl[i].ref_rate)), 'base_ref_rate': flt(flt(cl[i].ref_rate) * flt(doc.conversion_rate)) }, fname);
-    }*/
-    net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate));
-  }
-  doc.net_total = net_total;
-  refresh_field('net_total');
+		}*/
+		net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate));
+	}
+	doc.net_total = net_total;
+	refresh_field('net_total');
 }
 
 cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) {
-  doc = locals[doc.doctype][doc.name];
-  var detail = '';
-  detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
-  return detail;
+	doc = locals[doc.doctype][doc.name];
+	var detail = '';
+	detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
+	return detail;
 }
 
 // **************** RE-CALCULATE VALUES ***************************
 
-cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) {  
-  cur_frm.cscript['Calculate Charges'](doc,cdt,cdn);
+cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) {	
+	cur_frm.cscript['Calculate Charges'](doc,cdt,cdn);
 }
 
 cur_frm.cscript['Calculate Charges'] = function(doc, cdt, cdn) {
-	var other_fname  = cur_frm.cscript.other_fname;
+	var other_fname	= cur_frm.cscript.other_fname;
 
 	var cl = getchildren('RV Tax Detail', doc.name, other_fname, doc.doctype);
 	for(var i = 0; i<cl.length; i++){
 		cl[i].total_tax_amount = 0;
 		cl[i].total_amount = 0;
-		cl[i].tax_amount = 0;                    // this is done to calculate other charges
+		cl[i].tax_amount = 0;										// this is done to calculate other charges
 		cl[i].total = 0;
 		if(in_list(['On Previous Row Amount','On Previous Row Total'], cl[i].charge_type)) { 
 			if(!cl[i].row_id){
@@ -586,71 +630,71 @@
 // Get Sales Partner Commission
 // =================================================================================
 cur_frm.cscript.sales_partner = function(doc, cdt, cdn){
-  if(doc.sales_partner){
+	if(doc.sales_partner){
 
-    get_server_fields('get_comm_rate', doc.sales_partner, '', doc, cdt, cdn, 1);
-  }
+		get_server_fields('get_comm_rate', doc.sales_partner, '', doc, cdt, cdn, 1);
+	}
 }
 
 // *******Commission Rate Trigger (calculates total commission amount)*********
 cur_frm.cscript.commission_rate = function(doc, cdt, cdn) {
-  if(doc.commission_rate > 100){
-    alert("Commision rate cannot be greater than 100.");
-    doc.total_commission = 0;
-    doc.commission_rate = 0;
-  }
-  else
-    doc.total_commission = doc.net_total * doc.commission_rate / 100;
-  refresh_many(['total_commission','commission_rate']);
+	if(doc.commission_rate > 100){
+		alert("Commision rate cannot be greater than 100.");
+		doc.total_commission = 0;
+		doc.commission_rate = 0;
+	}
+	else
+		doc.total_commission = doc.net_total * doc.commission_rate / 100;
+	refresh_many(['total_commission','commission_rate']);
 
 }
 
 // *******Total Commission Trigger (calculates commission rate)*********
 cur_frm.cscript.total_commission = function(doc, cdt, cdn) {
-  if(doc.net_total){
-    if(doc.net_total < doc.total_commission){
-      alert("Total commission cannot be greater than net total.");
-      doc.total_commission = 0;
-      doc.commission_rate = 0;
-    }
-    else
-      doc.commission_rate = doc.total_commission * 100 / doc.net_total;
-    refresh_many(['total_commission','commission_rate']);
-  }
+	if(doc.net_total){
+		if(doc.net_total < doc.total_commission){
+			alert("Total commission cannot be greater than net total.");
+			doc.total_commission = 0;
+			doc.commission_rate = 0;
+		}
+		else
+			doc.commission_rate = doc.total_commission * 100 / doc.net_total;
+		refresh_many(['total_commission','commission_rate']);
+	}
 }
 // Sales Person Allocated % trigger 
 // ==============================================================================
 cur_frm.cscript.allocated_percentage = function(doc, cdt, cdn) {
-  var fname = cur_frm.cscript.sales_team_fname;
-  var d = locals[cdt][cdn];
-  if (d.allocated_percentage) {
-    d.allocated_amount = flt(flt(doc.net_total)*flt(d.allocated_percentage)/100);
-    refresh_field('allocated_amount', d.name, fname);
-  }
+	var fname = cur_frm.cscript.sales_team_fname;
+	var d = locals[cdt][cdn];
+	if (d.allocated_percentage) {
+		d.allocated_amount = flt(flt(doc.net_total)*flt(d.allocated_percentage)/100);
+		refresh_field('allocated_amount', d.name, fname);
+	}
 }
 
 // Client Side Validation
 // =================================================================================
 cur_frm.cscript.validate = function(doc, cdt, cdn) {
-  cur_frm.cscript.validate_items(doc);
-  var cl = getchildren('Other Charges', doc.name, 'other_charges');
-  for(var i =0;i<cl.length;i++) {
-    if(!cl[i].amount) {
-      alert("Please Enter Amount in Row no. "+cl[i].idx+" in Other Charges table");
-      validated = false;
-    }
-  }
-  cur_frm.cscript['Calculate Charges'] (doc, cdt, cdn);
+	cur_frm.cscript.validate_items(doc);
+	var cl = getchildren('Other Charges', doc.name, 'other_charges');
+	for(var i =0;i<cl.length;i++) {
+		if(!cl[i].amount) {
+			alert("Please Enter Amount in Row no. "+cl[i].idx+" in Other Charges table");
+			validated = false;
+		}
+	}
+	cur_frm.cscript['Calculate Charges'] (doc, cdt, cdn);
 
-  if (cur_frm.cscript.calc_adjustment_amount) cur_frm.cscript.calc_adjustment_amount(doc);
+	if (cur_frm.cscript.calc_adjustment_amount) cur_frm.cscript.calc_adjustment_amount(doc);
 }
 
 
 // ************** Atleast one item in document ****************
 cur_frm.cscript.validate_items = function(doc) {
-  var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
-  if(!cl.length){
-    alert("Please enter Items for " + doc.doctype);
-    validated = false;
-  }
+	var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
+	if(!cl.length){
+		alert("Please enter Items for " + doc.doctype);
+		validated = false;
+	}
 }
diff --git a/erpnext/selling/doctype/sales_common/sales_common.py b/erpnext/selling/doctype/sales_common/sales_common.py
index 0c3d858..1420ad6 100644
--- a/erpnext/selling/doctype/sales_common/sales_common.py
+++ b/erpnext/selling/doctype/sales_common/sales_common.py
@@ -109,10 +109,11 @@
 	# Get Item Details
 	# ===============================================================
 	def get_item_details(self, item_code, obj):
+		import json
 		if not obj.doc.price_list_name:
 			msgprint("Please Select Price List before selecting Items")
 			raise Exception
-		item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life >	now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" %(item_code), as_dict=1)
+		item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life >	now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" % (item_code), as_dict=1)
 		tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code)
 		t = {}
 		for x in tax: t[x[0]] = flt(x[1])
@@ -130,7 +131,7 @@
 			'adj_rate'				: 0,
 			'amount'				: 0,
 			'export_amount'			: 0,
-			'item_tax_rate'			: str(t),
+			'item_tax_rate'			: json.dumps(t),
 			'batch_no'				: ''
 		}
 		if(obj.doc.price_list_name and item):	#this is done to fetch the changed BASIC RATE and REF RATE based on PRICE LIST
diff --git a/erpnext/selling/doctype/sales_order/sales_order.js b/erpnext/selling/doctype/sales_order/sales_order.js
index 0229074..59f8b84 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.js
+++ b/erpnext/selling/doctype/sales_order/sales_order.js
@@ -14,111 +14,114 @@
 // ONLOAD
 // ================================================================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
-  if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-  if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
-  if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
-  // load default charges
-  
-  if(doc.__islocal){
-    hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
-  }
+	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
+	if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
+	if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
+	// load default charges
+	
+	if(doc.__islocal){
+		hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
+	}
+
+	// defined in sales_common.js
+	cur_frm.cscript.update_item_details(doc, cdt, cdn);
 }
 
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
-  if(doc.__islocal) {
-    if(doc.quotation) cur_frm.cscript['Pull Quotation Details'](doc,cdt,cdn);
-  } else {
+	if(doc.__islocal) {
+		if(doc.quotation) cur_frm.cscript['Pull Quotation Details'](doc,cdt,cdn);
+	} else {
 	cur_frm.cscript.load_taxes(doc, cdt, cdn);
-  }
+	}
 }
 
 // Refresh
 //==================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-  cur_frm.clear_custom_buttons();
-  
-  if(doc.docstatus==1) {
-  	if(doc.status != 'Stopped') {
-	    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-  	  // delivery note
-  	  if(doc.per_delivered < 100 && doc.order_type!='Maintenance')
-        cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']);
-  	  
-  	  // maintenance
-  	  if(doc.per_delivered < 100 && doc.order_type=='Maintenance') {
-        cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript['Make Maintenance Visit']);
-        cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']);
-  	  }
+	cur_frm.clear_custom_buttons();
+	
+	if(doc.docstatus==1) {
+		if(doc.status != 'Stopped') {
+			cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+			// delivery note
+			if(doc.per_delivered < 100 && doc.order_type!='Maintenance')
+				cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']);
+			
+			// maintenance
+			if(doc.per_delivered < 100 && doc.order_type=='Maintenance') {
+				cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript['Make Maintenance Visit']);
+				cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']);
+			}
 
-      // indent
-      if(doc.order_type != 'Maintenance')
-        cur_frm.add_custom_button('Make ' + get_doctype_label('Indent'), cur_frm.cscript['Make Purchase Requisition']);
-  	  
-      // sales invoice
-  	  if(doc.per_billed < 100)
-        cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
-      
-      // stop
-      if(doc.per_delivered < 100 || doc.per_billed < 100)
-        cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']);
-  } else {
-  	
-  	  // un-stop
-  	  cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']);
-  }
-  	
-    unhide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
-  } else {
-  	hide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
-  }
+			// indent
+			if(doc.order_type != 'Maintenance')
+				cur_frm.add_custom_button('Make ' + get_doctype_label('Indent'), cur_frm.cscript['Make Purchase Requisition']);
+			
+			// sales invoice
+			if(doc.per_billed < 100)
+				cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
+			
+			// stop
+			if(doc.per_delivered < 100 || doc.per_billed < 100)
+				cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']);
+	} else {
+		
+			// un-stop
+			cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']);
+	}
+		
+		unhide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
+	} else {
+		hide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
+	}
 }
 
 //customer
 cur_frm.cscript.customer = function(doc,dt,dn) {
-  var callback = function(r,rt) {
-      var doc = locals[cur_frm.doctype][cur_frm.docname];
-      get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
-      cur_frm.refresh();
-  }   
+	var callback = function(r,rt) {
+			var doc = locals[cur_frm.doctype][cur_frm.docname];
+			get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
+			cur_frm.refresh();
+	}	 
 
-  if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
-  if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
+	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
+	if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
 }
 
-cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {    
-  if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
+	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict.customer_address.on_new = function(dn) {
-  locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.cscript['Pull Quotation Details'] = function(doc,dt,dn) {
-  var callback = function(r,rt){
-    var doc = locals[cur_frm.doctype][cur_frm.docname];          
-    if(r.message){              
-      doc.quotation_no = r.message;      
-		  if(doc.quotation_no) {		      
-  			  unhide_field(['quotation_date','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);			    			  
-  			  if(doc.customer) get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
-		  }		  
-		  cur_frm.refresh();
-    }
-  } 
+	var callback = function(r,rt){
+		var doc = locals[cur_frm.doctype][cur_frm.docname];					
+		if(r.message){							
+			doc.quotation_no = r.message;			
+			if(doc.quotation_no) {					
+					unhide_field(['quotation_date','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);									
+					if(doc.customer) get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
+			}			
+			cur_frm.refresh();
+		}
+	} 
 
  $c_obj(make_doclist(doc.doctype, doc.name),'pull_quotation_details','',callback);
 }
@@ -126,10 +129,10 @@
 
 //================ create new contact ============================================================================
 cur_frm.cscript.new_contact = function(){
-  tn = createLocal('Contact');
-  locals['Contact'][tn].is_customer = 1;
-  if(doc.customer) locals['Contact'][tn].customer = doc.customer;
-  loaddoc('Contact', tn);
+	tn = createLocal('Contact');
+	locals['Contact'][tn].is_customer = 1;
+	if(doc.customer) locals['Contact'][tn].customer = doc.customer;
+	loaddoc('Contact', tn);
 }
 
 // DOCTYPE TRIGGERS
@@ -138,35 +141,35 @@
 /*
 // ***************** get shipping address based on customer selected *****************
 cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
+	return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
 }
 */
 
 
 // ***************** Get project name *****************
 cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
-  var cond = '';
-  if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
-  return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
+	var cond = '';
+	if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
+	return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
 }
 
 //---- get customer details ----------------------------
 cur_frm.cscript.project_name = function(doc,cdt,cdn){
-  $c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
-    refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
-  });
-  
+	$c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
+		refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
+	});
+	
 }
 
 
 
 // *************** Customized link query for QUOTATION ***************************** 
 cur_frm.fields_dict['quotation_no'].get_query = function(doc) {
-  var cond='';
-  if(doc.order_type) cond = ' ifnull(`tabQuotation`.order_type, "") = "'+doc.order_type+'" and';
-  if(doc.customer) cond += ' ifnull(`tabQuotation`.customer, "") = "'+doc.customer+'" and';
-  
-  return repl('SELECT DISTINCT name, customer, transaction_date  FROM `tabQuotation` WHERE `tabQuotation`.company = "' + doc.company + '" and `tabQuotation`.`docstatus` = 1 and `tabQuotation`.status != "Order Lost" and %(cond)s `tabQuotation`.%(key)s LIKE "%s" ORDER BY `tabQuotation`.`name` DESC LIMIT 50', {cond:cond});
+	var cond='';
+	if(doc.order_type) cond = ' ifnull(`tabQuotation`.order_type, "") = "'+doc.order_type+'" and';
+	if(doc.customer) cond += ' ifnull(`tabQuotation`.customer, "") = "'+doc.customer+'" and';
+	
+	return repl('SELECT DISTINCT name, customer, transaction_date	FROM `tabQuotation` WHERE `tabQuotation`.company = "' + doc.company + '" and `tabQuotation`.`docstatus` = 1 and `tabQuotation`.status != "Order Lost" and %(cond)s `tabQuotation`.%(key)s LIKE "%s" ORDER BY `tabQuotation`.`name` DESC LIMIT 50', {cond:cond});
 }
 
 
@@ -175,164 +178,164 @@
 
 // ***************** Get available qty in warehouse of item selected **************** 
 cur_frm.cscript.reserved_warehouse = function(doc, cdt , cdn) {
-  var d = locals[cdt][cdn];
-  if (d.reserved_warehouse) {
-    arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.reserved_warehouse +"'}";
-    get_server_fields('get_available_qty',arg,'sales_order_details',doc,cdt,cdn,1);
-  }
+	var d = locals[cdt][cdn];
+	if (d.reserved_warehouse) {
+		arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.reserved_warehouse +"'}";
+		get_server_fields('get_available_qty',arg,'sales_order_details',doc,cdt,cdn,1);
+	}
 }
 
 //----------- make maintenance schedule----------
 cur_frm.cscript['Make Maintenance Schedule'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  if (doc.docstatus == 1) { 
-    $c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_schedule','',
-      function(r,rt){
-        if(r.message == 'No'){
-          n = createLocal("Maintenance Schedule");
-          $c('dt_map', args={
-                  'docs':compress_doclist([locals["Maintenance Schedule"][n]]),
-                  'from_doctype':'Sales Order',
-                  'to_doctype':'Maintenance Schedule',
-                  'from_docname':doc.name,
-            'from_to_list':"[['Sales Order', 'Maintenance Schedule'], ['Sales Order Detail', 'Item Maintenance Detail']]"
-          }
-          , function(r,rt) {
-            loaddoc("Maintenance Schedule", n);
-          }
-          );
-        }
-        else{
-          msgprint("You have already created Maintenance Schedule against this Sales Order");
-        }
-      }
-    );
-  }
+	if (doc.docstatus == 1) { 
+		$c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_schedule','',
+			function(r,rt){
+				if(r.message == 'No'){
+					n = createLocal("Maintenance Schedule");
+					$c('dt_map', args={
+									'docs':compress_doclist([locals["Maintenance Schedule"][n]]),
+									'from_doctype':'Sales Order',
+									'to_doctype':'Maintenance Schedule',
+									'from_docname':doc.name,
+						'from_to_list':"[['Sales Order', 'Maintenance Schedule'], ['Sales Order Detail', 'Item Maintenance Detail']]"
+					}
+					, function(r,rt) {
+						loaddoc("Maintenance Schedule", n);
+					}
+					);
+				}
+				else{
+					msgprint("You have already created Maintenance Schedule against this Sales Order");
+				}
+			}
+		);
+	}
 }
 
 //------------ make maintenance visit ------------
 cur_frm.cscript['Make Maintenance Visit'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  if (doc.docstatus == 1) { 
-    $c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_visit','',
-      function(r,rt){
-        if(r.message == 'No'){
-          n = createLocal("Maintenance Visit");
-          $c('dt_map', args={
-                  'docs':compress_doclist([locals["Maintenance Visit"][n]]),
-                  'from_doctype':'Sales Order',
-                  'to_doctype':'Maintenance Visit',
-                  'from_docname':doc.name,
-            'from_to_list':"[['Sales Order', 'Maintenance Visit'], ['Sales Order Detail', 'Maintenance Visit Detail']]"
-          }
-          , function(r,rt) {
-            loaddoc("Maintenance Visit", n);
-          }
-          );
-        }
-        else{
-          msgprint("You have already completed maintenance against this Sales Order");
-        }
-      }
-    );
-  }
+	if (doc.docstatus == 1) { 
+		$c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_visit','',
+			function(r,rt){
+				if(r.message == 'No'){
+					n = createLocal("Maintenance Visit");
+					$c('dt_map', args={
+									'docs':compress_doclist([locals["Maintenance Visit"][n]]),
+									'from_doctype':'Sales Order',
+									'to_doctype':'Maintenance Visit',
+									'from_docname':doc.name,
+						'from_to_list':"[['Sales Order', 'Maintenance Visit'], ['Sales Order Detail', 'Maintenance Visit Detail']]"
+					}
+					, function(r,rt) {
+						loaddoc("Maintenance Visit", n);
+					}
+					);
+				}
+				else{
+					msgprint("You have already completed maintenance against this Sales Order");
+				}
+			}
+		);
+	}
 }
 
 // make indent
 // ================================================================================================
 cur_frm.cscript['Make Purchase Requisition'] = function() {
-  var doc = cur_frm.doc;
-  if (doc.docstatus == 1) { 
-  n = createLocal("Indent");
-  $c('dt_map', args={
-          'docs':compress_doclist([locals["Indent"][n]]),
-          'from_doctype':'Sales Order',
-          'to_doctype':'Indent',
-          'from_docname':doc.name,
-    'from_to_list':"[['Sales Order', 'Indent'], ['Sales Order Detail', 'Indent Detail']]"
-  }
-  , function(r,rt) {
-    loaddoc("Indent", n);
-    }
-    );
-  }
+	var doc = cur_frm.doc;
+	if (doc.docstatus == 1) { 
+	n = createLocal("Indent");
+	$c('dt_map', args={
+					'docs':compress_doclist([locals["Indent"][n]]),
+					'from_doctype':'Sales Order',
+					'to_doctype':'Indent',
+					'from_docname':doc.name,
+		'from_to_list':"[['Sales Order', 'Indent'], ['Sales Order Detail', 'Indent Detail']]"
+	}
+	, function(r,rt) {
+		loaddoc("Indent", n);
+		}
+		);
+	}
 }
 
 
 // MAKE DELIVERY NOTE
 // ================================================================================================
 cur_frm.cscript['Make Delivery Note'] = function() {
-  var doc = cur_frm.doc;
-  if (doc.docstatus == 1) { 
-  n = createLocal("Delivery Note");
-  $c('dt_map', args={
-          'docs':compress_doclist([locals["Delivery Note"][n]]),
-          'from_doctype':'Sales Order',
-          'to_doctype':'Delivery Note',
-          'from_docname':doc.name,
-    'from_to_list':"[['Sales Order', 'Delivery Note'], ['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
-  }
-  , function(r,rt) {
-    loaddoc("Delivery Note", n);
-    }
-    );
-  }
+	var doc = cur_frm.doc;
+	if (doc.docstatus == 1) { 
+	n = createLocal("Delivery Note");
+	$c('dt_map', args={
+					'docs':compress_doclist([locals["Delivery Note"][n]]),
+					'from_doctype':'Sales Order',
+					'to_doctype':'Delivery Note',
+					'from_docname':doc.name,
+		'from_to_list':"[['Sales Order', 'Delivery Note'], ['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
+	}
+	, function(r,rt) {
+		loaddoc("Delivery Note", n);
+		}
+		);
+	}
 }
 
 
 // MAKE SALES INVOICE
 // ================================================================================================
 cur_frm.cscript['Make Sales Invoice'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  n = createLocal('Receivable Voucher');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Receivable Voucher'][n]]),
-    'from_doctype':doc.doctype,
-    'to_doctype':'Receivable Voucher',
-    'from_docname':doc.name,
-    'from_to_list':"[['Sales Order','Receivable Voucher'],['Sales Order Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
-    }, function(r,rt) {
-       loaddoc('Receivable Voucher', n);
-    }
-  );
+	n = createLocal('Receivable Voucher');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Receivable Voucher'][n]]),
+		'from_doctype':doc.doctype,
+		'to_doctype':'Receivable Voucher',
+		'from_docname':doc.name,
+		'from_to_list':"[['Sales Order','Receivable Voucher'],['Sales Order Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
+		}, function(r,rt) {
+			 loaddoc('Receivable Voucher', n);
+		}
+	);
 }
 
 
 // STOP SALES ORDER
 // ==================================================================================================
 cur_frm.cscript['Stop Sales Order'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  var check = confirm("Are you sure you want to STOP " + doc.name);
+	var check = confirm("Are you sure you want to STOP " + doc.name);
 
-  if (check) {
-    $c('runserverobj', args={'method':'stop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-    });
-  }
+	if (check) {
+		$c('runserverobj', args={'method':'stop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+		});
+	}
 }
 
 // UNSTOP SALES ORDER
 // ==================================================================================================
 cur_frm.cscript['Unstop Sales Order'] = function() {
-  var doc = cur_frm.doc;
+	var doc = cur_frm.doc;
 
-  var check = confirm("Are you sure you want to UNSTOP " + doc.name);
+	var check = confirm("Are you sure you want to UNSTOP " + doc.name);
 
-  if (check) {
-    $c('runserverobj', args={'method':'unstop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
-      cur_frm.refresh();
-    });
-  }
+	if (check) {
+		$c('runserverobj', args={'method':'unstop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
+			cur_frm.refresh();
+		});
+	}
 }
 
 //get query select Territory
 //=======================================================================================================================
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"  ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';
+	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
 }
 
 $import(Notification Control)
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index aefe666..225e0dc 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -85,8 +85,18 @@
 # ================================================================================
 	# Get Item Details
 	# ----------------
-	def get_item_details(self, item_code):
-		return get_obj('Sales Common').get_item_details(item_code, self)
+	def get_item_details(self, item_code=None):
+		if item_code:
+			return get_obj('Sales Common').get_item_details(item_code, self)
+		else:
+			obj = get_obj('Sales Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					ret = obj.get_item_details(doc.item_code, self)
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]					
+
 
 	# Re-calculates Basic Rate & amount based on Price List Selected
 	# --------------------------------------------------------------
diff --git a/erpnext/setup/doctype/email_digest/email_digest.py b/erpnext/setup/doctype/email_digest/email_digest.py
index 93273ba..6524f5c 100644
--- a/erpnext/setup/doctype/email_digest/email_digest.py
+++ b/erpnext/setup/doctype/email_digest/email_digest.py
@@ -763,7 +763,7 @@
 	"""
 	edigest_list = webnotes.conn.sql("""
 		SELECT name FROM `tabEmail Digest`
-		WHERE enabled=1
+		WHERE enabled=1 and docstatus<2
 	""", as_list=1)
 
 	from webnotes.model.code import get_obj
diff --git a/erpnext/setup/doctype/price_list/price_list.py b/erpnext/setup/doctype/price_list/price_list.py
index 23a43e7..c4bab3b 100644
--- a/erpnext/setup/doctype/price_list/price_list.py
+++ b/erpnext/setup/doctype/price_list/price_list.py
@@ -85,8 +85,9 @@
 		  
 		from webnotes.utils import file_manager
 		fn, content = file_manager.get_file(fid)
-		
-		if not type(content) == str:
+	
+		# NOTE: Don't know why this condition exists
+		if not isinstance(content, basestring) and hasattr(content, 'tostring'):
 		  content = content.tostring()
 
-		return content	
\ No newline at end of file
+		return content	
diff --git a/erpnext/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py b/erpnext/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py
index 2028e5f..35564bb 100644
--- a/erpnext/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py
+++ b/erpnext/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py
@@ -96,8 +96,9 @@
 
 		from webnotes.utils import file_manager
 		fn, content = file_manager.get_file(fid)
-
-		if not type(content) == str:
+		
+		# NOTE: Don't know why this condition exists
+		if not isinstance(content, basestring) and hasattr(content, 'tostring'):
 		  content = content.tostring()
 
 		return content
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.js b/erpnext/stock/doctype/delivery_note/delivery_note.js
index 59dff8a..4099174 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.js
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.js
@@ -11,93 +11,97 @@
 // ONLOAD
 // ================================================================================================
 cur_frm.cscript.onload = function(doc, dt, dn) {
-  if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
-  if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()});
-  if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
-  if(doc.__islocal && doc.customer) cur_frm.cscript.pull_item_details_onload(doc,dt,dn);
-  if(!doc.price_list_currency) {
-	set_multiple(dt, dn, {price_list_currency: doc.currency, plc_conversion_rate:1});
-}
-  if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time()
-    
-  if(doc.__islocal){
-    hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
-  }   
+	if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
+	if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()});
+	if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
+	if(doc.__islocal && doc.customer) cur_frm.cscript.pull_item_details_onload(doc,dt,dn);
+	if(!doc.price_list_currency) {
+		set_multiple(dt, dn, {price_list_currency: doc.currency, plc_conversion_rate:1});
+	}
+	if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time()
+		
+	if(doc.__islocal){
+		hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+	}
+
+	// defined in sales_common.js
+	//cur_frm.cscript.update_item_details(doc, cdt, cdn);
+	
 }
 
 cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
-  // load default charges
-  if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length) 
-    cur_frm.cscript.load_taxes(doc, cdt, cdn);	
+	// load default charges
+	if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length) 
+		cur_frm.cscript.load_taxes(doc, cdt, cdn);	
 } 
 
 // REFRESH
 // ================================================================================================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) { 
-  cur_frm.clear_custom_buttons();
+	cur_frm.clear_custom_buttons();
  
-  if(doc.per_billed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
-  
-  if(doc.per_installed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
+	if(doc.per_billed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
+	
+	if(doc.per_installed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
 
-  if (doc.docstatus!=1) {
-    hide_field(['SMS', 'Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
-  } else {
-    cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-    unhide_field(['SMS','Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
-  }
+	if (doc.docstatus!=1) {
+		hide_field(['SMS', 'Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
+	} else {
+		cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+		unhide_field(['SMS','Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
+	}
 
-  if(doc.docstatus==1) {
-    cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
-  }
-  
-  set_print_hide(doc, cdt, cdn);
+	if(doc.docstatus==1) {
+		cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
+	}
+	
+	set_print_hide(doc, cdt, cdn);
 }
 
 
 //customer
-cur_frm.cscript.customer = function(doc,dt,dn) {  
-  var callback = function(r,rt) {
-      var doc = locals[cur_frm.doctype][cur_frm.docname];
-      cur_frm.refresh();
-  } 
-  if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', '', callback);
-  if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
+cur_frm.cscript.customer = function(doc,dt,dn) {	
+	var callback = function(r,rt) {
+			var doc = locals[cur_frm.doctype][cur_frm.docname];
+			cur_frm.refresh();
+	} 
+	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', '', callback);
+	if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
 }
 
-cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {    
-  if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
+	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict.customer_address.on_new = function(dn) {
-  locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-  locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.cscript['Get Items'] = function(doc,dt,dn) {
-  var callback = function(r,rt){
-    var doc = locals[cur_frm.doctype][cur_frm.docname];          
-    if(r.message){              
-      doc.sales_order_no = r.message;      
-		  if(doc.sales_order_no) {		      
-  			  unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);			    			    			  
-		  }		  
-		  refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
-    }
-  } 
+	var callback = function(r,rt){
+		var doc = locals[cur_frm.doctype][cur_frm.docname];					
+		if(r.message){							
+			doc.sales_order_no = r.message;			
+			if(doc.sales_order_no) {					
+					unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);														
+			}			
+			refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+		}
+	} 
  $c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback); 
 }
 
@@ -105,45 +109,45 @@
 //RV-DN : Pull Item details - UOM, Item Group as it was not in Sales Invoice
 //---------------------------------------------------------------------
 cur_frm.cscript.pull_item_details_onload = function(doc,dt,dn){
-  var callback = function(r,rt){
-    refresh_field('delivery_note_details');
-    cur_frm.cscript.customer(doc,dt,dn);
-  } 
-  $c_obj(make_doclist(dt,dn),'set_item_details','',callback);
+	var callback = function(r,rt){
+		refresh_field('delivery_note_details');
+		cur_frm.cscript.customer(doc,dt,dn);
+	} 
+	$c_obj(make_doclist(dt,dn),'set_item_details','',callback);
 }
 
 //================ create new contact ============================================================================
 cur_frm.cscript.new_contact = function(){
-  tn = createLocal('Contact');
-  locals['Contact'][tn].is_customer = 1;
-  if(doc.customer) locals['Contact'][tn].customer = doc.customer;
-  loaddoc('Contact', tn);
+	tn = createLocal('Contact');
+	locals['Contact'][tn].is_customer = 1;
+	if(doc.customer) locals['Contact'][tn].customer = doc.customer;
+	loaddoc('Contact', tn);
 }
 
 //========================= Overloaded query for link batch_no =============================================================
 cur_frm.fields_dict['delivery_note_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if(d.item_code){
-    return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
-  }
-  else{
-    alert("Please enter Item Code.");
-  }
+	var d = locals[cdt][cdn];
+	if(d.item_code){
+		return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
+	}
+	else{
+		alert("Please enter Item Code.");
+	}
 }
 
 // ***************** Get project name *****************
 cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
-  var cond = '';
-  if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
-  return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
+	var cond = '';
+	if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
+	return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
 }
 
 /*
 //---- get customer details ----------------------------
 cur_frm.cscript.project_name = function(doc,cdt,cdn){
-  $c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
-    refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
-  });
+	$c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
+		refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
+	});
 }
 */
 
@@ -154,23 +158,23 @@
 /*
 var cfn_set_fields = function(doc, cdt, cdn) { 
  var supplier_field_list = ['Supplier','supplier','supplier_address'];
-  var customer_field_list = ['Customer','customer','customer_name','customer_address','territory','customer_group','Business Associate','sales_partner','commission_rate','total_commission','sales_order_no','Get Items'];
-  if (doc.delivery_type == 'Rejected' && doc.purchase_receipt_no) {
-    unhide_field('purchase_receipt_no');
-    unhide_field(supplier_field_list);
-    hide_field(customer_field_list);
-    get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
-  }
-  else if (doc.delivery_type == 'Subcontract' && doc.purchase_order_no) {
-    unhide_field('purchase_order_no');
-    unhide_field(supplier_field_list);
-    hide_field(cutomer_field_list);
-    get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
-  }
-  else if (doc.delivery_type == 'Sample') unhide_field('to_warehouse');
-  else get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 0;   
-    
-  
+	var customer_field_list = ['Customer','customer','customer_name','customer_address','territory','customer_group','Business Associate','sales_partner','commission_rate','total_commission','sales_order_no','Get Items'];
+	if (doc.delivery_type == 'Rejected' && doc.purchase_receipt_no) {
+		unhide_field('purchase_receipt_no');
+		unhide_field(supplier_field_list);
+		hide_field(customer_field_list);
+		get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
+	}
+	else if (doc.delivery_type == 'Subcontract' && doc.purchase_order_no) {
+		unhide_field('purchase_order_no');
+		unhide_field(supplier_field_list);
+		hide_field(cutomer_field_list);
+		get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
+	}
+	else if (doc.delivery_type == 'Sample') unhide_field('to_warehouse');
+	else get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 0;	 
+		
+	
 }
 
 */
@@ -181,14 +185,14 @@
 /*
 // ***************** Get Contact Person based on customer selected *****************
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE ((`tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'") or (`tabContact`.is_sales_partner = 1 AND `tabContact`.sales_partner = "'+ doc.sales_partner+'")) AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
+	return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE ((`tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'") or (`tabContact`.is_sales_partner = 1 AND `tabContact`.sales_partner = "'+ doc.sales_partner+'")) AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
 }
 */
 
 /*
 // ***************** get shipping address based on customer selected *****************
 cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
+	return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
 }
 */
 
@@ -196,179 +200,179 @@
 
 // *************** Customized link query for SALES ORDER based on customer and currency***************************** 
 cur_frm.fields_dict['sales_order_no'].get_query = function(doc) {
-  doc = locals[this.doctype][this.docname];
-  var cond = '';
-  
-  if(doc.customer) {
-    if(doc.currency) cond = '`tabSales Order`.customer = "'+doc.customer+'" and `tabSales Order`.currency = "'+doc.currency+'" and';
-    else cond = '`tabSales Order`.customer = "'+doc.customer+'" and';
-  }
-  else {
-    if(doc.currency) cond = '`tabSales Order`.currency = "'+doc.currency+'" and';
-    else cond = '';
-  }
-  if(doc.project_name){
-    cond += '`tabSales Order`.project_name ="'+doc.project_name+'"';
-  }
-  return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 100 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond})
+	doc = locals[this.doctype][this.docname];
+	var cond = '';
+	
+	if(doc.customer) {
+		if(doc.currency) cond = '`tabSales Order`.customer = "'+doc.customer+'" and `tabSales Order`.currency = "'+doc.currency+'" and';
+		else cond = '`tabSales Order`.customer = "'+doc.customer+'" and';
+	}
+	else {
+		if(doc.currency) cond = '`tabSales Order`.currency = "'+doc.currency+'" and';
+		else cond = '';
+	}
+	if(doc.project_name){
+		cond += '`tabSales Order`.project_name ="'+doc.project_name+'"';
+	}
+	return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 100 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond})
 }
 
 
 // ****************************** DELIVERY TYPE ************************************
 cur_frm.cscript.delivery_type = function(doc, cdt, cdn) {
-  if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn);
+	if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn);
 }
 
 cur_frm.cscript.serial_no = function(doc, cdt , cdn) {
-  var d = locals[cdt][cdn];
-  if (d.serial_no) {
-     get_server_fields('get_serial_details',d.serial_no,'delivery_note_details',doc,cdt,cdn,1);
-  }
+	var d = locals[cdt][cdn];
+	if (d.serial_no) {
+		 get_server_fields('get_serial_details',d.serial_no,'delivery_note_details',doc,cdt,cdn,1);
+	}
 }
 
 /* 
 // this won't work in case of Sales Bom item where item.is_stock_item = 'No'
 cur_frm.fields_dict['delivery_note_details'].grid.get_field('warehouse').get_query= function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50";
+	var d = locals[cdt][cdn];
+	return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50";
 }
 */
 
 cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if (! d.item_code) {alert("please enter item code first"); return};
-  if (d.warehouse) {
-    arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
-    get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1);
-  }
+	var d = locals[cdt][cdn];
+	if (! d.item_code) {alert("please enter item code first"); return};
+	if (d.warehouse) {
+		arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
+		get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1);
+	}
 }
 
 
 cur_frm.fields_dict['transporter_name'].get_query = function(doc) {
-  return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
+	return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
 }
 
 //-----------------------------------Make Sales Invoice----------------------------------------------
 cur_frm.cscript['Make Sales Invoice'] = function() {
-  var doc = cur_frm.doc
-  n = createLocal('Receivable Voucher');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Receivable Voucher'][n]]),
-    'from_doctype':doc.doctype,
-    'to_doctype':'Receivable Voucher',
-    'from_docname':doc.name,
-    'from_to_list':"[['Delivery Note','Receivable Voucher'],['Delivery Note Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
-    }, function(r,rt) {
-       loaddoc('Receivable Voucher', n);
-    }
-  );
+	var doc = cur_frm.doc
+	n = createLocal('Receivable Voucher');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Receivable Voucher'][n]]),
+		'from_doctype':doc.doctype,
+		'to_doctype':'Receivable Voucher',
+		'from_docname':doc.name,
+		'from_to_list':"[['Delivery Note','Receivable Voucher'],['Delivery Note Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
+		}, function(r,rt) {
+			 loaddoc('Receivable Voucher', n);
+		}
+	);
 }
 
 //-----------------------------------Make Installation Note----------------------------------------------
 cur_frm.cscript['Make Installation Note'] = function() {
-  var doc = cur_frm.doc;
-  if(doc.per_installed < 100){
-    n = createLocal('Installation Note');
-    $c('dt_map', args={
-      'docs':compress_doclist([locals['Installation Note'][n]]),
-      'from_doctype':doc.doctype,
-      'to_doctype':'Installation Note',
-      'from_docname':doc.name,
-      'from_to_list':"[['Delivery Note','Installation Note'],['Delivery Note Detail','Installed Item Details']]"
-      }, function(r,rt) {
-         loaddoc('Installation Note', n);
-      }
-    );
-  }
-  else if(doc.per_installed >= 100)
-    msgprint("Item installation is already completed")
+	var doc = cur_frm.doc;
+	if(doc.per_installed < 100){
+		n = createLocal('Installation Note');
+		$c('dt_map', args={
+			'docs':compress_doclist([locals['Installation Note'][n]]),
+			'from_doctype':doc.doctype,
+			'to_doctype':'Installation Note',
+			'from_docname':doc.name,
+			'from_to_list':"[['Delivery Note','Installation Note'],['Delivery Note Detail','Installed Item Details']]"
+			}, function(r,rt) {
+				 loaddoc('Installation Note', n);
+			}
+		);
+	}
+	else if(doc.per_installed >= 100)
+		msgprint("Item installation is already completed")
 }
 
 //-----------------------------------Make Sales Invoice----------------------------------------------
 cur_frm.cscript['Make Packing Slip'] = function() {
-  var doc = cur_frm.doc
-  n = createLocal('Packing Slip');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Packing Slip'][n]]),
-    'from_doctype':doc.doctype,
-    'to_doctype':'Packing Slip',
-    'from_docname':doc.name,
-    'from_to_list':"[['Delivery Note','Packing Slip'],['Delivery Note Detail','Packing Slip Detail']]"
-    }, function(r,rt) {
-       loaddoc('Packing Slip', n);
-    }
-  );
+	var doc = cur_frm.doc
+	n = createLocal('Packing Slip');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Packing Slip'][n]]),
+		'from_doctype':doc.doctype,
+		'to_doctype':'Packing Slip',
+		'from_docname':doc.name,
+		'from_to_list':"[['Delivery Note','Packing Slip'],['Delivery Note Detail','Packing Slip Detail']]"
+		}, function(r,rt) {
+			 loaddoc('Packing Slip', n);
+		}
+	);
 }
 
 
 //get query select Territory
 //=======================================================================================================================
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"  ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';
+	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
 }
 
 //------------------------for printing without amount----------
 
 var set_print_hide= function(doc, cdt, cdn){
-  if (doc.print_without_amount) {
-    fields['Delivery Note']['currency'].print_hide = 1;
-    fields['Delivery Note Detail']['export_rate'].print_hide = 1;
-    fields['Delivery Note Detail']['adj_rate'].print_hide = 1;
-    fields['Delivery Note Detail']['ref_rate'].print_hide = 1;
-    fields['Delivery Note Detail']['export_amount'].print_hide = 1;
-  } else {
-    fields['Delivery Note']['currency'].print_hide = 0;
-    fields['Delivery Note Detail']['export_rate'].print_hide = 0;
-    fields['Delivery Note Detail']['adj_rate'].print_hide = 0;
-    fields['Delivery Note Detail']['ref_rate'].print_hide = 0;
-    fields['Delivery Note Detail']['export_amount'].print_hide = 0;
-  }
+	if (doc.print_without_amount) {
+		fields['Delivery Note']['currency'].print_hide = 1;
+		fields['Delivery Note Detail']['export_rate'].print_hide = 1;
+		fields['Delivery Note Detail']['adj_rate'].print_hide = 1;
+		fields['Delivery Note Detail']['ref_rate'].print_hide = 1;
+		fields['Delivery Note Detail']['export_amount'].print_hide = 1;
+	} else {
+		fields['Delivery Note']['currency'].print_hide = 0;
+		fields['Delivery Note Detail']['export_rate'].print_hide = 0;
+		fields['Delivery Note Detail']['adj_rate'].print_hide = 0;
+		fields['Delivery Note Detail']['ref_rate'].print_hide = 0;
+		fields['Delivery Note Detail']['export_amount'].print_hide = 0;
+	}
 }
 
 cur_frm.cscript.print_without_amount = function(doc, cdt, cdn) {
-  set_print_hide(doc, cdt, cdn);
+	set_print_hide(doc, cdt, cdn);
 }
 
 
 //****************** For print sales order no and date*************************
 cur_frm.pformat.sales_order_no= function(doc, cdt, cdn){
-  //function to make row of table
-  
-  var make_row = function(title,val1, val2, bold){
-    var bstart = '<b>'; var bend = '</b>';
+	//function to make row of table
+	
+	var make_row = function(title,val1, val2, bold){
+		var bstart = '<b>'; var bend = '</b>';
 
-    return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
-     +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
-     +'</tr>'
-  }
+		return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+		 +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+		 +'</tr>'
+	}
 
-  out ='';
-  
-  var cl = getchildren('Delivery Note Detail',doc.name,'delivery_note_details');
+	out ='';
+	
+	var cl = getchildren('Delivery Note Detail',doc.name,'delivery_note_details');
 
-  // outer table  
-  var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
-  
-  // main table
-  out +='<table class="noborder" style="width:100%">';
+	// outer table	
+	var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
+	
+	// main table
+	out +='<table class="noborder" style="width:100%">';
 
-  // add rows
-  if(cl.length){
-    prevdoc_list = new Array();
-    for(var i=0;i<cl.length;i++){
-      if(cl[i].prevdoc_doctype == 'Sales Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
-        prevdoc_list.push(cl[i].prevdoc_docname);
-        if(prevdoc_list.length ==1)
-          out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-        else
-          out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-      }
-    }
-  }
+	// add rows
+	if(cl.length){
+		prevdoc_list = new Array();
+		for(var i=0;i<cl.length;i++){
+			if(cl[i].prevdoc_doctype == 'Sales Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
+				prevdoc_list.push(cl[i].prevdoc_docname);
+				if(prevdoc_list.length ==1)
+					out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+				else
+					out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+			}
+		}
+	}
 
-  out +='</table></td></tr></table></div>';
+	out +='</table></td></tr></table></div>';
 
-  return out;
+	return out;
 }
 
 $import(Notification Control)
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index f791893..60aee13 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -100,8 +100,18 @@
 # ================================================================================
 
 	# ***************** Get Item Details ******************************
-	def get_item_details(self, item_code):
-		return get_obj('Sales Common').get_item_details(item_code, self)
+	def get_item_details(self, item_code=None):
+		if item_code:
+			return get_obj('Sales Common').get_item_details(item_code, self)
+		else:
+			obj = get_obj('Sales Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					ret = obj.get_item_details(doc.item_code, self)
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]					
+
 
 	# *** Re-calculates Basic Rate & amount based on Price List Selected ***
 	def get_adj_percent(self, arg=''):
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
index b5c68c2..5d4310f 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -9,17 +9,19 @@
 //========================== On Load ================================================================
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
 
-  if(!doc.fiscal_year && doc.__islocal){ set_default_values(doc);}
-  if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
-  if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
-  if (!doc.status) doc.status = 'Draft';
-  
-  if(doc.__islocal){
-    hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
-  }
-  
-  if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
-  
+	if(!doc.fiscal_year && doc.__islocal){ set_default_values(doc);}
+	if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
+	if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
+	if (!doc.status) doc.status = 'Draft';
+	
+	if(doc.__islocal){
+		hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
+	}
+	
+	if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
+	
+	// defined in purchase_common.js
+	cur_frm.cscript.update_item_details(doc, cdt, cdn);	
 }
 
 cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
@@ -31,198 +33,198 @@
 //========================== Refresh ===============================================================
 cur_frm.cscript.refresh = function(doc, cdt, cdn) { 
 
-  // Unhide Fields in Next Steps
-  // ---------------------------------
-  cur_frm.clear_custom_buttons();
-  if(doc.docstatus == 1){
-    var ch = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
-    allow_billing = 0;
-    for(var i in ch){
-      if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
-    }
-   cur_frm.add_custom_button('Make Purchase Invoice', cur_frm.cscript['Make Purchase Invoice']);
-   cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
-  }
-  else{
-    hide_field(['Repair Purchase Receipt']);
-  }
+	// Unhide Fields in Next Steps
+	// ---------------------------------
+	cur_frm.clear_custom_buttons();
+	if(doc.docstatus == 1){
+		var ch = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
+		allow_billing = 0;
+		for(var i in ch){
+			if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
+		}
+	 cur_frm.add_custom_button('Make Purchase Invoice', cur_frm.cscript['Make Purchase Invoice']);
+	 cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
+	}
+	else{
+		hide_field(['Repair Purchase Receipt']);
+	}
 }
 
 
 //Supplier
 cur_frm.cscript.supplier = function(doc,dt,dn) {
-  if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
-  if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
+	if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
+	if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
 }
 
-cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {    
-  if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
+cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
+	if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 
 cur_frm.fields_dict.supplier_address.on_new = function(dn) {
-  locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 cur_frm.fields_dict.contact_person.on_new = function(dn) {
-  locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
-  locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
+	locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
+	locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
 }
 
 
 // Get Purchase Order Button
 // -----------------
 cur_frm.cscript['Pull Purchase Order Details'] = function(doc, dt, dn) {
-  var callback = function(r,rt) { 
-	  unhide_field(['supplier_address','contact_person','supplier_name','address_display', 'contact_display', 'contact_mobile','contact_email']);			  
-	  refresh_many(['supplier','supplier_address','contact_person', 'supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email', 'purchase_receipt_details', 'purchase_tax_details']);
-  }
-  $c_obj(make_doclist(dt,dn),'get_po_details','',callback);
+	var callback = function(r,rt) { 
+		unhide_field(['supplier_address','contact_person','supplier_name','address_display', 'contact_display', 'contact_mobile','contact_email']);				
+		refresh_many(['supplier','supplier_address','contact_person', 'supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email', 'purchase_receipt_details', 'purchase_tax_details']);
+	}
+	$c_obj(make_doclist(dt,dn),'get_po_details','',callback);
 }
 
 
 
 //================ create new contact ============================================================================
 cur_frm.cscript.new_contact = function(){
-  tn = createLocal('Contact');
-  locals['Contact'][tn].is_supplier = 1;
-  if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
-  loaddoc('Contact', tn);
+	tn = createLocal('Contact');
+	locals['Contact'][tn].is_supplier = 1;
+	if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
+	loaddoc('Contact', tn);
 }
 
 //======================= posting date =============================
 cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
-  if(doc.__islocal){ 
-    cur_frm.cscript.get_default_schedule_date(doc);
-  }
+	if(doc.__islocal){ 
+		cur_frm.cscript.get_default_schedule_date(doc);
+	}
 }
 
 // ***************** Get project name *****************
 cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
 }
 
 
 //========================= Overloaded query for link batch_no =============================================================
 cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  if(d.item_code){
-    return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
-  }
-  else{
-    alert("Please enter Item Code.");
-  }
+	var d = locals[cdt][cdn];
+	if(d.item_code){
+		return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
+	}
+	else{
+		alert("Please enter Item Code.");
+	}
 }
 
 cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
-  if(doc.select_print_heading){
-    // print heading
-    cur_frm.pformat.print_heading = doc.select_print_heading;
-  }
-  else
-    cur_frm.pformat.print_heading = "Purchase Receipt";
+	if(doc.select_print_heading){
+		// print heading
+		cur_frm.pformat.print_heading = doc.select_print_heading;
+	}
+	else
+		cur_frm.pformat.print_heading = "Purchase Receipt";
 }
-// ***************** Get Print Heading  *****************
+// ***************** Get Print Heading	*****************
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
 }
 
 //========================= Received Qty =============================================================
 
 cur_frm.cscript.received_qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  ret = {
-      'qty' : 0,
-      'stock_qty': 0,
-      'rejected_qty' : 0
-    }
-  set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
-  cur_frm.cscript.calc_amount(doc, 2);
+	var d = locals[cdt][cdn];
+	ret = {
+			'qty' : 0,
+			'stock_qty': 0,
+			'rejected_qty' : 0
+		}
+	set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
+	cur_frm.cscript.calc_amount(doc, 2);
 }
 
 //======================== Qty (Accepted Qty) =========================================================
 
 cur_frm.cscript.qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  // Step 1 :=> Check If Qty > Received Qty
-  if (flt(d.qty) > flt(d.received_qty)) {
-    alert("Accepted Qty cannot be greater than Received Qty")
-    ret = {
-      'qty' : 0,
-      'stock_qty': 0,
-      'rejected_qty' : 0
-    }
-    // => Set Qty = 0 and rejected_qty = 0
-    set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
-    cur_frm.cscript.calc_amount(doc, 2);
-    // => Return
-    return
-  }
-  // Step 2 :=> Check IF Qty <= REceived Qty
-  else {
-    ret = {
-      'rejected_qty':flt(d.received_qty) - flt(d.qty)
-    }
-    // => Set Rejected Qty = Received Qty - Qty
-    set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
-    // => Calculate Amount
-    cur_frm.cscript.calc_amount(doc, 2);
-    cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-  }  
+	var d = locals[cdt][cdn];
+	// Step 1 :=> Check If Qty > Received Qty
+	if (flt(d.qty) > flt(d.received_qty)) {
+		alert("Accepted Qty cannot be greater than Received Qty")
+		ret = {
+			'qty' : 0,
+			'stock_qty': 0,
+			'rejected_qty' : 0
+		}
+		// => Set Qty = 0 and rejected_qty = 0
+		set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
+		cur_frm.cscript.calc_amount(doc, 2);
+		// => Return
+		return
+	}
+	// Step 2 :=> Check IF Qty <= REceived Qty
+	else {
+		ret = {
+			'rejected_qty':flt(d.received_qty) - flt(d.qty)
+		}
+		// => Set Rejected Qty = Received Qty - Qty
+		set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
+		// => Calculate Amount
+		cur_frm.cscript.calc_amount(doc, 2);
+		cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
+	}	
 }
 
 //======================== Rejected Qty =========================================================
 cur_frm.cscript.rejected_qty = function(doc, cdt, cdn) {
-  var d = locals[cdt][cdn];
-  // Step 1 :=> Check If Rejected Qty > Received Qty
-  if (flt(d.rejected_qty) > flt(d.received_qty)) {
-    alert("Rejected Qty cannot be greater than Received Qty") 
-    ret = {
-      'qty' : 0,
-      'stock_qty': 0,
-      'rejected_qty' : 0
-    }
-    // => Set Qty = 0 and rejected_qty = 0
-    set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
-    cur_frm.cscript.calc_amount(doc, 2);
-    // => Return
-    return
-  }
-  // Step 2 :=> Check IF Rejected Qty <= REceived Qty
-  else {
-    ret = {
-      'qty':flt(d.received_qty) - flt(d.rejected_qty)
-    }
-    // => Set Qty = Received Qty - Rejected Qty
-    set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
-    // Calculate Amount
-    cur_frm.cscript.calc_amount(doc, 2);
-    cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-  }
+	var d = locals[cdt][cdn];
+	// Step 1 :=> Check If Rejected Qty > Received Qty
+	if (flt(d.rejected_qty) > flt(d.received_qty)) {
+		alert("Rejected Qty cannot be greater than Received Qty") 
+		ret = {
+			'qty' : 0,
+			'stock_qty': 0,
+			'rejected_qty' : 0
+		}
+		// => Set Qty = 0 and rejected_qty = 0
+		set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
+		cur_frm.cscript.calc_amount(doc, 2);
+		// => Return
+		return
+	}
+	// Step 2 :=> Check IF Rejected Qty <= REceived Qty
+	else {
+		ret = {
+			'qty':flt(d.received_qty) - flt(d.rejected_qty)
+		}
+		// => Set Qty = Received Qty - Rejected Qty
+		set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
+		// Calculate Amount
+		cur_frm.cscript.calc_amount(doc, 2);
+		cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
+	}
 }
 
 //================================= Purchase Order No Get Query ====================================
 cur_frm.fields_dict['purchase_order_no'].get_query = function(doc) {
-  if (doc.supplier)
-    return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`supplier` = "' +doc.supplier + '" and`tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100  and `tabPurchase Order`.`currency` = ifnull("' +doc.currency+ '","") and `tabPurchase Order`.company = "'+ doc.company +'" and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
-  else
-    return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`company` = "'+ doc.company +'" and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
+	if (doc.supplier)
+		return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`supplier` = "' +doc.supplier + '" and`tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100	and `tabPurchase Order`.`currency` = ifnull("' +doc.currency+ '","") and `tabPurchase Order`.company = "'+ doc.company +'" and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
+	else
+		return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`company` = "'+ doc.company +'" and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
 }
 
 // QA INspection report get_query
 //---------------------------------
 
 cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query = function(doc) {
-  return 'SELECT `tabQA Inspection Report`.name FROM `tabQA Inspection Report` WHERE `tabQA Inspection Report`.docstatus = 1 AND `tabQA Inspection Report`.%(key)s LIKE "%s"';
+	return 'SELECT `tabQA Inspection Report`.name FROM `tabQA Inspection Report` WHERE `tabQA Inspection Report`.docstatus = 1 AND `tabQA Inspection Report`.%(key)s LIKE "%s"';
 }
 
 // On Button Click Functions
@@ -231,17 +233,17 @@
 
 // ================================ Make Purchase Invoice ==========================================
 cur_frm.cscript['Make Purchase Invoice'] = function() {
-  n = createLocal('Payable Voucher');
-  $c('dt_map', args={
-    'docs':compress_doclist([locals['Payable Voucher'][n]]),
-    'from_doctype': cur_frm.doc.doctype,
-    'to_doctype':'Payable Voucher',
-    'from_docname': cur_frm.doc.name,
-    'from_to_list':"[['Purchase Receipt','Payable Voucher'],['Purchase Receipt Detail','PV Detail']]"
-    }, function(r,rt) {
-       loaddoc('Payable Voucher', n);
-    }
-  );
+	n = createLocal('Payable Voucher');
+	$c('dt_map', args={
+		'docs':compress_doclist([locals['Payable Voucher'][n]]),
+		'from_doctype': cur_frm.doc.doctype,
+		'to_doctype':'Payable Voucher',
+		'from_docname': cur_frm.doc.name,
+		'from_to_list':"[['Purchase Receipt','Payable Voucher'],['Purchase Receipt Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
+		}, function(r,rt) {
+			 loaddoc('Payable Voucher', n);
+		}
+	);
 }
 
 
@@ -249,43 +251,43 @@
 
 //****************** For print sales order no and date*************************
 cur_frm.pformat.purchase_order_no = function(doc, cdt, cdn){
-  //function to make row of table
-  
-  var make_row = function(title,val1, val2, bold){
-    var bstart = '<b>'; var bend = '</b>';
+	//function to make row of table
+	
+	var make_row = function(title,val1, val2, bold){
+		var bstart = '<b>'; var bend = '</b>';
 
-    return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
-     +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
-     +'</tr>'
-  }
+		return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+		 +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+		 +'</tr>'
+	}
 
-  out ='';
-  
-  var cl = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
+	out ='';
+	
+	var cl = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
 
-  // outer table  
-  var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
-  
-  // main table
-  out +='<table class="noborder" style="width:100%">';
+	// outer table	
+	var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
+	
+	// main table
+	out +='<table class="noborder" style="width:100%">';
 
-  // add rows
-  if(cl.length){
-    prevdoc_list = new Array();
-    for(var i=0;i<cl.length;i++){
-      if(cl[i].prevdoc_doctype == 'Purchase Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
-        prevdoc_list.push(cl[i].prevdoc_docname);
-        if(prevdoc_list.length ==1)
-          out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-        else
-          out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
-      }
-    }
-  }
+	// add rows
+	if(cl.length){
+		prevdoc_list = new Array();
+		for(var i=0;i<cl.length;i++){
+			if(cl[i].prevdoc_doctype == 'Purchase Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
+				prevdoc_list.push(cl[i].prevdoc_docname);
+				if(prevdoc_list.length ==1)
+					out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+				else
+					out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
+			}
+		}
+	}
 
-  out +='</table></td></tr></table></div>';
+	out +='</table></td></tr></table></div>';
 
-  return out;
+	return out;
 }
 
 $import(Notification Control)
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 41ee2ff..ccc4201 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -19,407 +19,422 @@
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
-  def __init__(self, doc, doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
-    self.defaults = get_defaults()
-    self.tname = 'Purchase Receipt Detail'
-    self.fname = 'purchase_receipt_details'
-    self.count = 0
+	def __init__(self, doc, doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		self.defaults = get_defaults()
+		self.tname = 'Purchase Receipt Detail'
+		self.fname = 'purchase_receipt_details'
+		self.count = 0
 
-  # Autoname
-  # ---------
-  def autoname(self):
-    self.doc.name = make_autoname(self.doc.naming_series+'.#####')
+	# Autoname
+	# ---------
+	def autoname(self):
+		self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
 
-  # Client Trigger Functions
-  #----------------------------------------------------------------------------------------------------
+	# Client Trigger Functions
+	#----------------------------------------------------------------------------------------------------
 
-  def get_default_schedule_date(self):
-    get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
+	def get_default_schedule_date(self):
+		get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
 
 #-----------------Validation For Fiscal Year------------------------
-  def validate_fiscal_year(self):
-    get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')
+	def validate_fiscal_year(self):
+		get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')
 
 
-  # Get Item Details
-  def get_item_details(self, arg = ''):
-    return get_obj(dt='Purchase Common').get_item_details(self,arg)
-
-  # Get UOM Details
-  def get_uom_details(self, arg = ''):
-    return get_obj(dt='Purchase Common').get_uom_details(arg)
-
-  # GET TERMS & CONDITIONS
-  # =====================================================================================
-  def get_tc_details(self):
-    return get_obj('Purchase Common').get_tc_details(self)
-
-  # get available qty at warehouse
-  def get_bin_details(self, arg = ''):
-    return get_obj(dt='Purchase Common').get_bin_details(arg)
-
-  # Pull Purchase Order
-  def get_po_details(self):
-    self.validate_prev_docname()
-    get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
-
-  # validate if PO has been pulled twice
-  def validate_prev_docname(self):
-    for d in getlist(self.doclist, 'purchase_receipt_details'):
-      if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
-        msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
-        raise Exception
+	# Get Item Details
+	def get_item_details(self, arg = ''):
+		if arg:
+			return get_obj(dt='Purchase Common').get_item_details(self,arg)
+		else:
+			import json
+			obj = get_obj('Purchase Common')
+			for doc in self.doclist:
+				if doc.fields.get('item_code'):
+					temp = {
+						'item_code': doc.fields.get('item_code'),
+						'warehouse': doc.fields.get('warehouse')
+					}
+					ret = obj.get_item_details(self, json.dumps(temp))
+					for r in ret:
+						if not doc.fields.get(r):
+							doc.fields[r] = ret[r]
 
 
-  # validation
-  #-------------------------------------------------------------------------------------------------------------
-  # validate accepted and rejected qty
-  def validate_accepted_rejected_qty(self):
-    for d in getlist(self.doclist, "purchase_receipt_details"):
+	# Get UOM Details
+	def get_uom_details(self, arg = ''):
+		return get_obj(dt='Purchase Common').get_uom_details(arg)
 
-      # If Reject Qty than Rejected warehouse is mandatory
-      if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
-        msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
-        raise Exception
+	# GET TERMS & CONDITIONS
+	# =====================================================================================
+	def get_tc_details(self):
+		return get_obj('Purchase Common').get_tc_details(self)
 
-      # Check Received Qty = Accepted Qty + Rejected Qty
-      if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
+	# get available qty at warehouse
+	def get_bin_details(self, arg = ''):
+		return get_obj(dt='Purchase Common').get_bin_details(arg)
 
-        msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
-        raise Exception
+	# Pull Purchase Order
+	def get_po_details(self):
+		self.validate_prev_docname()
+		get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
+
+	# validate if PO has been pulled twice
+	def validate_prev_docname(self):
+		for d in getlist(self.doclist, 'purchase_receipt_details'):
+			if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
+				msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
+				raise Exception
 
 
-  def validate_challan_no(self):
-    "Validate if same challan no exists for same supplier in a submitted purchase receipt"
-    if self.doc.challan_no:
-      exists = webnotes.conn.sql("""
-	    SELECT name FROM `tabPurchase Receipt`
-	    WHERE name!=%s AND supplier=%s AND challan_no=%s
+	# validation
+	#-------------------------------------------------------------------------------------------------------------
+	# validate accepted and rejected qty
+	def validate_accepted_rejected_qty(self):
+		for d in getlist(self.doclist, "purchase_receipt_details"):
+
+			# If Reject Qty than Rejected warehouse is mandatory
+			if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
+				msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
+				raise Exception
+
+			# Check Received Qty = Accepted Qty + Rejected Qty
+			if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
+
+				msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
+				raise Exception
+
+
+	def validate_challan_no(self):
+		"Validate if same challan no exists for same supplier in a submitted purchase receipt"
+		if self.doc.challan_no:
+			exists = webnotes.conn.sql("""
+			SELECT name FROM `tabPurchase Receipt`
+			WHERE name!=%s AND supplier=%s AND challan_no=%s
 		AND docstatus=1""", (self.doc.name, self.doc.supplier, self.doc.challan_no))
-      if exists:
-	    webnotes.msgprint("Another Purchase Receipt using the same Challan No. already exists.\
-		  Please enter a valid Challan No.", raise_exception=1)
+			if exists:
+				webnotes.msgprint("Another Purchase Receipt using the same Challan No. already exists.\
+			Please enter a valid Challan No.", raise_exception=1)
 
 
-  # update valuation rate
-  def update_valuation_rate(self):
-    total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
-    for d in getlist(self.doclist, 'purchase_receipt_details'):
-      if flt(self.doc.net_total) and flt(d.qty):
-        #d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
-        d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
+	# update valuation rate
+	def update_valuation_rate(self):
+		total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
+		for d in getlist(self.doclist, 'purchase_receipt_details'):
+			if flt(self.doc.net_total) and flt(d.qty):
+				#d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
+				d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
 
-  # Check for Stopped status
-  def check_for_stopped_status(self, pc_obj):
-    check_list =[]
-    for d in getlist(self.doclist, 'purchase_receipt_details'):
-      if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
-        check_list.append(d.prevdoc_docname)
-        pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
+	# Check for Stopped status
+	def check_for_stopped_status(self, pc_obj):
+		check_list =[]
+		for d in getlist(self.doclist, 'purchase_receipt_details'):
+			if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
+				check_list.append(d.prevdoc_docname)
+				pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
 
-  #check in manage account if purchase order required or not.
-  # ====================================================================================
-  def po_required(self):
-    res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
-    if res and res[0][0]== 'Yes':
-       for d in getlist(self.doclist,'purchase_receipt_details'):
-         if not d.prevdoc_docname:
-           msgprint("Purchse Order No. required against item %s"%d.item_code)
-           raise Exception
+	#check in manage account if purchase order required or not.
+	# ====================================================================================
+	def po_required(self):
+		res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
+		if res and res[0][0]== 'Yes':
+			 for d in getlist(self.doclist,'purchase_receipt_details'):
+				 if not d.prevdoc_docname:
+					 msgprint("Purchse Order No. required against item %s"%d.item_code)
+					 raise Exception
 
 
-  # validate
-  def validate(self):
-    self.po_required()
-    self.validate_fiscal_year()
-    set(self.doc, 'status', 'Draft')       # set status as "Draft"
-    self.validate_accepted_rejected_qty()
-    self.validate_inspection()             # Validate Inspection
-    get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')
-    self.validate_challan_no()
+	# validate
+	def validate(self):
+		self.po_required()
+		self.validate_fiscal_year()
+		set(self.doc, 'status', 'Draft')			 # set status as "Draft"
+		self.validate_accepted_rejected_qty()
+		self.validate_inspection()						 # Validate Inspection
+		get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')
+		self.validate_challan_no()
 
-    pc_obj = get_obj(dt='Purchase Common')
-    pc_obj.validate_for_items(self)
-    pc_obj.validate_mandatory(self)
-    pc_obj.validate_conversion_rate(self)
-    pc_obj.get_prevdoc_date(self)
-    pc_obj.validate_reference_value(self)
-    self.check_for_stopped_status(pc_obj)
+		pc_obj = get_obj(dt='Purchase Common')
+		pc_obj.validate_for_items(self)
+		pc_obj.validate_mandatory(self)
+		pc_obj.validate_conversion_rate(self)
+		pc_obj.get_prevdoc_date(self)
+		pc_obj.validate_reference_value(self)
+		self.check_for_stopped_status(pc_obj)
 
-    # get total in words
-    dcc = TransactionBase().get_company_currency(self.doc.company)
-    self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
-    self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
-    # update valuation rate
-    self.update_valuation_rate()
+		# get total in words
+		dcc = TransactionBase().get_company_currency(self.doc.company)
+		self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
+		self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
+		# update valuation rate
+		self.update_valuation_rate()
 
 
-  # On Update
-  # ----------------------------------------------------------------------------------------------------
-  def on_update(self):
-    if self.doc.rejected_warehouse:
-      for d in getlist(self.doclist,'purchase_receipt_details'):
-        d.rejected_warehouse = self.doc.rejected_warehouse
+	# On Update
+	# ----------------------------------------------------------------------------------------------------
+	def on_update(self):
+		if self.doc.rejected_warehouse:
+			for d in getlist(self.doclist,'purchase_receipt_details'):
+				d.rejected_warehouse = self.doc.rejected_warehouse
 
-    self.update_rw_material_detail()
-    get_obj('Stock Ledger').scrub_serial_nos(self)
+		self.update_rw_material_detail()
+		get_obj('Stock Ledger').scrub_serial_nos(self)
 
 
-  # On Submit
-  # -----------------------------------------------------------------------------------------------------
+	# On Submit
+	# -----------------------------------------------------------------------------------------------------
 
  # Update Stock
-  def update_stock(self, is_submit):
-    pc_obj = get_obj('Purchase Common')
-    self.values = []
-    for d in getlist(self.doclist, 'purchase_receipt_details'):
-      # Check if is_stock_item == 'Yes'
-      if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
-        ord_qty = 0
-        pr_qty = flt(d.qty) * flt(d.conversion_factor)
+	def update_stock(self, is_submit):
+		pc_obj = get_obj('Purchase Common')
+		self.values = []
+		for d in getlist(self.doclist, 'purchase_receipt_details'):
+			# Check if is_stock_item == 'Yes'
+			if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
+				ord_qty = 0
+				pr_qty = flt(d.qty) * flt(d.conversion_factor)
 
-        # Check If Prevdoc Doctype is Purchase Order
-        if cstr(d.prevdoc_doctype) == 'Purchase Order':
-          # get qty and pending_qty of prevdoc
-          curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name)
-          max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
+				# Check If Prevdoc Doctype is Purchase Order
+				if cstr(d.prevdoc_doctype) == 'Purchase Order':
+					# get qty and pending_qty of prevdoc
+					curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name)
+					max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
 
-          if flt(qty) + flt(pr_qty) > flt(max_qty):
-            curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor)
-          else:
-            curr_qty = flt(pr_qty)
+					if flt(qty) + flt(pr_qty) > flt(max_qty):
+						curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor)
+					else:
+						curr_qty = flt(pr_qty)
 
-          ord_qty = -flt(curr_qty)
-          # update order qty in bin
-          bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date)
+					ord_qty = -flt(curr_qty)
+					# update order qty in bin
+					bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date)
 
-        # UPDATE actual qty to warehouse by pr_qty
-        self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit)
-        # UPDATE actual to rejected warehouse by rejected qty
-        if flt(d.rejected_qty) > 0:
-          self.make_sl_entry(d, self.doc.rejected_warehouse, flt(d.rejected_qty) * flt(d.conversion_factor), d.valuation_rate, is_submit)
+				# UPDATE actual qty to warehouse by pr_qty
+				self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit)
+				# UPDATE actual to rejected warehouse by rejected qty
+				if flt(d.rejected_qty) > 0:
+					self.make_sl_entry(d, self.doc.rejected_warehouse, flt(d.rejected_qty) * flt(d.conversion_factor), d.valuation_rate, is_submit)
 
-    self.bk_flush_supp_wh(is_submit)
+		self.bk_flush_supp_wh(is_submit)
 
-    if self.values:
-      get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
+		if self.values:
+			get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
 
 
-  # make Stock Entry
-  def make_sl_entry(self, d, wh, qty, in_value, is_submit):
-    self.values.append({
-      'item_code'           : d.fields.has_key('item_code') and d.item_code or d.rm_item_code,
-      'warehouse'           : wh,
-      'transaction_date'    : self.doc.transaction_date,
-      'posting_date'        : self.doc.posting_date,
-      'posting_time'        : self.doc.posting_time,
-      'voucher_type'        : 'Purchase Receipt',
-      'voucher_no'          : self.doc.name,
-      'voucher_detail_no'   : d.name,
-      'actual_qty'          : qty,
-      'stock_uom'           : d.stock_uom,
-      'incoming_rate'       : in_value,
-      'company'             : self.doc.company,
-      'fiscal_year'         : self.doc.fiscal_year,
-      'is_cancelled'        : (is_submit==1) and 'No' or 'Yes',
-      'batch_no'            : d.batch_no,
-      'serial_no'           : d.serial_no
-      })
+	# make Stock Entry
+	def make_sl_entry(self, d, wh, qty, in_value, is_submit):
+		self.values.append({
+			'item_code'					 : d.fields.has_key('item_code') and d.item_code or d.rm_item_code,
+			'warehouse'					 : wh,
+			'transaction_date'		: self.doc.transaction_date,
+			'posting_date'				: self.doc.posting_date,
+			'posting_time'				: self.doc.posting_time,
+			'voucher_type'				: 'Purchase Receipt',
+			'voucher_no'					: self.doc.name,
+			'voucher_detail_no'	 : d.name,
+			'actual_qty'					: qty,
+			'stock_uom'					 : d.stock_uom,
+			'incoming_rate'			 : in_value,
+			'company'						 : self.doc.company,
+			'fiscal_year'				 : self.doc.fiscal_year,
+			'is_cancelled'				: (is_submit==1) and 'No' or 'Yes',
+			'batch_no'						: d.batch_no,
+			'serial_no'					 : d.serial_no
+			})
 
 
-  def validate_inspection(self):
-    for d in getlist(self.doclist, 'purchase_receipt_details'):     #Enter inspection date for all items that require inspection
-      ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1)
-      ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'
-      if ins_reqd == 'Yes' and not d.qa_no:
-        msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report")
+	def validate_inspection(self):
+		for d in getlist(self.doclist, 'purchase_receipt_details'):		 #Enter inspection date for all items that require inspection
+			ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1)
+			ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'
+			if ins_reqd == 'Yes' and not d.qa_no:
+				msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report")
 
-  # Check for Stopped status
-  def check_for_stopped_status(self, pc_obj):
-    check_list =[]
-    for d in getlist(self.doclist, 'purchase_receipt_details'):
-      if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
-        check_list.append(d.prevdoc_docname)
-        pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
+	# Check for Stopped status
+	def check_for_stopped_status(self, pc_obj):
+		check_list =[]
+		for d in getlist(self.doclist, 'purchase_receipt_details'):
+			if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
+				check_list.append(d.prevdoc_docname)
+				pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
 
 
-  # on submit
-  def on_submit(self):
-    # Check for Approving Authority
-    get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
+	# on submit
+	def on_submit(self):
+		# Check for Approving Authority
+		get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
 
-    # Set status as Submitted
-    set(self.doc,'status', 'Submitted')
-    pc_obj = get_obj('Purchase Common')
+		# Set status as Submitted
+		set(self.doc,'status', 'Submitted')
+		pc_obj = get_obj('Purchase Common')
 
-    # Update Previous Doc i.e. update pending_qty and Status accordingly
-    pc_obj.update_prevdoc_detail(self, is_submit = 1)
+		# Update Previous Doc i.e. update pending_qty and Status accordingly
+		pc_obj.update_prevdoc_detail(self, is_submit = 1)
 
-    # Update Serial Record
-    get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1)
+		# Update Serial Record
+		get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1)
 
-    # Update Stock
-    self.update_stock(is_submit = 1)
+		# Update Stock
+		self.update_stock(is_submit = 1)
 
-    # Update last purchase rate
-    pc_obj.update_last_purchase_rate(self, 1)
+		# Update last purchase rate
+		pc_obj.update_last_purchase_rate(self, 1)
 
 
 
-  #On Cancel
-  #----------------------------------------------------------------------------------------------------
-  def check_next_docstatus(self):
-    submit_rv = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % (self.doc.name))
-    if submit_rv:
-      msgprint("Purchase Invoice : " + cstr(self.submit_rv[0][0]) + " has already been submitted !")
-      raise Exception , "Validation Error."
+	#On Cancel
+	#----------------------------------------------------------------------------------------------------
+	def check_next_docstatus(self):
+		submit_rv = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % (self.doc.name))
+		if submit_rv:
+			msgprint("Purchase Invoice : " + cstr(self.submit_rv[0][0]) + " has already been submitted !")
+			raise Exception , "Validation Error."
 
 
-  def on_cancel(self):
-    pc_obj = get_obj('Purchase Common')
+	def on_cancel(self):
+		pc_obj = get_obj('Purchase Common')
 
-    self.check_for_stopped_status(pc_obj)
-    # 1.Check if Payable Voucher has been submitted against current Purchase Order
-    # pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
+		self.check_for_stopped_status(pc_obj)
+		# 1.Check if Payable Voucher has been submitted against current Purchase Order
+		# pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
 
-    submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name)
-    if submitted:
-      msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
-      raise Exception
+		submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name)
+		if submitted:
+			msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
+			raise Exception
 
-    # 2.Set Status as Cancelled
-    set(self.doc,'status','Cancelled')
+		# 2.Set Status as Cancelled
+		set(self.doc,'status','Cancelled')
 
-    # 3. Cancel Serial No
-    get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1)
+		# 3. Cancel Serial No
+		get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1)
 
-    # 4.Update Bin
-    self.update_stock(is_submit = 0)
+		# 4.Update Bin
+		self.update_stock(is_submit = 0)
 
-    # 5.Update Indents Pending Qty and accordingly it's Status
-    pc_obj.update_prevdoc_detail(self, is_submit = 0)
+		# 5.Update Indents Pending Qty and accordingly it's Status
+		pc_obj.update_prevdoc_detail(self, is_submit = 0)
 
-    # 6. Update last purchase rate
-    pc_obj.update_last_purchase_rate(self, 0)
+		# 6. Update last purchase rate
+		pc_obj.update_last_purchase_rate(self, 0)
 
 
 #----------- code for Sub-contracted Items -------------------
-  #--------check for sub-contracted items and accordingly update PR raw material detail table--------
-  def update_rw_material_detail(self):
+	#--------check for sub-contracted items and accordingly update PR raw material detail table--------
+	def update_rw_material_detail(self):
 
-    for d in getlist(self.doclist,'purchase_receipt_details'):
-      item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
+		for d in getlist(self.doclist,'purchase_receipt_details'):
+			item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
 
-      if item_det[0][0] == 'Yes':
-        if item_det[0][1] == 'Yes':
-          if not self.doc.is_subcontracted:
-            msgprint("Please enter whether purchase receipt to be made for subcontracting or for purchase in 'Is Subcontracted' field .")
-            raise Exception
-          if self.doc.is_subcontracted == 'Yes':
-            if not self.doc.supplier_warehouse:
-              msgprint("Please Enter Supplier Warehouse for subcontracted Items")
-              raise Exception
-            self.add_bom(d)
-          else:
-            self.doc.clear_table(self.doclist,'pr_raw_material_details',1)
-            self.doc.save()
-        elif item_det[0][1] == 'No':
-          if not self.doc.supplier_warehouse:
-            msgprint("Please Enter Supplier Warehouse for subcontracted Items")
-            raise Exception
-          self.add_bom(d)
+			if item_det[0][0] == 'Yes':
+				if item_det[0][1] == 'Yes':
+					if not self.doc.is_subcontracted:
+						msgprint("Please enter whether purchase receipt to be made for subcontracting or for purchase in 'Is Subcontracted' field .")
+						raise Exception
+					if self.doc.is_subcontracted == 'Yes':
+						if not self.doc.supplier_warehouse:
+							msgprint("Please Enter Supplier Warehouse for subcontracted Items")
+							raise Exception
+						self.add_bom(d)
+					else:
+						self.doc.clear_table(self.doclist,'pr_raw_material_details',1)
+						self.doc.save()
+				elif item_det[0][1] == 'No':
+					if not self.doc.supplier_warehouse:
+						msgprint("Please Enter Supplier Warehouse for subcontracted Items")
+						raise Exception
+					self.add_bom(d)
 
-      self.delete_irrelevant_raw_material()
-      #---------------calculate amt in  PR Raw Material Detail-------------
-      self.calculate_amount(d)
+			self.delete_irrelevant_raw_material()
+			#---------------calculate amt in	PR Raw Material Detail-------------
+			self.calculate_amount(d)
 
 
-  def add_bom(self, d):
-    #----- fetching default bom from Bill of Materials instead of Item Master --
-    bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.description from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1 and t2.docstatus =1" % d.item_code)
-    if not bom_det:
-      msgprint("No default BOM exists for item: %s" % d.item_code)
-      raise Exception
-    else:
-      #-------------- add child function--------------------
-      chgd_rqd_qty = []
-      for i in bom_det:
+	def add_bom(self, d):
+		#----- fetching default bom from Bill of Materials instead of Item Master --
+		bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.description from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1 and t2.docstatus =1" % d.item_code)
+		if not bom_det:
+			msgprint("No default BOM exists for item: %s" % d.item_code)
+			raise Exception
+		else:
+			#-------------- add child function--------------------
+			chgd_rqd_qty = []
+			for i in bom_det:
 
-        if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
+				if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
 
-          rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist)
+					rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist)
 
-          rm_child.reference_name = d.name
-          rm_child.bom_detail_no = i and i[6] or ''
-          rm_child.main_item_code = i and i[0] or ''
-          rm_child.rm_item_code = i and i[1] or ''
-          rm_child.description = i and i[7] or ''
-          rm_child.stock_uom = i and i[5] or ''
-          rm_child.rate = i and flt(i[3]) or flt(i[4])
-          rm_child.conversion_factor = d.conversion_factor
-          rm_child.required_qty = flt(i  and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
-          rm_child.consumed_qty = flt(i  and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
-          rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
-          rm_child.save()
-          chgd_rqd_qty.append(cstr(i[1]))
-        else:
-          act_qty = flt(i  and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
-          for pr_rmd in getlist(self.doclist, 'pr_raw_material_details'):
-            if i and i[6] == pr_rmd.bom_detail_no and (flt(act_qty) != flt(pr_rmd.required_qty) or i[1] != pr_rmd.rm_item_code or i[7] != pr_rmd.description):
-              chgd_rqd_qty.append(cstr(i[1]))
-              pr_rmd.main_item_code = i[0]
-              pr_rmd.rm_item_code = i[1]
-              pr_rmd.description = i[7]
-              pr_rmd.stock_uom = i[5]
-              pr_rmd.required_qty = flt(act_qty)
-              pr_rmd.consumed_qty = flt(act_qty)
-              pr_rmd.rate = i and flt(i[3]) or flt(i[4])
-              pr_rmd.amount = flt(flt(pr_rmd.consumed_qty)*flt(pr_rmd.rate))
-              pr_rmd.save()
-      if chgd_rqd_qty:
-        msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0])))
+					rm_child.reference_name = d.name
+					rm_child.bom_detail_no = i and i[6] or ''
+					rm_child.main_item_code = i and i[0] or ''
+					rm_child.rm_item_code = i and i[1] or ''
+					rm_child.description = i and i[7] or ''
+					rm_child.stock_uom = i and i[5] or ''
+					rm_child.rate = i and flt(i[3]) or flt(i[4])
+					rm_child.conversion_factor = d.conversion_factor
+					rm_child.required_qty = flt(i	and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
+					rm_child.consumed_qty = flt(i	and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
+					rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
+					rm_child.save()
+					chgd_rqd_qty.append(cstr(i[1]))
+				else:
+					act_qty = flt(i	and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
+					for pr_rmd in getlist(self.doclist, 'pr_raw_material_details'):
+						if i and i[6] == pr_rmd.bom_detail_no and (flt(act_qty) != flt(pr_rmd.required_qty) or i[1] != pr_rmd.rm_item_code or i[7] != pr_rmd.description):
+							chgd_rqd_qty.append(cstr(i[1]))
+							pr_rmd.main_item_code = i[0]
+							pr_rmd.rm_item_code = i[1]
+							pr_rmd.description = i[7]
+							pr_rmd.stock_uom = i[5]
+							pr_rmd.required_qty = flt(act_qty)
+							pr_rmd.consumed_qty = flt(act_qty)
+							pr_rmd.rate = i and flt(i[3]) or flt(i[4])
+							pr_rmd.amount = flt(flt(pr_rmd.consumed_qty)*flt(pr_rmd.rate))
+							pr_rmd.save()
+			if chgd_rqd_qty:
+				msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0])))
 
 
-  # Delete irrelevant raw material from PR Raw material details
-  #--------------------------------------------------------------
-  def delete_irrelevant_raw_material(self):
-    for d in getlist(self.doclist,'pr_raw_material_details'):
-      if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
-        d.parent = 'old_par:'+self.doc.name
-        d.save()
+	# Delete irrelevant raw material from PR Raw material details
+	#--------------------------------------------------------------
+	def delete_irrelevant_raw_material(self):
+		for d in getlist(self.doclist,'pr_raw_material_details'):
+			if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
+				d.parent = 'old_par:'+self.doc.name
+				d.save()
 
-  def calculate_amount(self, d):
-    amt = 0
-    for i in getlist(self.doclist,'pr_raw_material_details'):
+	def calculate_amount(self, d):
+		amt = 0
+		for i in getlist(self.doclist,'pr_raw_material_details'):
 
-      if(i.reference_name == d.name):
-        #if i.consumed_qty == 0:
-         # msgprint("consumed qty cannot be 0. Please Enter consumed qty ")
-          #raise Exception
-        i.amount = flt(i.consumed_qty)* flt(i.rate)
-        amt += i.amount
-    d.rm_supp_cost = amt
-    d.save()
+			if(i.reference_name == d.name):
+				#if i.consumed_qty == 0:
+				 # msgprint("consumed qty cannot be 0. Please Enter consumed qty ")
+					#raise Exception
+				i.amount = flt(i.consumed_qty)* flt(i.rate)
+				amt += i.amount
+		d.rm_supp_cost = amt
+		d.save()
 
 
-  # --------------- Back Flush function called on submit and on cancel from update stock
-  def bk_flush_supp_wh(self, is_submit):
-    for d in getlist(self.doclist, 'pr_raw_material_details'):
-      #--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled
-      consumed_qty = - flt(d.consumed_qty)
-      self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit)
+	# --------------- Back Flush function called on submit and on cancel from update stock
+	def bk_flush_supp_wh(self, is_submit):
+		for d in getlist(self.doclist, 'pr_raw_material_details'):
+			#--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled
+			consumed_qty = - flt(d.consumed_qty)
+			self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit)
 
 
-  # get current_stock
-  # ----------------
-  def get_current_stock(self):
-    for d in getlist(self.doclist, 'pr_raw_material_details'):
-      if self.doc.supplier_warehouse:
-        bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1)
-        d.current_stock = bin and flt(bin[0]['actual_qty']) or 0
+	# get current_stock
+	# ----------------
+	def get_current_stock(self):
+		for d in getlist(self.doclist, 'pr_raw_material_details'):
+			if self.doc.supplier_warehouse:
+				bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1)
+				d.current_stock = bin and flt(bin[0]['actual_qty']) or 0
 
 
 
@@ -427,15 +442,15 @@
 # OTHER CHARGES TRIGGER FUNCTIONS
 # ====================================================================================
 
-  # *********** Get Tax rate if account type is TAX ********************
-  def get_rate(self,arg):
-    return get_obj('Purchase Common').get_rate(arg,self)
+	# *********** Get Tax rate if account type is TAX ********************
+	def get_rate(self,arg):
+		return get_obj('Purchase Common').get_rate(arg,self)
 
-  # **** Pull details from other charges master (Get Other Charges) ****
-  def get_purchase_tax_details(self):
-    return get_obj('Purchase Common').get_purchase_tax_details(self)
+	# **** Pull details from other charges master (Get Other Charges) ****
+	def get_purchase_tax_details(self):
+		return get_obj('Purchase Common').get_purchase_tax_details(self)
 
-  # Repair Purchase Order
-  # ===========================================
-  def repair_purchase_receipt(self):
-    get_obj('Purchase Common').repair_curr_doctype_details(self)
+	# Repair Purchase Order
+	# ===========================================
+	def repair_purchase_receipt(self):
+		get_obj('Purchase Common').repair_curr_doctype_details(self)
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
index 7b9d294..ace16fb 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -25,8 +25,9 @@
 		from webnotes.utils import file_manager
 		fn, content = file_manager.get_file(filename[1])
 		
-		if not type(content) == str:
-			content = content.tostring()
+		# NOTE: Don't know why this condition exists
+		if not isinstance(content, basestring) and hasattr(content, 'tostring'):
+		  content = content.tostring()
 
 		return content
 
diff --git a/erpnext/support/doctype/support_ticket/__init__.py b/erpnext/support/doctype/support_ticket/__init__.py
index 3b05bda..1b09fc9 100644
--- a/erpnext/support/doctype/support_ticket/__init__.py
+++ b/erpnext/support/doctype/support_ticket/__init__.py
@@ -1,4 +1,5 @@
 import webnotes
+from webnotes.utils import cstr
 
 from webnotes.utils.email_lib.receive import POP3Mailbox
 
@@ -111,7 +112,7 @@
 			status = add_file_list('Support Ticket', doc.name, attachment['filename'], fid)
 			if not status:
 				doc.description = doc.description \
-					+ "\nCould not attach: " + str(attachment['filename'])
+					+ "\nCould not attach: " + cstr(attachment['filename'])
 				doc.save()
 			webnotes.conn.commit()
 
@@ -137,7 +138,7 @@
 		sendmail(\
 			recipients = [d.raised_by], \
 			sender = self.email_settings.support_email, \
-			subject = '['+d.name+'] ' + str(d.subject or ''), \
+			subject = '['+d.name+'] ' + cstr(d.subject), \
 			msg = response)
 		
 	def auto_close_tickets(self):
diff --git a/erpnext/utilities/doctype/bulk_rename_tool/bulk_rename_tool.py b/erpnext/utilities/doctype/bulk_rename_tool/bulk_rename_tool.py
index 62d4d83..bb9d9e6 100644
--- a/erpnext/utilities/doctype/bulk_rename_tool/bulk_rename_tool.py
+++ b/erpnext/utilities/doctype/bulk_rename_tool/bulk_rename_tool.py
@@ -76,7 +76,8 @@
 		from webnotes.utils import file_manager
 		fn, content = file_manager.get_file(fid)
 		
-		if not type(content) == str:
+		# NOTE: Don't know why this condition exists
+		if not isinstance(content, basestring) and hasattr(content, 'tostring'):
 		  content = content.tostring()
 
 		return content
diff --git a/index.html b/index.html
index 2793bd7..150a2cf 100644
--- a/index.html
+++ b/index.html
@@ -3,7 +3,7 @@
 	<meta charset="utf-8">
 	<title>ERPNext</title>
 	<meta name="author" content="">
-	<script type="text/javascript">window._version_number="140"
+	<script type="text/javascript">window._version_number="146"
 
 wn={}
 wn.provide=function(namespace){var nsl=namespace.split('.');var l=nsl.length;var parent=window;for(var i=0;i<l;i++){var n=nsl[i];if(!parent[n]){parent[n]={}}
diff --git a/version.num b/version.num
index acfba60..bc768da 100644
--- a/version.num
+++ b/version.num
@@ -1 +1 @@
-141
\ No newline at end of file
+146
\ No newline at end of file