Development is merged into Master
diff --git a/.gitignore b/.gitignore
index e9c8fc6..56149a0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
 *.pyc
 *.comp.js
-*.txt
 .DS_Store
 server_tools
 patch.log
diff --git a/accounts/Module Def/Accounts/Accounts.txt b/accounts/Module Def/Accounts/Accounts.txt
index 708a2c9..512b460 100644
--- a/accounts/Module Def/Accounts/Accounts.txt
+++ b/accounts/Module Def/Accounts/Accounts.txt
@@ -5,7 +5,7 @@
 	{
 		'creation': '2010-09-25 10:50:34',
 		'docstatus': 0,
-		'modified': '2011-07-15 10:43:04',
+		'modified': '2011-07-28 12:01:10',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -40,7 +40,7 @@
 		'module_icon': 'Accounts.gif',
 		'module_label': 'Accounts',
 		'module_name': 'Accounts',
-		'module_seq': 5,
+		'module_seq': 3,
 		'name': '__common__'
 	},
 
@@ -107,8 +107,9 @@
 
 	# Module Def Item
 	{
-		'display_name': 'Loan',
-		'doc_name': 'Loan',
+		'description': 'Lease Agreement for Vehicles',
+		'display_name': 'Lease Agreement',
+		'doc_name': 'Lease Agreement',
 		'doc_type': 'Forms',
 		'doctype': 'Module Def Item',
 		'idx': 6
@@ -354,6 +355,69 @@
 		'idx': 32
 	},
 
+	# Module Def Item
+	{
+		'display_name': 'Lease Agreement List',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 33
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Monthly Future Installment Inflows',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 34
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Overdue Age Wise',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 35
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Overdue List',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 36
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Receipts Client Wise',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 37
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Receipt Summary Month Wise',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 38
+	},
+
+	# Module Def Item
+	{
+		'display_name': 'Lease Yearly Future Installment Inflows',
+		'doc_name': 'GL Entry',
+		'doc_type': 'Reports',
+		'doctype': 'Module Def Item',
+		'idx': 39
+	},
+
 	# Module Def Role
 	{
 		'doctype': 'Module Def Role',
diff --git a/accounts/doctype/account/account.js b/accounts/doctype/account/account.js
index 071bf57..51cacda 100644
--- a/accounts/doctype/account/account.js
+++ b/accounts/doctype/account/account.js
@@ -72,16 +72,6 @@
   else alert("Please select master type");
 }
 
-/*
-// Get customer/supplier address
-// -----------------------------------------
-cur_frm.cscript.master_name = function(doc,cdt,cdn){
-  if(doc.master_name){
-    get_server_fields('get_address','','',doc,cdt,cdn);
-  }
-}
-*/
-
 // parent account get query
 // -----------------------------------------
 cur_frm.fields_dict['parent_account'].get_query = function(doc){
diff --git a/accounts/doctype/account/account.py b/accounts/doctype/account/account.py
index f5e4a6d..52c66a9 100644
--- a/accounts/doctype/account/account.py
+++ b/accounts/doctype/account/account.py
@@ -94,8 +94,8 @@
 	def convert_group_to_ledger(self):
 		if self.check_if_child_exists():
 			msgprint("Account: %s has existing child. You can not convert this account to ledger" % (self.doc.name), raise_exception=1)
-		elif self.check_prev_bal_exists():
-			msgprint("Account with balance can not be converted to ledger.", raise_exception=1)
+		elif self.check_gle_exists():
+			msgprint("Account with existing transaction can not be converted to ledger.", raise_exception=1)
 		else:
 			self.doc.group_or_ledger = 'Ledger'
 			self.doc.save()
@@ -104,8 +104,8 @@
 	# Convert ledger to group
 	# ==================================================================
 	def convert_ledger_to_group(self):
-		if self.check_prev_bal_exists():
-			msgprint("Account with balance can not be converted to group.", raise_exception=1)
+		if self.check_gle_exists():
+			msgprint("Account with existing transaction can not be converted to group.", raise_exception=1)
 		else:
 			self.doc.group_or_ledger = 'Group'
 			self.doc.save()
@@ -113,9 +113,9 @@
 
 	# Check if any previous balance exists
 	# ==================================================================
-	def check_prev_bal_exists(self):
-		bal = sql("select balance from `tabAccount Balance` where parent = '%s' and ifnull(balance, 0) > 0" % (self.doc.name))
-		return bal and flt(bal[0][0]) or 0
+	def check_gle_exists(self):
+		exists = sql("select name from `tabGL Entry` where account = '%s' and ifnull(is_cancelled, 'No') = 'No'" % (self.doc.name))
+		return exists and exists[0][0] or ''
 
 	# check if child exists
 	# ==================================================================
@@ -231,8 +231,8 @@
 	# Account with balance cannot be inactive
 	# ==================================================================
 	def check_balance_before_trash(self):
-		if flt(self.get_curr_bal()) != 0:
-			msgprint("Account with existing balance can not be trashed", raise_exception=1)
+		if self.check_gle_exists():
+			msgprint("Account with existing transaction can not be trashed", raise_exception=1)
 		if self.check_if_child_exists():
 			msgprint("Child account exists for this account. You can not trash this account.", raise_exception=1)
 
diff --git a/accounts/doctype/account/account.txt b/accounts/doctype/account/account.txt
index 9ce509c..bf48a24 100644
--- a/accounts/doctype/account/account.txt
+++ b/accounts/doctype/account/account.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1308829300',
+		'_last_update': '1309508836',
 		'allow_copy': 1,
 		'allow_trash': 1,
 		'colour': 'White:FFF',
@@ -179,7 +179,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -225,7 +225,7 @@
 		'options': '\nLedger\nGroup',
 		'permlevel': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -259,7 +259,7 @@
 		'oldfieldname': 'debit_or_credit',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -274,7 +274,7 @@
 		'oldfieldtype': 'Select',
 		'options': 'Yes\nNo',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -344,7 +344,7 @@
 		'options': 'Company',
 		'permlevel': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -455,7 +455,8 @@
 		'description': "Don't delete this field at any cost",
 		'doctype': 'DocField',
 		'fieldname': 'old_parent',
-		'fieldtype': 'Data',
+		'fieldtype': 'Link',
+		'options': 'Account', 
 		'hidden': 1,
 		'idx': 24,
 		'label': 'Old Parent',
@@ -517,4 +518,4 @@
 		'oldfieldtype': 'Small Text',
 		'permlevel': 1
 	}
-]
\ No newline at end of file
+]
diff --git a/accounts/doctype/account_balance/account_balance.txt b/accounts/doctype/account_balance/account_balance.txt
index a53def2..1d23bb2 100644
--- a/accounts/doctype/account_balance/account_balance.txt
+++ b/accounts/doctype/account_balance/account_balance.txt
@@ -174,7 +174,7 @@
 		'oldfieldname': 'fiscal_year',
 		'oldfieldtype': 'Link',
 		'options': 'Fiscal Year',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/bank_reconciliation/bank_reconciliation.py b/accounts/doctype/bank_reconciliation/bank_reconciliation.py
index 8434f62..3ba477b 100644
--- a/accounts/doctype/bank_reconciliation/bank_reconciliation.py
+++ b/accounts/doctype/bank_reconciliation/bank_reconciliation.py
@@ -18,32 +18,32 @@
 
 
 class DocType:
-  def __init__(self, d, dl):
-    self.doc, self.doclist = d, dl
+	def __init__(self, d, dl):
+		self.doc, self.doclist = d, dl
 
-  def get_details(self):
-    if not (self.doc.bank_account and self.doc.from_date and self.doc.to_date):
-      msgprint("Bank Account, From Date and To Date are Mandatory")
-      return
-  
-    dl = sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and (t1.cheque_no is not null or t1.cheque_no != '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
-    
-    self.doc.clear_table(self.doclist, 'entries')
-    self.doc.total_amount = 0.0
+	def get_details(self):
+		if not (self.doc.bank_account and self.doc.from_date and self.doc.to_date):
+			msgprint("Bank Account, From Date and To Date are Mandatory")
+			return
+	
+		dl = sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and (t1.cheque_no is not null or t1.cheque_no != '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
+		
+		self.doc.clear_table(self.doclist, 'entries')
+		self.doc.total_amount = 0.0
 
-    for d in dl:
-      nl = addchild(self.doc, 'entries', 'Bank Reconciliation Detail', 1, self.doclist)
-      nl.posting_date = str(d[5])
-      nl.voucher_id = str(d[0])
-      nl.cheque_number = str(d[1])
-      nl.cheque_date = str(d[2])
-      nl.debit = flt(d[3])
-      nl.credit = flt(d[4])
-      nl.against_account = d[6]
-      self.doc.total_amount += flt(flt(d[4]) - flt(d[3]))
+		for d in dl:
+			nl = addchild(self.doc, 'entries', 'Bank Reconciliation Detail', 1, self.doclist)
+			nl.posting_date = str(d[5])
+			nl.voucher_id = str(d[0])
+			nl.cheque_number = str(d[1])
+			nl.cheque_date = str(d[2])
+			nl.debit = flt(d[3])
+			nl.credit = flt(d[4])
+			nl.against_account = d[6]
+			self.doc.total_amount += flt(flt(d[4]) - flt(d[3]))
 
-  def update_details(self):
-    for d in getlist(self.doclist, 'entries'):
-      if d.clearance_date:
-        sql("update `tabJournal Voucher` set clearance_date = %s where name=%s", (d.clearance_date, d.voucher_id))
-    msgprint("Updated")
\ No newline at end of file
+	def update_details(self):
+		for d in getlist(self.doclist, 'entries'):
+			if d.clearance_date:
+				sql("update `tabJournal Voucher` set clearance_date = %s, modified = %s where name=%s", (d.clearance_date, nowdate(), d.voucher_id))
+		msgprint("Updated")
diff --git a/accounts/doctype/cost_center/cost_center.py b/accounts/doctype/cost_center/cost_center.py
index 060225d..521712b 100644
--- a/accounts/doctype/cost_center/cost_center.py
+++ b/accounts/doctype/cost_center/cost_center.py
@@ -31,7 +31,7 @@
     ret = {
       'company_abbr'  : abbr
     }
-    return cstr(ret)
+    return ret
 
   def validate(self): 
     # Cost Center name must be unique
diff --git a/accounts/doctype/cost_center/cost_center.txt b/accounts/doctype/cost_center/cost_center.txt
index ce39929..fab2dd5 100644
--- a/accounts/doctype/cost_center/cost_center.txt
+++ b/accounts/doctype/cost_center/cost_center.txt
@@ -182,6 +182,7 @@
 		'options': 'Company',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -227,7 +228,8 @@
 		'oldfieldname': 'distribution_id',
 		'oldfieldtype': 'Link',
 		'options': 'Budget Distribution',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/fiscal_year/fiscal_year.txt b/accounts/doctype/fiscal_year/fiscal_year.txt
index fe02b34..4a7f49a 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.txt
+++ b/accounts/doctype/fiscal_year/fiscal_year.txt
@@ -182,7 +182,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Company',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/form_16a/form_16a.py b/accounts/doctype/form_16a/form_16a.py
index 292c52a..0bcef6b 100644
--- a/accounts/doctype/form_16a/form_16a.py
+++ b/accounts/doctype/form_16a/form_16a.py
@@ -39,7 +39,7 @@
 				'company_address': cstr(comp_det[0][0]),
 				'registration_details': cstr(comp_det[0][1])
 			}	 
-		return cstr(ret)		
+		return ret
     
 	# Get party details
 	#------------------
diff --git a/accounts/doctype/gl_entry/gl_entry.txt b/accounts/doctype/gl_entry/gl_entry.txt
index 7278c4d..776cbb3 100644
--- a/accounts/doctype/gl_entry/gl_entry.txt
+++ b/accounts/doctype/gl_entry/gl_entry.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1294312170',
+		'_last_update': '1309508838',
 		'autoname': 'GL.#######',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
@@ -119,7 +119,7 @@
 		'label': 'Aging Date',
 		'oldfieldname': 'aging_date',
 		'oldfieldtype': 'Date',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -221,7 +221,7 @@
 		'oldfieldname': 'voucher_type',
 		'oldfieldtype': 'Select',
 		'options': 'Journal Voucher\nReceivable Voucher\nPayable Voucher',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -262,7 +262,7 @@
 		'oldfieldname': 'is_cancelled',
 		'oldfieldtype': 'Select',
 		'options': 'No\nYes',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -276,7 +276,7 @@
 		'oldfieldname': 'is_opening',
 		'oldfieldtype': 'Select',
 		'options': 'No\nYes',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -304,7 +304,7 @@
 		'oldfieldname': 'fiscal_year',
 		'oldfieldtype': 'Select',
 		'options': 'link:Fiscal Year',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -318,6 +318,6 @@
 		'oldfieldname': 'company',
 		'oldfieldtype': 'Link',
 		'options': 'Company',
-		'search_index': 1
+		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/accounts/doctype/journal_voucher/journal_voucher.js b/accounts/doctype/journal_voucher/journal_voucher.js
index dce570b..f65ee31 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.js
+++ b/accounts/doctype/journal_voucher/journal_voucher.js
@@ -1,9 +1,5 @@
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
   var cp = locals['Control Panel']['Control Panel'];
-  if(doc.__islocal){
-    doc.clearance_date ='';
-    refresh_field('clearance_date');
-  }
   
   if (!doc.voucher_date) doc.voucher_date = dateutil.obj_to_str(new Date());
 
@@ -155,4 +151,4 @@
     report.dt.run();
   }
   loadreport('GL Entry','General Ledger', callback);
-}
\ No newline at end of file
+}
diff --git a/accounts/doctype/journal_voucher/journal_voucher.py b/accounts/doctype/journal_voucher/journal_voucher.py
index 4f5e67a..5942ca1 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.py
+++ b/accounts/doctype/journal_voucher/journal_voucher.py
@@ -38,9 +38,9 @@
     args = eval(args)
     o_s = sql("select outstanding_amount from `tab%s` where name = '%s'" % (args['doctype'],args['docname']))
     if args['doctype'] == 'Payable Voucher':
-      return cstr({'debit': o_s and flt(o_s[0][0]) or 0})
+      return {'debit': o_s and flt(o_s[0][0]) or 0}
     if args['doctype'] == 'Receivable Voucher':
-      return cstr({'credit': o_s and flt(o_s[0][0]) or 0})
+      return {'credit': o_s and flt(o_s[0][0]) or 0}
 
   #--------------------------------------------------------------------------------------------------------
   # Create remarks
diff --git a/accounts/doctype/journal_voucher/journal_voucher.txt b/accounts/doctype/journal_voucher/journal_voucher.txt
index c40be8f..104d3d1 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.txt
+++ b/accounts/doctype/journal_voucher/journal_voucher.txt
@@ -5,14 +5,14 @@
 	{
 		'creation': '2010-08-08 17:09:06',
 		'docstatus': 0,
-		'modified': '2011-07-15 14:37:05',
+		'modified': '2011-07-28 15:28:12',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1310533805',
+		'_last_update': '1311251040',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'module': 'Accounts',
@@ -23,7 +23,7 @@
 		'show_in_menu': 0,
 		'subject': ' ',
 		'tag_fields': 'voucher_type',
-		'version': 308
+		'version': 309
 	},
 
 	# These values are common for all DocField
diff --git a/accounts/doctype/journal_voucher_detail/journal_voucher_detail.txt b/accounts/doctype/journal_voucher_detail/journal_voucher_detail.txt
index 39da084..4a350c2 100644
--- a/accounts/doctype/journal_voucher_detail/journal_voucher_detail.txt
+++ b/accounts/doctype/journal_voucher_detail/journal_voucher_detail.txt
@@ -69,7 +69,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
 		'permlevel': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '180px'
 	},
 
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/doctype/lease_agreement/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/doctype/lease_agreement/__init__.py
diff --git a/accounts/doctype/lease_agreement/lease_agreement.js b/accounts/doctype/lease_agreement/lease_agreement.js
new file mode 100644
index 0000000..8ffd522
--- /dev/null
+++ b/accounts/doctype/lease_agreement/lease_agreement.js
@@ -0,0 +1,78 @@
+$.extend(cur_frm.cscript, {
+	Generate: function(doc, dt, dn) {
+		if(doc.installment_amount==''){
+			msgprint('Set Installment Amount before generating schedule');
+			return;
+		}
+		if(doc.no_of_installments==''){
+			msgprint('Set Number of Installments before generating schedule');
+			return;
+		}
+		if(doc.start_date==''){
+			msgprint('Set Start Date before generating schedule');
+			return;
+		}
+		cur_frm.cscript.clear_installments(doc);
+		tot=0;i=0;
+		while(tot<flt(doc.invoice_amount)-flt(doc.down_payment)){
+				d = LocalDB.add_child(doc, 'Lease Installment', 'installments');
+				d.amount = flt(doc.installment_amount) < flt(doc.invoice_amount)-flt(doc.down_payment)-tot ? flt(doc.installment_amount) : flt(doc.invoice_amount)-flt(doc.down_payment)-tot
+				d.due_date = dateutil.add_months(doc.start_date, i+1);
+				tot += flt(doc.installment_amount)
+				i++;
+		}
+		cur_frm.refresh();
+	},
+	refresh: function(doc) {
+		cur_frm.cscript.hide_show_buttons(doc);
+	},
+	hide_show_buttons: function(doc) {
+		if(doc.docstatus==0) {
+			hide_field('Installment Reciept'); show_field('Generate');
+		} else if (doc.docstatus==1) {
+			show_field('Installment Reciept');hide_field('Generate');
+		}
+	},
+	clear_installments: function(doc) {
+		$.each(getchildren('Lease Installment', doc.name, 'installments', 'Lease Agreement'),
+			function(i, d) {
+				LocalDB.delete_doc('Lease Installment', d.name);
+			}
+		)
+	},
+	no_of_installments: function(doc)
+	{
+		if(flt(doc.no_of_installments)!=0) {
+			doc.installment_amount = (flt(doc.invoice_amount)- flt(doc.down_payment))/flt(doc.no_of_installments);
+			refresh_field('installment_amount');
+		}
+	},
+	'Installment Reciept': function(doc, dt, dn) {
+		var d = new wn.widgets.Dialog({
+			width: 500,
+			title: 'Add a new payment installment',
+			fields: [
+				{fieldtype:'Data', label:'Cheque Number', fieldname:'cheque_number', reqd:1},
+				{fieldtype:'Date', label:'Cheque Date', fieldname:'cheque_date', reqd:1},
+				{fieldtype:'Link', label:'Bank Account', fieldname:'bank_account', reqd:1, options:'Account'},
+				{fieldtype:'Button', label:'Update',fieldname:'update'}
+			]
+		})
+		d.show();
+		d.fields_dict.update.input.onclick = function() {
+			var data = d.get_values();
+
+			if(data) {
+				$c_obj(make_doclist(dt,dn),'lease_installment_post',data,function(){cur_frm.refresh(); d.hide();});
+			}
+		}
+	}
+})
+
+
+cur_frm.add_fetch('invoice','grand_total','invoice_amount');
+
+cur_frm.fields_dict.invoice.get_query=function(doc){
+
+	return "SELECT tv.name FROM `tabReceivable Voucher` tv WHERE debit_to='"+doc.account+"' and  tv.%(key)s like '%s' ORDER BY tv.name LIMIT 50"
+}
\ No newline at end of file
diff --git a/accounts/doctype/lease_agreement/lease_agreement.py b/accounts/doctype/lease_agreement/lease_agreement.py
new file mode 100644
index 0000000..dd63c2e
--- /dev/null
+++ b/accounts/doctype/lease_agreement/lease_agreement.py
@@ -0,0 +1,37 @@
+import webnotes
+from webnotes.model.doc import make_autoname, Document, addchild
+from webnotes import msgprint
+from webnotes.utils import get_defaults
+import json
+from accounts.utils import post_jv
+sql = webnotes.conn.sql
+
+class DocType:
+	def __init__(self, doc, doclist):
+		self.doc, self.doclist = doc, doclist
+
+	def autoname(self):
+		"""
+			Create Lease Id using naming_series pattern
+		"""
+		self.doc.name = make_autoname(self.doc.naming_series+ '.#####')
+
+	def lease_installment_post(self, args):
+		"""
+			Posts the Installment receipt into Journal Voucher
+		"""
+		next_inst = sql("select amount,name from `tabLease Installment` where parent=%s and ifnull(cheque_number,'')='' order by due_date limit 1",self.doc.name)
+
+		data = json.loads(args)
+		data['voucher_type']='Lease Receipt'
+		data['naming_series']='JV'
+		data['amount']=next_inst[0][0]
+		data['debit_account']=data.get('bank_account')
+		data['credit_account']=self.doc.account
+		data['fiscal_year']=get_defaults()['fiscal_year']
+		data['company']=get_defaults()['company']
+		jv_name=post_jv(data)
+
+		sql("update `tabLease Installment` set cheque_number=%s, cheque_date=%s, jv_number=%s where name=%s",(data.get('cheque_number'),data.get('cheque_date'),jv_name,next_inst[0][1]))
+
+		self.doclist = [Document(d.doctype, d.name) for d in self.doclist]
diff --git a/accounts/doctype/lease_agreement/lease_agreement.txt b/accounts/doctype/lease_agreement/lease_agreement.txt
new file mode 100644
index 0000000..c221020
--- /dev/null
+++ b/accounts/doctype/lease_agreement/lease_agreement.txt
@@ -0,0 +1,310 @@
+# DocType, Lease Agreement
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-22 17:47:57',
+		'docstatus': 0,
+		'modified': '2011-07-27 15:33:55',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all DocType
+	{
+		'_last_update': '1311555967',
+		'colour': 'White:FFF',
+		'doctype': 'DocType',
+		'module': 'Accounts',
+		'name': '__common__',
+		'section_style': 'Simple',
+		'show_in_menu': 0,
+		'version': 21
+	},
+
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'name': '__common__',
+		'parent': 'Lease Agreement',
+		'parentfield': 'fields',
+		'parenttype': 'DocType'
+	},
+
+	# These values are common for all DocPerm
+	{
+		'doctype': 'DocPerm',
+		'name': '__common__',
+		'parent': 'Lease Agreement',
+		'parentfield': 'permissions',
+		'parenttype': 'DocType',
+		'read': 1
+	},
+
+	# DocType, Lease Agreement
+	{
+		'doctype': 'DocType',
+		'name': 'Lease Agreement'
+	},
+
+	# DocPerm
+	{
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'idx': 1,
+		'permlevel': 0,
+		'role': 'Accounts User',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm',
+		'idx': 2,
+		'permlevel': 1,
+		'role': 'Accounts User'
+	},
+
+	# DocPerm
+	{
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'idx': 3,
+		'permlevel': 0,
+		'role': 'Accounts Manager',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm',
+		'idx': 4,
+		'permlevel': 1,
+		'role': 'Accounts Manager'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'naming_series',
+		'fieldtype': 'Select',
+		'idx': 1,
+		'label': 'Naming Series',
+		'options': '\nLA',
+		'permlevel': 0,
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 2,
+		'label': 'Lessee Info.',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'account',
+		'fieldtype': 'Link',
+		'idx': 3,
+		'label': 'Lessee Account',
+		'options': 'Account',
+		'permlevel': 0,
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'lessee_father',
+		'fieldtype': 'Data',
+		'idx': 4,
+		'label': 'Lessee Father',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'lessee_nic',
+		'fieldtype': 'Data',
+		'idx': 5,
+		'label': 'Lessee NIC',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'lessee_contact',
+		'fieldtype': 'Data',
+		'idx': 6,
+		'label': 'Lessee Contact',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'lessee_address',
+		'fieldtype': 'Text',
+		'idx': 7,
+		'label': 'Lessee Address',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 8,
+		'label': 'Vehicle Info.',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'model_no',
+		'fieldtype': 'Data',
+		'idx': 9,
+		'label': 'Model No',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'engine_no',
+		'fieldtype': 'Data',
+		'idx': 10,
+		'label': 'Engine No',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'chassis_no',
+		'fieldtype': 'Data',
+		'idx': 11,
+		'label': 'Chassis No',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 12,
+		'label': 'Invoice and Payment Info.',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldname': 'invoice',
+		'fieldtype': 'Link',
+		'idx': 13,
+		'label': 'Invoice',
+		'options': 'Receivable Voucher',
+		'permlevel': 0,
+		'reqd': 1,
+		'trigger': 'Client'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'invoice_amount',
+		'fieldtype': 'Currency',
+		'idx': 14,
+		'label': 'Invoice Amount',
+		'permlevel': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'down_payment',
+		'fieldtype': 'Currency',
+		'idx': 15,
+		'label': 'Down Payment',
+		'permlevel': 0,
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'start_date',
+		'fieldtype': 'Date',
+		'idx': 16,
+		'label': 'Start Date',
+		'permlevel': 0,
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'no_of_installments',
+		'fieldtype': 'Int',
+		'idx': 17,
+		'label': 'No of Installments',
+		'permlevel': 0,
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'installment_amount',
+		'fieldtype': 'Currency',
+		'idx': 18,
+		'label': 'Installment Amount',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 19,
+		'label': 'Generate',
+		'permlevel': 0,
+		'trigger': 'Client'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'installments',
+		'fieldtype': 'Table',
+		'idx': 20,
+		'label': 'Installments',
+		'options': 'Lease Installment',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'allow_on_submit': 1,
+		'colour': 'White:FFF',
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 21,
+		'label': 'Installment Reciept',
+		'permlevel': 0
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/doctype/lease_installment/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/doctype/lease_installment/__init__.py
diff --git a/accounts/doctype/lease_installment/lease_installment.txt b/accounts/doctype/lease_installment/lease_installment.txt
new file mode 100644
index 0000000..2434a78
--- /dev/null
+++ b/accounts/doctype/lease_installment/lease_installment.txt
@@ -0,0 +1,91 @@
+# DocType, Lease Installment
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-22 17:49:33',
+		'docstatus': 0,
+		'modified': '2011-07-22 17:49:33',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all DocType
+	{
+		'colour': 'White:FFF',
+		'doctype': 'DocType',
+		'istable': 1,
+		'module': 'Accounts',
+		'name': '__common__',
+		'section_style': 'Simple',
+		'show_in_menu': 0,
+		'version': 5
+	},
+
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'name': '__common__',
+		'parent': 'Lease Installment',
+		'parentfield': 'fields',
+		'parenttype': 'DocType'
+	},
+
+	# DocType, Lease Installment
+	{
+		'doctype': 'DocType',
+		'name': 'Lease Installment'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'amount',
+		'fieldtype': 'Currency',
+		'idx': 1,
+		'label': 'Amount',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'due_date',
+		'fieldtype': 'Date',
+		'idx': 2,
+		'label': 'Due Date',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'cheque_number',
+		'fieldtype': 'Data',
+		'idx': 3,
+		'label': 'Cheque Number',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'cheque_date',
+		'fieldtype': 'Date',
+		'idx': 4,
+		'label': 'Cheque Date',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'jv_number',
+		'fieldtype': 'Link',
+		'hidden': 0,
+		'idx': 5,
+		'label': 'JV Number',
+		'options': 'Journal Voucher',
+		'permlevel': 1
+	}
+]
\ No newline at end of file
diff --git a/accounts/doctype/payable_voucher/payable_voucher.py b/accounts/doctype/payable_voucher/payable_voucher.py
index 0e930e3..e88066a 100644
--- a/accounts/doctype/payable_voucher/payable_voucher.py
+++ b/accounts/doctype/payable_voucher/payable_voucher.py
@@ -48,14 +48,14 @@
 				ret['due_date'] = add_days(cstr(self.doc.posting_date), acc_head and cint(acc_head[0][1]) or 0)
 		elif not acc_head:
 			msgprint("%s does not have an Account Head in %s. You must first create it from the Supplier Master" % (self.doc.supplier, self.doc.company))
-		return cstr(ret)
+		return ret
 		
 	def get_cust(self):
 		ret = {}
 		if self.doc.credit_to:			
 			ret['supplier'] = get_value('Account',self.doc.credit_to,'master_name')
 			
-		return cstr(ret)	
+		return ret
 
 
 	# Get Default Cost Center and Expense Head from Item Master
@@ -70,7 +70,7 @@
 			if not args['cost_center'] or args['cost_center'] == 'undefined':
 				cost_center = sql("select cost_center from `tabItem` where name = '%s'" % args['item_code'])
 				ret['cost_center'] = cost_center and cost_center[0][0] or ''
-		return cstr(ret)
+		return ret
 		 
 	
 	# Get Items based on PO or PR
@@ -115,7 +115,7 @@
 			'cost_center' : item_det and item_det[0]['cost_center'] or '',
 			'item_tax_rate'			: str(t)
 		}
-		return cstr(ret)
+		return ret
 		
 	# Advance Allocation
 	# -------------------
@@ -139,7 +139,7 @@
 	def get_rate1(self,acc):
 		rate = sql("select tax_rate from `tabAccount` where name='%s'"%(acc))
 		ret={'add_tax_rate' :rate and flt(rate[0][0]) or 0 }
-		return cstr(ret)
+		return ret
 	
 
 # *************************** Server Utility Functions *****************************
diff --git a/accounts/doctype/payable_voucher/payable_voucher.txt b/accounts/doctype/payable_voucher/payable_voucher.txt
index c330e8d..c77db19 100644
--- a/accounts/doctype/payable_voucher/payable_voucher.txt
+++ b/accounts/doctype/payable_voucher/payable_voucher.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1308741898',
+		'_last_update': '1309508838',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'module': 'Accounts',
@@ -221,6 +221,7 @@
 		'options': 'Supplier',
 		'permlevel': 0,
 		'print_hide': 1,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -326,7 +327,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -342,7 +343,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'print_hide': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -378,7 +379,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -394,7 +395,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -690,7 +691,7 @@
 		'options': 'No\nYes',
 		'permlevel': 0,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -768,7 +769,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -785,7 +786,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -1084,7 +1085,7 @@
 		'oldfieldtype': 'Currency',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index ed42459..c7e5db6 100644
--- a/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -129,7 +129,7 @@
 
     # save
     le.save(1)
-    le_obj.on_update(adv_adj = '')
+    le_obj.on_update(adv_adj = '', cancel = '')
     
 
   # Reposting Balances
diff --git a/accounts/doctype/period_closing_voucher/period_closing_voucher.txt b/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
index e5bb1a2..5850887 100644
--- a/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
+++ b/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
@@ -147,7 +147,8 @@
 		'oldfieldtype': 'Select',
 		'options': 'link:Fiscal Year',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/accounts/doctype/pos_setting/pos_setting.txt b/accounts/doctype/pos_setting/pos_setting.txt
index 7b1b9fa..3809d67 100755
--- a/accounts/doctype/pos_setting/pos_setting.txt
+++ b/accounts/doctype/pos_setting/pos_setting.txt
@@ -172,7 +172,8 @@
 		'oldfieldname': 'company',
 		'oldfieldtype': 'Link',
 		'options': 'Company',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -193,7 +194,8 @@
 		'oldfieldname': 'customer_account',
 		'oldfieldtype': 'Link',
 		'options': 'Account',
-		'reqd': 0
+		'reqd': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -206,7 +208,8 @@
 		'oldfieldname': 'cash_bank_account',
 		'oldfieldtype': 'Link',
 		'options': 'Account',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -219,7 +222,8 @@
 		'oldfieldname': 'income_account',
 		'oldfieldtype': 'Link',
 		'options': 'Account',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -232,7 +236,8 @@
 		'oldfieldname': 'warehouse',
 		'oldfieldtype': 'Link',
 		'options': 'Warehouse',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -245,7 +250,8 @@
 		'oldfieldname': 'cost_center',
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -257,7 +263,8 @@
 		'label': 'Charge',
 		'oldfieldname': 'charge',
 		'oldfieldtype': 'Link',
-		'options': 'Other Charges'
+		'options': 'Other Charges',
+		'search_index': 0
 	},
 
 	# DocField
@@ -282,7 +289,8 @@
 		'label': 'Terms',
 		'oldfieldname': 'tc_name',
 		'oldfieldtype': 'Link',
-		'options': 'Term'
+		'options': 'Term',
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/purchase_tax_detail/purchase_tax_detail.txt b/accounts/doctype/purchase_tax_detail/purchase_tax_detail.txt
index 583a97f..ed67ba2 100644
--- a/accounts/doctype/purchase_tax_detail/purchase_tax_detail.txt
+++ b/accounts/doctype/purchase_tax_detail/purchase_tax_detail.txt
@@ -151,6 +151,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
 		'permlevel': 0,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
diff --git a/accounts/doctype/pv_detail/pv_detail.txt b/accounts/doctype/pv_detail/pv_detail.txt
index 0243d71..1e05160 100644
--- a/accounts/doctype/pv_detail/pv_detail.txt
+++ b/accounts/doctype/pv_detail/pv_detail.txt
@@ -111,7 +111,7 @@
 		'options': 'Item Group',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/receivable_voucher/receivable_voucher.py b/accounts/doctype/receivable_voucher/receivable_voucher.py
index cb62a65..185b0b1 100644
--- a/accounts/doctype/receivable_voucher/receivable_voucher.py
+++ b/accounts/doctype/receivable_voucher/receivable_voucher.py
@@ -90,7 +90,7 @@
 	def get_debit_to(self):
 		acc_head = self.get_customer_account()
 		if acc_head:
-			return cstr({ 'debit_to' : acc_head })
+			return { 'debit_to' : acc_head }
 
 
 	# Set Due Date = Posting Date + Credit Days
@@ -515,7 +515,7 @@
 		ret = {
 			 'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
 		}
-		return cstr(ret)
+		return ret
 
 	# Make GL Entries
 	# -------------------------
diff --git a/accounts/doctype/receivable_voucher/receivable_voucher.txt b/accounts/doctype/receivable_voucher/receivable_voucher.txt
index bcad9cc..f2f9eaf 100644
--- a/accounts/doctype/receivable_voucher/receivable_voucher.txt
+++ b/accounts/doctype/receivable_voucher/receivable_voucher.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1308741898',
+		'_last_update': '1309508839',
 		'change_log': '1. Change in pull_details method dt.-26-06-2009',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
@@ -323,7 +323,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -342,7 +342,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -433,7 +433,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -903,7 +903,7 @@
 		'options': 'No\nYes',
 		'permlevel': 0,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -1027,7 +1027,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -1045,7 +1045,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -1116,7 +1116,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/rv_detail/rv_detail.txt b/accounts/doctype/rv_detail/rv_detail.txt
index 6950ca9..94a4583 100644
--- a/accounts/doctype/rv_detail/rv_detail.txt
+++ b/accounts/doctype/rv_detail/rv_detail.txt
@@ -243,6 +243,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
+		'search_index': 1,
 		'trigger': 'Client',
 		'width': '120px'
 	},
@@ -262,6 +263,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
+		'search_index': 1,
 		'trigger': 'Client',
 		'width': '120px'
 	},
diff --git a/accounts/doctype/rv_tax_detail/rv_tax_detail.txt b/accounts/doctype/rv_tax_detail/rv_tax_detail.txt
index 94846cb..a9326a0 100644
--- a/accounts/doctype/rv_tax_detail/rv_tax_detail.txt
+++ b/accounts/doctype/rv_tax_detail/rv_tax_detail.txt
@@ -80,7 +80,8 @@
 		'oldfieldname': 'cost_center_other_charges',
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/tds_category_account/tds_category_account.txt b/accounts/doctype/tds_category_account/tds_category_account.txt
index 88ee39a..6f6022b 100644
--- a/accounts/doctype/tds_category_account/tds_category_account.txt
+++ b/accounts/doctype/tds_category_account/tds_category_account.txt
@@ -51,7 +51,7 @@
 		'label': 'Company',
 		'oldfieldname': 'company',
 		'options': 'Company',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/accounts/doctype/tds_payment/tds_payment.py b/accounts/doctype/tds_payment/tds_payment.py
index c91a269..5079d04 100644
--- a/accounts/doctype/tds_payment/tds_payment.py
+++ b/accounts/doctype/tds_payment/tds_payment.py
@@ -34,7 +34,7 @@
     else:
       ret = { 'registration_details': cstr(comp_det[0][0])}
    
-    return cstr(ret)
+    return ret
 
   # Get default bank and tds account
   #------------------------------------
diff --git a/accounts/doctype/tds_payment/tds_payment.txt b/accounts/doctype/tds_payment/tds_payment.txt
index abd4b0c..8d0edfb 100644
--- a/accounts/doctype/tds_payment/tds_payment.txt
+++ b/accounts/doctype/tds_payment/tds_payment.txt
@@ -207,7 +207,7 @@
 		'options': 'link:Fiscal Year',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -269,7 +269,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Company',
 		'permlevel': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
diff --git a/accounts/search_criteria/accounts_payable/accounts_payable.py b/accounts/search_criteria/accounts_payable/accounts_payable.py
index 53fff08..8c07b68 100644
--- a/accounts/search_criteria/accounts_payable/accounts_payable.py
+++ b/accounts/search_criteria/accounts_payable/accounts_payable.py
@@ -2,134 +2,145 @@
 # ------------------------------------------------------------------
 
 if not filter_values.get('posting_date') or not filter_values.get('posting_date1'):
-  msgprint("Please select From Posting Date and To Posting Date ")
-  raise Exception
+	msgprint("Please select From Posting Date and To Posting Date ")
+	raise Exception
 else:
-  from_date = filter_values.get('posting_date')
-  to_date = filter_values.get('posting_date1')
+	from_date = filter_values.get('posting_date')
+	to_date = filter_values.get('posting_date1')
 
 if not filter_values['range_1'] or not filter_values['range_2'] or not filter_values['range_3'] or not filter_values['range_4']:
-  msgprint("Please select aging ranges in no of days in 'More Filters' ")
-  raise Exception
+	msgprint("Please select aging ranges in no of days in 'More Filters' ")
+	raise Exception
 
 # validate Range
 range_list = ['range_1','range_2','range_3','range_4']
 for r in range(len(range_list)-1):
-  if not cint(filter_values[range_list[r]]) < cint(filter_values[range_list[r + 1]]):
-    msgprint("Range %s should be less than Range %s." % (cstr(r+1),cstr(r+2)))
-    raise Exception
+	if not cint(filter_values[range_list[r]]) < cint(filter_values[range_list[r + 1]]):
+		msgprint("Range %s should be less than Range %s." % (cstr(r+1),cstr(r+2)))
+		raise Exception
 
-  
+	
 # Add columns
 # ------------------------------------------------------------------
 data = [['Aging Date','Date','80px',''],
-        ['Transaction Date','Date','80px',''],
-        ['Account','Data','120px',''],
-        ['Against Voucher Type','Data','120px',''],
-        ['Against Voucher','Data','120px',''],
-        ['Voucher Type','Data','120px',''],
-        ['Voucher No','Data','120px',''],
-        ['Remarks','Data','160px',''],
-        ['Supplier Type', 'Data', '80px', ''],
-        ['Due Date', 'Data', '80px', ''],
-        ['Bill No','Data','80px',''],
-        ['Bill Date','Data','80px',''],
-        ['Opening Amt','Currency','120px',''],
-        ['Outstanding Amt','Currency','120px',''],
-        ['Age (Days)', 'Currency', '150px', ''],
-        ['0-'+cstr(filter_values['range_1']),'Currency','100px',''],
-        [cstr(cint(filter_values['range_1']) + 1)+ '-' +cstr(filter_values['range_2']),'Currency','100px',''],
-        [cstr(cint(filter_values['range_2']) + 1)+ '-' +cstr(filter_values['range_3']),'Currency','100px',''],
-        [cstr(cint(filter_values['range_3']) + 1)+ '-' +cstr(filter_values['range_4']),'Currency','100px',''],
-        [cstr(filter_values['range_4']) + '-Above','Currency','100px','']]
-        
+				['Transaction Date','Date','80px',''],
+				['Account','Data','120px',''],
+				['Against Voucher Type','Data','120px',''],
+				['Against Voucher','Data','120px',''],
+				['Voucher Type','Data','120px',''],
+				['Voucher No','Data','120px',''],
+				['Remarks','Data','160px',''],
+				['Supplier Type', 'Data', '80px', ''],
+				['Due Date', 'Data', '80px', ''],
+				['Bill No','Data','80px',''],
+				['Bill Date','Data','80px',''],
+				['Opening Amt','Currency','120px',''],
+				['Outstanding Amt','Currency','120px',''],
+				['Age (Days)', 'Currency', '150px', ''],
+				['0-'+cstr(filter_values['range_1']),'Currency','100px',''],
+				[cstr(cint(filter_values['range_1']) + 1)+ '-' +cstr(filter_values['range_2']),'Currency','100px',''],
+				[cstr(cint(filter_values['range_2']) + 1)+ '-' +cstr(filter_values['range_3']),'Currency','100px',''],
+				[cstr(cint(filter_values['range_3']) + 1)+ '-' +cstr(filter_values['range_4']),'Currency','100px',''],
+				[cstr(filter_values['range_4']) + '-Above','Currency','100px','']]
+				
 
 for d in data:
-  colnames.append(d[0])
-  coltypes.append(d[1])
-  colwidths.append(d[2])
-  coloptions.append(d[3])
-  col_idx[d[0]] = len(colnames)-1
-  
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+	
 # ageing based on
 # ------------------------------------------------------------------
 aging_based_on = 'Aging Date'
 if filter_values.has_key('aging_based_on') and filter_values['aging_based_on']:
-  aging_based_on = filter_values['aging_based_on'].split(NEWLINE)[-1]
+	aging_based_on = filter_values['aging_based_on'].split(NEWLINE)[-1]
 
-if  len(res) > 600 and from_export == 0:
-  msgprint("This is a very large report and cannot be shown in the browser as it is likely to make your browser very slow.Please select Account or click on 'Export' to open in excel")
-  raise Exception
+if	len(res) > 600 and from_export == 0:
+	msgprint("This is a very large report and cannot be shown in the browser as it is likely to make your browser very slow.Please select Account or click on 'Export' to open in excel")
+	raise Exception
 
 
 # ------------------------------------------------------------------
 # main loop starts here
 # ------------------------------------------------------------------
 
+# get supplier type
+supp_type_dict = {}
+for each in sql("select t2.name, t1.supplier_type from tabSupplier t1, tabAccount t2 where t1.name = t2.account_name group by t2.name"):
+	supp_type_dict[each[0]] = each[1]
+
+# get due_date, bill_no, bill_date from PV
+pv_dict = {}
+for t in sql("select name, due_date, bill_no, bill_date from `tabPayable Voucher` group by name"):
+	pv_dict[t[0]] = [cstr(t[1]), t[2], cstr(t[3])]
+
+# pv outside this period
+pv_outside_period = [d[0] for d in sql("select distinct name from `tabPayable Voucher` where (posting_date < '%s' or posting_date > '%s') and docstatus = 1" % (from_date, to_date))]
+
+
 out = []
 total_booking_amt, total_outstanding_amt = 0,0
 
 for r in res:
-  # get supplier type
-  supplier_type = sql("select t1.supplier_type from tabSupplier t1, tabAccount t2 where t1.name = t2.account_name and t2.name = '%s'" % r[col_idx['Account']])
-  r.append(supplier_type and cstr(supplier_type[0][0]) or '')
+	outstanding_amt, due_date, bill_no, bill_date, cond = 0, '','','', ''
+	booking_amt = r.pop(8)
+	
+	# supplier type
+	r.append(supp_type_dict.get(r[col_idx['Account']], ''))	
+	
+	# if entry against Payable Voucher
+	if r[col_idx['Against Voucher']] and r[col_idx['Voucher Type']] == 'Payable Voucher':
+		r += pv_dict.get(r[col_idx['Voucher No']], ['', '', ''])
+		cond = " and ifnull(against_voucher, '') = '%s'" % r[col_idx['Against Voucher']]
 
-  outstanding_amt, booking_amt, due_date, bill_no, bill_date, cond = 0,0, '','','', ''
+	# if entry against JV & and not adjusted within period
+	elif r[col_idx['Against Voucher Type']] == 'Payable Voucher' and r[col_idx['Against Voucher']] in pv_outside_period:
+		booking_amt = 0
+		cond = " and voucher_no = '%s' and ifnull(against_voucher, '') = '%s'" % (r[col_idx['Voucher No']], r[col_idx['Against Voucher']])
+	
+	# if un-adjusted
+	elif not r[col_idx['Against Voucher']]:
+		booking_amt = 0
+		cond = " and ((voucher_no = '%s' and ifnull(against_voucher, '') = '') or (ifnull(against_voucher, '') = '%s' and voucher_type = 'Journal Voucher'))" % (r[col_idx['Voucher No']], r[col_idx['Voucher No']])
 
-  # if entry against Payable Voucher
-  if r[col_idx['Against Voucher']] and r[col_idx['Voucher Type']] == 'Payable Voucher':
-    due_date, bill_no, bill_date = [cstr(t) for t in sql("select due_date,bill_no,bill_date from `tabPayable Voucher` where name = %s", r[col_idx['Voucher No']])[0]]
+	if cond:
+		outstanding_amt = flt(sql("select sum(ifnull(credit, 0))-sum(ifnull(debit, 0)) from `tabGL Entry` where account = '%s' and ifnull(is_cancelled, 'No') = 'No' and posting_date <= '%s' %s" % (r[col_idx['Account']], to_date, cond))[0][0] or 0)
 
-    # get opening
-    booking_amt = sql("select credit from `tabGL Entry` where account = %s and voucher_no = %s and is_cancelled = 'No'", (r[col_idx['Account']], r[col_idx['Voucher No']]))
-    booking_amt = booking_amt and flt(booking_amt[0][0]) or 0
+		# add to total outstanding
+		total_outstanding_amt += flt(outstanding_amt)
 
-    cond = " and against_voucher = '%s' and against_voucher is not null" % r[col_idx['Against Voucher']]
+		# add to total booking amount
+		if outstanding_amt and r[col_idx['Voucher Type']] == 'Payable Voucher' and r[col_idx['Against Voucher']]:
+			total_booking_amt += flt(booking_amt)
 
-  # if entry against JV & and not adjusted within period
-  elif r[col_idx['Against Voucher Type']] == 'Payable Voucher' and sql("select name from `tabPayable Voucher` where name = '%s' and (posting_date < '%s' or posting_date > '%s') and docstatus = 1" % (r[col_idx['Against Voucher']], from_date, to_date)):
-    cond = " and voucher_no = '%s' and ifnull(against_voucher, '') = '%s'" % (r[col_idx['Voucher No']], r[col_idx['Against Voucher']])
-  
-  # if un-adjusted
-  elif not r[col_idx['Against Voucher']]:
-    cond = " and ((voucher_no = '%s' and ifnull(against_voucher, '') = '') or (ifnull(against_voucher, '') = '%s' and voucher_type = 'Journal Voucher'))" % (r[col_idx['Voucher No']], r[col_idx['Voucher No']])
+	r += [booking_amt, outstanding_amt]
+	
+	# split into date ranges
+	val_l1 = val_l2 = val_l3 = val_l4 = val_l5_above= 0
+	if r[col_idx[aging_based_on]]:
+		diff = (getdate(to_date) - getdate(r[col_idx[aging_based_on]])).days
+		if diff < cint(filter_values['range_1']):
+			val_l1 = outstanding_amt
+		if diff >= cint(filter_values['range_1']) and diff < cint(filter_values['range_2']):
+			val_l2 = outstanding_amt
+		if diff >= cint(filter_values['range_2']) and diff < cint(filter_values['range_3']):
+			val_l3 = outstanding_amt
+		if diff >= cint(filter_values['range_3']) and diff < cint(filter_values['range_4']):
+			val_l4 = outstanding_amt
+		if diff >= cint(filter_values['range_4']):
+			val_l5_above = outstanding_amt
 
-  if cond:
-    outstanding_amt = flt(sql("select sum(ifnull(credit, 0))-sum(ifnull(debit, 0)) from `tabGL Entry` where account = '%s' and ifnull(is_cancelled, 'No') = 'No' and posting_date <= '%s' %s" % (r[col_idx['Account']], to_date, cond))[0][0] or 0)
+	r += [diff, val_l1, val_l2, val_l3, val_l4, val_l5_above]
 
-    # add to total outstanding
-    total_outstanding_amt += flt(outstanding_amt)
-
-    # add to total booking amount
-    if outstanding_amt and r[col_idx['Voucher Type']] == 'Payable Voucher' and r[col_idx['Against Voucher']]:
-      total_booking_amt += flt(booking_amt)
-
-  r += [due_date, bill_no, bill_date, booking_amt, outstanding_amt]
-  
-  # split into date ranges
-  val_l1 = val_l2 = val_l3 = val_l4 = val_l5_above= 0
-  if r[col_idx[aging_based_on]]:
-    diff = (getdate(to_date) - getdate(r[col_idx[aging_based_on]])).days
-    if diff < cint(filter_values['range_1']):
-      val_l1 = outstanding_amt
-    if diff >= cint(filter_values['range_1']) and diff < cint(filter_values['range_2']):
-      val_l2 = outstanding_amt
-    if diff >= cint(filter_values['range_2']) and diff < cint(filter_values['range_3']):
-      val_l3 = outstanding_amt
-    if diff >= cint(filter_values['range_3']) and diff < cint(filter_values['range_4']):
-      val_l4 = outstanding_amt
-    if diff >= cint(filter_values['range_4']):
-      val_l5_above = outstanding_amt
-
-  r += [diff, val_l1, val_l2, val_l3, val_l4, val_l5_above]
-
-  # Only show that entry which has outstanding
-  if abs(flt(outstanding_amt)) > 0.001:
-    out.append(r)
-    
-if  len(out) > 300 and from_export == 0:
-  msgprint("This is a very large report and cannot be shown in the browser as it is likely to make your browser very slow.Please select Account or click on 'Export' to open in excel")
-  raise Exception
+	# Only show that entry which has outstanding
+	if abs(flt(outstanding_amt)) > 0.001:
+		out.append(r)
+		
+if	len(out) > 300 and from_export == 0:
+	msgprint("This is a very large report and cannot be shown in the browser as it is likely to make your browser very slow.Please select Account or click on 'Export' to open in excel")
+	raise Exception
 
 
 # Append Extra rows to RES
diff --git a/accounts/search_criteria/accounts_payable/accounts_payable.sql b/accounts/search_criteria/accounts_payable/accounts_payable.sql
index 520535f..2054b1e 100644
--- a/accounts/search_criteria/accounts_payable/accounts_payable.sql
+++ b/accounts/search_criteria/accounts_payable/accounts_payable.sql
@@ -1,26 +1,11 @@
-SELECT *
-FROM (
-
-SELECT a.posting_date, a.voucher_no, a.account, a.credit AS inv_amount, ifnull( a.credit, 0 ) - ifnull( b.debit, 0 ) AS outstanding
-FROM (
-
-SELECT gl . *
-FROM `tabGL Entry` gl, `tabAccount` acc
-WHERE gl.account = acc.name
-AND acc.master_type = 'Supplier'
-AND ifnull( gl.is_cancelled, 'No' ) = 'No'
-AND gl.credit >0
-AND gl.posting_date <= current_date
-)a
-LEFT JOIN (
-
-SELECT against_voucher, account, sum( debit ) AS debit
-FROM `tabGL Entry`
-WHERE ifnull( is_cancelled, 'No' ) = 'No'
-AND posting_date <= current_date
-GROUP BY against_voucher, account
-)b ON a.voucher_no = b.against_voucher
-AND a.account = b.account
-)c
-WHERE outstanding !=0
-ORDER BY posting_date, voucher_no
\ No newline at end of file
+SELECT DISTINCT `tabGL Entry`.`Aging_date`,`tabGL Entry`.`transaction_date`,`tabGL Entry`.`account`, `tabGL Entry`.`against_voucher_type`, `tabGL Entry`.`against_voucher`,`tabGL Entry`.`voucher_type`,`tabGL Entry`.`voucher_no`, `tabGL Entry`.`remarks`, `tabGL Entry`.`credit`
+FROM `tabGL Entry`,`tabAccount` 
+WHERE `tabGL Entry`.`posting_date`>= '%(posting_date)s'
+ AND `tabGL Entry`.`posting_date`<= '%(posting_date1)s'
+ AND `tabGL Entry`.`account` LIKE '%(account)s%%'
+ AND `tabGL Entry`.`company` LIKE '%(company)s%%'
+ AND ((ifnull(`tabGL Entry`.voucher_type,'') = 'Payable Voucher' and `tabGL Entry`.credit>0) OR `tabGL Entry`.voucher_type = 'Journal Voucher')
+ AND `tabGL Entry`.`is_cancelled` = 'No'
+ AND `tabAccount`.master_type = 'Supplier'
+ AND `tabAccount`.name = `tabGL Entry`.account
+ ORDER BY `tabGL Entry`.`posting_date`
diff --git a/accounts/search_criteria/accounts_receivable/accounts_receivable.js b/accounts/search_criteria/accounts_receivable/accounts_receivable.js
index a51b8fb..f31dc76 100644
--- a/accounts/search_criteria/accounts_receivable/accounts_receivable.js
+++ b/accounts/search_criteria/accounts_receivable/accounts_receivable.js
@@ -5,8 +5,8 @@
   this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Posting Date'].df.filter_hide = 0;
   this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Posting Date'].df.filter_hide = 0;
   this.filter_fields_dict['GL Entry'+FILTER_SEP +'Account'].df.filter_hide = 0;
-  
-  this.add_filter({fieldname:'aging_based_on', label:'Aging Based On', fieldtype:'Select', options:NEWLINE+'Transaction Date'+NEWLINE+'Aging Date'+NEWLINE+'Due Date',ignore : 1, parent:'Receivable Voucher', report_default:'Aging Date'});  
+
+  this.add_filter({fieldname:'aging_based_on', label:'Aging Based On', fieldtype:'Select', options:NEWLINE+'Transaction Date'+NEWLINE+'Aging Date'+NEWLINE+'Due Date',ignore : 1, parent:'Receivable Voucher', report_default:'Aging Date'});
   this.add_filter({fieldname:'range_1', label:'Range 1', fieldtype:'Data', ignore : 1, parent:'GL Entry'});
   this.add_filter({fieldname:'range_2', label:'Range 2', fieldtype:'Data', ignore : 1, parent:'GL Entry'});
   this.add_filter({fieldname:'range_3', label:'Range 3', fieldtype:'Data', ignore : 1, parent:'GL Entry'});
@@ -19,4 +19,4 @@
   this.dt.set_no_limit(1);
 }
 
-this.mytabs.items['Select Columns'].hide()
\ No newline at end of file
+//this.mytabs.items['Select Columns'].hide()
\ No newline at end of file
diff --git a/accounts/search_criteria/budget_variance_report/budget_variance_report.py b/accounts/search_criteria/budget_variance_report/budget_variance_report.py
index 2efca28..182f9e5 100644
--- a/accounts/search_criteria/budget_variance_report/budget_variance_report.py
+++ b/accounts/search_criteria/budget_variance_report/budget_variance_report.py
@@ -51,7 +51,6 @@
   q1 = "select sum(t1.budget_allocated) from `tabBudget Detail` t1, `tab%s` t2, `tabAccount` t3 where "
   cond2 = " t3.is_pl_account = 'Yes' and t3.debit_or_credit = 'Debit' and t3.name = t1.account and t1.docstatus != 2 and "
   if ch:
-                                                                                                                                                                                                     
     qur = q1+cond2+cond1+" and t2.name = '%s'"
     ret_amt = sql(qur%(based_on,fiscal_year,based_on,r[0].strip()))
     
@@ -170,4 +169,4 @@
     r.append(actual)
     # ================ Variance ===================================================
     r.append(r[idx] - r[idx + 1])
-    count = count +1
\ No newline at end of file
+    count = count +1
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_agreement_list/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_agreement_list/__init__.py
diff --git a/accounts/search_criteria/lease_agreement_list/lease_agreement_list.js b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.js
new file mode 100644
index 0000000..4cb3d2b
--- /dev/null
+++ b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.js
@@ -0,0 +1,11 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=sys_defaults.year_start_date;
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_agreement_list/lease_agreement_list.py b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.py
new file mode 100644
index 0000000..e749d1b
--- /dev/null
+++ b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.py
@@ -0,0 +1,13 @@
+data =[
+		['Agreement No.','Data','100px',''],
+		['Lessee Name','Data','300px',''],
+		['Amount','Currency','120px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_agreement_list/lease_agreement_list.sql b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.sql
new file mode 100644
index 0000000..6097b2f
--- /dev/null
+++ b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.sql
@@ -0,0 +1,3 @@
+select la.name, la.account, la.invoice_amount
+from `tabLease Agreement` la
+where start_date between '%(date)s' and '%(date1)s' order by la.name
diff --git a/accounts/search_criteria/lease_agreement_list/lease_agreement_list.txt b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.txt
new file mode 100644
index 0000000..f7c9f84
--- /dev/null
+++ b/accounts/search_criteria/lease_agreement_list/lease_agreement_list.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_agreement_list
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-26 17:01:34',
+		'docstatus': 0,
+		'modified': '2011-07-28 12:55:50',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Agreement List',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_agreement_list
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_agreement_list'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_monthly_future_installment_inflows/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_monthly_future_installment_inflows/__init__.py
diff --git a/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.js b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.js
new file mode 100644
index 0000000..2d89611
--- /dev/null
+++ b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.js
@@ -0,0 +1,14 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=dateutil.obj_to_str(new Date());
+//	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df.filter_hide=1;
+
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.py b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.py
new file mode 100644
index 0000000..8e5b8ad
--- /dev/null
+++ b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.py
@@ -0,0 +1,13 @@
+data =[
+		['Month','Data','100px',''],
+		['Year','Data','100px',''],
+		['Amount','Currency','120px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.sql b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.sql
new file mode 100644
index 0000000..564a3fd
--- /dev/null
+++ b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.sql
@@ -0,0 +1,9 @@
+select date_format(due_date,'%M') as mnt,year(due_date),sum(amount)
+
+from `tabLease Agreement` la,`tabLease Installment` lai
+
+where la.name=lai.parent and (lai.cheque_date is null or lai.cheque_date > '%(date)s')
+
+group by date_format(due_date,'%M-%Y')
+
+order by year(due_date),month(due_date)
\ No newline at end of file
diff --git a/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.txt b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.txt
new file mode 100644
index 0000000..a531bb9
--- /dev/null
+++ b/accounts/search_criteria/lease_monthly_future_installment_inflows/lease_monthly_future_installment_inflows.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_monthly_future_installment_inflows
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-27 13:14:29',
+		'docstatus': 0,
+		'modified': '2011-07-27 13:14:29',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Monthly Future Installment Inflows',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_monthly_future_installment_inflows
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_monthly_future_installment_inflows'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_over_due_list/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_over_due_list/__init__.py
diff --git a/accounts/search_criteria/lease_over_due_list/lease_over_due_list.js b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.js
new file mode 100644
index 0000000..2d89611
--- /dev/null
+++ b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.js
@@ -0,0 +1,14 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=dateutil.obj_to_str(new Date());
+//	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df.filter_hide=1;
+
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_over_due_list/lease_over_due_list.py b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.py
new file mode 100644
index 0000000..869d46a
--- /dev/null
+++ b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.py
@@ -0,0 +1,14 @@
+data =[
+		['Agreement No.','Data','100px',''],
+		['Lessee Name','Data','300px',''],
+		['Amount','Currency','120px',''],
+		['Age','Data','100px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_over_due_list/lease_over_due_list.sql b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.sql
new file mode 100644
index 0000000..1789f7e
--- /dev/null
+++ b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.sql
@@ -0,0 +1,7 @@
+select la.name,la.account,lai.amount,cast('%(date)s' as date)-due_date as age
+
+from `tabLease Agreement` la,`tabLease Installment` lai
+
+where la.name=lai.parent and lai.due_date<cast('%(date)s' as date) and (lai.cheque_date is null or lai.cheque_date > cast('%(date)s' as date))
+
+order by cast('%(date)s' as date)-due_date desc
\ No newline at end of file
diff --git a/accounts/search_criteria/lease_over_due_list/lease_over_due_list.txt b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.txt
new file mode 100644
index 0000000..22bdc55
--- /dev/null
+++ b/accounts/search_criteria/lease_over_due_list/lease_over_due_list.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_over_due_list
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-26 18:11:47',
+		'docstatus': 0,
+		'modified': '2011-07-26 18:27:01',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Over Due List',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_over_due_list
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_over_due_list'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_overdue_age_wise/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_overdue_age_wise/__init__.py
diff --git a/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.js b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.js
new file mode 100644
index 0000000..2d89611
--- /dev/null
+++ b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.js
@@ -0,0 +1,14 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=dateutil.obj_to_str(new Date());
+//	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df.filter_hide=1;
+
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.py b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.py
new file mode 100644
index 0000000..5e16489
--- /dev/null
+++ b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.py
@@ -0,0 +1,16 @@
+data =[
+		['Lessee Name','Data','300px',''],
+		['Below 30 Days','Currency','120px',''],
+		['Below 90 Days','Currency','120px',''],
+		['Below 180 Days','Currency','120px',''],
+		['Below 360 Days','Currency','120px',''],
+		['Above 360 Days','Currency','120px',''],
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.sql b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.sql
new file mode 100644
index 0000000..2e6912e
--- /dev/null
+++ b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.sql
@@ -0,0 +1,9 @@
+select account,sum(od_30)as od_30,sum(od_90)as od_90,sum(od_180)as od_180,sum(od_360)as od_360,sum(od_1yr)as od_1yr from
+(
+	select account,case when age<=30 then amount end as od_30,case when age between 31 and 90 then amount end as od_90,case when age between 91 and 180 then amount end as od_180,case when age between 181 and 360 then amount end as od_360,case when age>360 then amount end as od_1yr from
+	(
+		select la.account,lai.amount,cast('%(date)s' as date)-due_date as age
+		from `tabLease Agreement` la,`tabLease Installment` lai
+		where la.name=lai.parent and lai.due_date<'%(date)s' and (lai.cheque_date is null or lai.cheque_date > '%(date)s')
+	)a
+)b group by account order by account
diff --git a/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.txt b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.txt
new file mode 100644
index 0000000..dcd0f94
--- /dev/null
+++ b/accounts/search_criteria/lease_overdue_age_wise/lease_overdue_age_wise.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_overdue_age_wise
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-27 13:14:29',
+		'docstatus': 0,
+		'modified': '2011-07-27 13:14:29',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Overdue Age Wise',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_overdue_age_wise
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_overdue_age_wise'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_receipt_summary_month_wise/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_receipt_summary_month_wise/__init__.py
diff --git a/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.js b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.js
new file mode 100644
index 0000000..4cb3d2b
--- /dev/null
+++ b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.js
@@ -0,0 +1,11 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=sys_defaults.year_start_date;
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.py b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.py
new file mode 100644
index 0000000..8e5b8ad
--- /dev/null
+++ b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.py
@@ -0,0 +1,13 @@
+data =[
+		['Month','Data','100px',''],
+		['Year','Data','100px',''],
+		['Amount','Currency','120px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.sql b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.sql
new file mode 100644
index 0000000..cdd48b8
--- /dev/null
+++ b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.sql
@@ -0,0 +1,5 @@
+SELECT date_format(gl.posting_date,'%M'),year(gl.posting_date),sum(gl.credit) as amount
+FROM `tabGL Entry` gl, `tabAccount` a
+WHERE gl.account=a.name and a.master_type='Customer' and gl.credit>0 and gl.posting_date between '%(date)s' and '%(date1)s'
+GROUP BY month(gl.posting_date),year(gl.posting_date)
+ORDER BY year(gl.posting_date),month(gl.posting_date)
diff --git a/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.txt b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.txt
new file mode 100644
index 0000000..6e1b266
--- /dev/null
+++ b/accounts/search_criteria/lease_receipt_summary_month_wise/lease_receipt_summary_month_wise.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_receipt_summary_month_wise
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-27 18:48:29',
+		'docstatus': 0,
+		'modified': '2011-07-28 12:56:35',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Receipt Summary Month Wise',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_receipt_summary_month_wise
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_receipt_summary_month_wise'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_receipts_client_wise/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_receipts_client_wise/__init__.py
diff --git a/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.js b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.js
new file mode 100644
index 0000000..4cb3d2b
--- /dev/null
+++ b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.js
@@ -0,0 +1,11 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=sys_defaults.year_start_date;
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.py b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.py
new file mode 100644
index 0000000..b84ff9f
--- /dev/null
+++ b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.py
@@ -0,0 +1,12 @@
+data =[
+		['Lessee Name','Data','300px',''],
+		['Amount','Currency','120px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.sql b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.sql
new file mode 100644
index 0000000..f951388
--- /dev/null
+++ b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.sql
@@ -0,0 +1,5 @@
+SELECT gl.account,sum(gl.credit) as amount
+FROM `tabGL Entry` gl, `tabAccount` a
+WHERE gl.account=a.name and a.master_type='Customer' and gl.posting_date between '%(date)s' and '%(date1)s'
+GROUP BY gl.account
+ORDER BY posting_date
diff --git a/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.txt b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.txt
new file mode 100644
index 0000000..26c0ff7
--- /dev/null
+++ b/accounts/search_criteria/lease_receipts_client_wise/lease_receipts_client_wise.txt
@@ -0,0 +1,31 @@
+# Search Criteria, lease_receipts_client_wise
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-28 12:13:41',
+		'docstatus': 0,
+		'modified': '2011-07-28 12:56:47',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Receipts Client Wise',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'page_len': 50,
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_receipts_client_wise
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_receipts_client_wise'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/support_email_settings/__init__.py b/accounts/search_criteria/lease_yearly_future_installment_inflows/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to accounts/search_criteria/lease_yearly_future_installment_inflows/__init__.py
diff --git a/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.js b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.js
new file mode 100644
index 0000000..2d89611
--- /dev/null
+++ b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.js
@@ -0,0 +1,14 @@
+report.customize_filters = function() {
+	this.hide_all_filters();
+
+	this.add_filter({fieldname:'date', label:'Date', fieldtype:'Date', options:'',ignore : 1, parent:'GL Entry', 'in_first_page':1});
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'From Date'].df['report_default']=dateutil.obj_to_str(new Date());
+//	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df['report_default']=dateutil.obj_to_str(new Date());
+
+	this.filter_fields_dict['GL Entry'+FILTER_SEP +'To Date'].df.filter_hide=1;
+
+}
+
+$dh(this.mytabs.tabs['More Filters']);
+$dh(this.mytabs.tabs['Select Columns']);
diff --git a/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.py b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.py
new file mode 100644
index 0000000..0163ba6
--- /dev/null
+++ b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.py
@@ -0,0 +1,12 @@
+data =[
+		['Year','Data','100px',''],
+		['Amount','Currency','120px','']
+	]
+
+for d in data:
+	colnames.append(d[0])
+	coltypes.append(d[1])
+	colwidths.append(d[2])
+	coloptions.append(d[3])
+	col_idx[d[0]] = len(colnames)-1
+
diff --git a/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.sql b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.sql
new file mode 100644
index 0000000..ec6c816
--- /dev/null
+++ b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.sql
@@ -0,0 +1,9 @@
+select year(date_sub(due_date,interval 6 MONTH)) as yr,sum(amount)
+
+from `tabLease Agreement` la,`tabLease Installment` lai
+
+where la.name=lai.parent and (lai.cheque_date is null or lai.cheque_date > '%(date)s')
+
+group by year(date_sub(due_date,interval 6 MONTH))
+
+order by yr
\ No newline at end of file
diff --git a/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.txt b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.txt
new file mode 100644
index 0000000..aa52224
--- /dev/null
+++ b/accounts/search_criteria/lease_yearly_future_installment_inflows/lease_yearly_future_installment_inflows.txt
@@ -0,0 +1,30 @@
+# Search Criteria, lease_yearly_future_installment_inflows
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-27 13:14:29',
+		'docstatus': 0,
+		'modified': '2011-07-27 13:14:29',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all Search Criteria
+	{
+		'columns': 'GL Entry\x01ID,GL Entry\x01Owner,GL Entry\x01Posting Date,GL Entry\x01Aging Date,GL Entry\x01Account,GL Entry\x01Cost Center,GL Entry\x01Against,GL Entry\x01Against Voucher,GL Entry\x01Voucher Type,GL Entry\x01Voucher No,GL Entry\x01Remarks,GL Entry\x01Is Cancelled,GL Entry\x01Is Opening,GL Entry\x01Fiscal Year,GL Entry\x01Company',
+		'criteria_name': 'Lease Yearly Future Installment Inflows',
+		'doc_type': 'GL Entry',
+		'doctype': 'Search Criteria',
+		'filters': "{'GL Entry\x01Voucher Type':'','GL Entry\x01Is Cancelled':'','GL Entry\x01Is Opening':'','GL Entry\x01Fiscal Year':''}",
+		'module': 'Accounts',
+		'name': '__common__',
+		'standard': 'Yes'
+	},
+
+	# Search Criteria, lease_yearly_future_installment_inflows
+	{
+		'doctype': 'Search Criteria',
+		'name': 'lease_yearly_future_installment_inflows'
+	}
+]
\ No newline at end of file
diff --git a/accounts/utils/__init__.py b/accounts/utils/__init__.py
new file mode 100644
index 0000000..e8ca13e
--- /dev/null
+++ b/accounts/utils/__init__.py
@@ -0,0 +1,27 @@
+from webnotes.model.doc import make_autoname, Document, addchild
+# Posts JV
+
+def post_jv(data):
+	jv = Document('Journal Voucher')
+	jv.voucher_type = data.get('voucher_type')
+	jv.naming_series = data.get('naming_series')
+	jv.voucher_date = data.get('cheque_date')
+	jv.posting_date = data.get('cheque_date')
+	jv.cheque_no = data.get('cheque_number')
+	jv.cheque_date = data.get('cheque_date')
+	jv.fiscal_year = data.get('fiscal_year') # To be modified to take care
+	jv.company = data.get('company')
+
+	jv.save(1)
+
+	jc = addchild(jv,'entries','Journal Voucher Detail',0)
+	jc.account = data.get('debit_account')
+	jc.debit = data.get('amount')
+	jc.save()
+
+	jc = addchild(jv,'entries','Journal Voucher Detail',0)
+	jc.account = data.get('credit_account')
+	jc.credit = data.get('amount')
+	jc.save()
+
+	return jv.name
\ No newline at end of file
diff --git a/analysis/doctype/mis_control/mis_control.py b/analysis/doctype/mis_control/mis_control.py
index 08a71f2..5af36e9 100644
--- a/analysis/doctype/mis_control/mis_control.py
+++ b/analysis/doctype/mis_control/mis_control.py
@@ -195,7 +195,7 @@
   # Get Children
   # ------------
   def get_children(self, parent_account, level, pl, company, fy):
-    cl = sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s order by name asc", (parent_account, pl, company))
+    cl = sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
     level0_diff = [0 for p in self.period_list]
     if pl=='Yes' and level==0: # switch for income & expenses
       cl = [c for c in cl]
@@ -295,7 +295,7 @@
         sd = self.ysd.strftime('%Y-%m-%d')
         cond = ""
 
-      bal = sql("select SUM(t1.debit), SUM(t1.credit) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= '%s' AND t1.posting_date <= '%s' AND t1.company = '%s' AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(is_opening,'No') = 'No' %s" % (sd,ed,company,lft,rgt, cond))
+      bal = sql("select SUM(t1.debit), SUM(t1.credit) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= '%s' AND t1.posting_date <= '%s' AND t1.company = '%s' AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(t1.is_opening,'No') = 'No' and ifnull(t1.is_cancelled, 'No') = 'No' %s" % (sd,ed,company,lft,rgt, cond))
       
       
       bal = bal and (flt(bal[0][0]) - flt(bal[0][1])) or 0
@@ -316,7 +316,7 @@
     a = sql("select account_name, name, debit_or_credit, lft, rgt, is_pl_account from `tabAccount` where account_name=%s and company=%s", (acc, company), as_dict=1)
     if a:
       a = a[0]
-      bal = sql("select SUM(IFNULL(t1.debit,0)), SUM(IFNULL(t1.credit,0)) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= %s AND t1.posting_date <= %s AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(is_opening, 'No') = 'No'", (sd,ed,a['lft'],a['rgt']))
+      bal = sql("select SUM(IFNULL(t1.debit,0)), SUM(IFNULL(t1.credit,0)) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= %s AND t1.posting_date <= %s AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(is_opening, 'No') = 'No' and ifnull(t1.is_cancelled, 'No') = 'No'", (sd,ed,a['lft'],a['rgt']))
       if a['debit_or_credit']=='Debit':
         bal = flt(flt(bal[0][0]) - flt(bal[0][1]))
       else:
@@ -341,13 +341,13 @@
     rec_grp = sql("select receivables_group from tabCompany where name=%s", company)
     if rec_grp:
       pa_lft_rgt = sql("select lft, rgt from tabAccount where name=%s and company=%s", (rec_grp[0][0], company))[0]
-      return sql("select t1.account_name, SUM(t2.debit) from tabAccount t1, `tabGL Entry` t2 where t1.lft > %s and t1.rgt < %s and t2.account = t1.name GROUP BY t1.name ORDER BY SUM(t2.debit) desc limit 5", (pa_lft_rgt[0], pa_lft_rgt[1]))
+      return sql("select t1.account_name, SUM(t2.debit) from tabAccount t1, `tabGL Entry` t2 where t1.lft > %s and t1.rgt < %s and t2.account = t1.name  and ifnull(t2.is_cancelled, 'No') = 'No' GROUP BY t1.name ORDER BY SUM(t2.debit) desc limit 5", (pa_lft_rgt[0], pa_lft_rgt[1]))
     else:
       return []
 
   def get_top_5_exp(self, company):
     a = sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where account_name=%s and company=%s", ('Expenses', company), as_dict=1)[0]
-    return sql("select t1.account_name, SUM(t2.debit) from tabAccount t1, `tabGL Entry` t2 where t1.lft>%s and t1.rgt<%s and t1.group_or_ledger = 'Ledger' and t2.account = t1.name and t2.voucher_type != 'Period Closing Voucher' GROUP BY t1.name ORDER BY SUM(t2.debit) desc limit 5", (a['lft'],a['rgt']))
+    return sql("select t1.account_name, SUM(t2.debit) from tabAccount t1, `tabGL Entry` t2 where t1.lft>%s and t1.rgt<%s and t1.group_or_ledger = 'Ledger' and t2.account = t1.name  and ifnull(t2.is_cancelled, 'No') = 'No' and t2.voucher_type != 'Period Closing Voucher' GROUP BY t1.name ORDER BY SUM(t2.debit) desc limit 5", (a['lft'],a['rgt']))
   
   def bl(self, acc, company):
     dt = getdate(nowdate())
diff --git a/buying/doctype/indent/indent.txt b/buying/doctype/indent/indent.txt
index 93767a8..cd6c912 100644
--- a/buying/doctype/indent/indent.txt
+++ b/buying/doctype/indent/indent.txt
@@ -282,6 +282,7 @@
 		'oldfieldtype': 'Data',
 		'options': 'Sales Order',
 		'permlevel': 0,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -338,7 +339,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -357,7 +358,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -487,7 +488,8 @@
 		'options': 'Term',
 		'permlevel': 0,
 		'print_hide': 1,
-		'report_hide': 1
+		'report_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/buying/doctype/indent_detail/indent_detail.txt b/buying/doctype/indent_detail/indent_detail.txt
index c81b9cf..c207266 100644
--- a/buying/doctype/indent_detail/indent_detail.txt
+++ b/buying/doctype/indent_detail/indent_detail.txt
@@ -85,7 +85,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -132,6 +132,7 @@
 		'options': 'Brand',
 		'permlevel': 1,
 		'print_hide': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -151,7 +152,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -199,6 +200,7 @@
 		'options': 'UOM',
 		'permlevel': 1,
 		'reqd': 1,
+		'search_index': 0,
 		'width': '50px'
 	},
 
diff --git a/buying/doctype/po_detail/po_detail.txt b/buying/doctype/po_detail/po_detail.txt
index 9e4d790..71d78df 100644
--- a/buying/doctype/po_detail/po_detail.txt
+++ b/buying/doctype/po_detail/po_detail.txt
@@ -54,7 +54,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -89,7 +89,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -182,6 +182,7 @@
 		'permlevel': 0,
 		'print_hide': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client',
 		'width': '100px'
 	},
@@ -331,7 +332,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Brand',
 		'permlevel': 1,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -348,7 +350,7 @@
 		'options': 'Item Group',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/buying/doctype/purchase_common/purchase_common.py b/buying/doctype/purchase_common/purchase_common.py
index fe8c8e6..29658cb 100644
--- a/buying/doctype/purchase_common/purchase_common.py
+++ b/buying/doctype/purchase_common/purchase_common.py
@@ -84,7 +84,7 @@
 			# ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
 			contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where supplier = '%s' and is_supplier = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
 			ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
-			return cstr(ret)
+			return ret
 		else:
 			msgprint("Supplier : %s does not exists" % (name))
 			raise Exception
@@ -142,14 +142,14 @@
 			ret['purchase_rate'] = item and flt(item[0]['last_purchase_rate']) or 0
 			ret['import_rate'] = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(obj.doc.fields.has_key('conversion_rate') and flt(obj.doc.conversion_rate) or 1)
 		
-		return cstr(ret)
+		return ret
 
 	# Get Available Qty at Warehouse
 	def get_bin_details( self, arg = ''):
 		arg = eval(arg)
 		bin = sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (arg['item_code'], arg['warehouse']), as_dict=1)
 		ret = { 'projected_qty' : bin and flt(bin[0]['projected_qty']) or 0 }
-		return str(ret)
+		return ret
 
 	# Get UOM Details
 	def get_uom_details(self, arg = ''):
@@ -163,7 +163,7 @@
 				'purchase_rate'		 : (lpr and flt(lpr[0]['last_purchase_rate']) * flt(uom[0]['conversion_factor'])) or 0
 			}
 		
-		return str(ret)
+		return ret
 
 	# get last purchase rate
 	def get_last_purchase_rate( self, obj):
@@ -522,7 +522,7 @@
 				'rate'	:	rate and (rate[0]['account_type'] == 'Tax' and not arg['charge_type'] == 'Actual') and flt(rate[0]['tax_rate']) or 0
 		}
 		#msgprint(ret)
-		return cstr(ret)
+		return ret
 
 
 				
diff --git a/buying/doctype/purchase_order/purchase_order.py b/buying/doctype/purchase_order/purchase_order.py
index 7d9e1da..1a5d2d7 100644
--- a/buying/doctype/purchase_order/purchase_order.py
+++ b/buying/doctype/purchase_order/purchase_order.py
@@ -38,23 +38,17 @@
     get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date')
 
 
-  # Client Trigger Functions
-  #----------------------------------------------------------------------------------------------------
-  # Get Supplier Details 
-  #def get_supplier_details(self, name = ''):
-    #return cstr(get_obj(dt='Purchase Common').get_supplier_details(name))
-
   # Get Item Details
   def get_item_details(self, arg =''):
-    return cstr(get_obj(dt='Purchase Common').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 cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
+    return get_obj(dt='Purchase Common').get_uom_details(arg)
 
   # get available qty at warehouse
   def get_bin_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_bin_details(arg))
+    return get_obj(dt='Purchase Common').get_bin_details(arg)
 
   # Pull Indent
   def get_indent_details(self):
diff --git a/buying/doctype/qa_inspection_report/qa_inspection_report.txt b/buying/doctype/qa_inspection_report/qa_inspection_report.txt
index 5febdec..10890dc 100644
--- a/buying/doctype/qa_inspection_report/qa_inspection_report.txt
+++ b/buying/doctype/qa_inspection_report/qa_inspection_report.txt
@@ -206,7 +206,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Serial No',
 		'permlevel': 0,
-		'print_hide': 0
+		'print_hide': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -219,7 +220,8 @@
 		'oldfieldname': 'batch_no',
 		'oldfieldtype': 'Link',
 		'options': 'Batch',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -255,7 +257,7 @@
 		'options': 'Delivery Note',
 		'permlevel': 0,
 		'print_hide': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/buying/doctype/supplier/supplier.txt b/buying/doctype/supplier/supplier.txt
index b7797e5..a7a08c3 100644
--- a/buying/doctype/supplier/supplier.txt
+++ b/buying/doctype/supplier/supplier.txt
@@ -5,7 +5,7 @@
 	{
 		'creation': '2010-08-08 17:09:26',
 		'docstatus': 0,
-		'modified': '2011-05-10 17:42:21',
+		'modified': '2011-07-19 16:18:58',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -25,7 +25,7 @@
 		'show_in_menu': 0,
 		'subject': ' ',
 		'tag_fields': 'supplier_type',
-		'version': 86
+		'version': 87
 	},
 
 	# These values are common for all DocField
@@ -166,21 +166,8 @@
 	# DocField
 	{
 		'doctype': 'DocField',
-		'fieldname': 'supplier_status',
-		'fieldtype': 'Select',
-		'idx': 6,
-		'label': 'Supplier Status',
-		'oldfieldname': 'supplier_status',
-		'oldfieldtype': 'Select',
-		'options': '\nApproved\nUnapproved',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 7,
+		'idx': 6,
 		'label': 'Address & Contacts',
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0
@@ -192,7 +179,7 @@
 		'depends_on': 'eval:doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 8,
+		'idx': 7,
 		'label': 'Address Desc',
 		'options': '<em>Addresses will appear only when you save the supplier</em>',
 		'permlevel': 0
@@ -203,7 +190,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 9,
+		'idx': 8,
 		'label': 'Address HTML',
 		'permlevel': 1
 	},
@@ -212,7 +199,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 10,
+		'idx': 9,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -223,7 +210,7 @@
 		'depends_on': 'eval:doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 11,
+		'idx': 10,
 		'label': 'Contact Desc',
 		'options': '<em>Contact Details will appear only when you save the supplier</em>',
 		'permlevel': 0
@@ -233,7 +220,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 12,
+		'idx': 11,
 		'label': 'Contact HTML',
 		'permlevel': 1
 	},
@@ -242,7 +229,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 13,
+		'idx': 12,
 		'label': 'More Info',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -255,7 +242,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'company',
 		'fieldtype': 'Link',
-		'idx': 14,
+		'idx': 13,
 		'in_filter': 1,
 		'label': 'Company',
 		'oldfieldname': 'company',
@@ -263,7 +250,7 @@
 		'options': 'Company',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -273,7 +260,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'supplier_details',
 		'fieldtype': 'Text',
-		'idx': 15,
+		'idx': 14,
 		'label': 'Supplier Details',
 		'oldfieldname': 'supplier_details',
 		'oldfieldtype': 'Code',
@@ -284,7 +271,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 16,
+		'idx': 15,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -294,7 +281,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'credit_days',
 		'fieldtype': 'Int',
-		'idx': 17,
+		'idx': 16,
 		'label': 'Credit Days',
 		'permlevel': 0
 	},
@@ -304,7 +291,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'website',
 		'fieldtype': 'Data',
-		'idx': 18,
+		'idx': 17,
 		'label': 'Website',
 		'oldfieldname': 'website',
 		'oldfieldtype': 'Data',
@@ -317,7 +304,7 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 19,
+		'idx': 18,
 		'label': 'Transaction History',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0
@@ -329,7 +316,7 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 20,
+		'idx': 19,
 		'label': 'History HTML',
 		'oldfieldtype': 'HTML',
 		'permlevel': 0
@@ -340,7 +327,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'trash_reason',
 		'fieldtype': 'Small Text',
-		'idx': 21,
+		'idx': 20,
 		'label': 'Trash Reason',
 		'oldfieldname': 'trash_reason',
 		'oldfieldtype': 'Small Text',
diff --git a/buying/doctype/supplier_quotation/supplier_quotation.py b/buying/doctype/supplier_quotation/supplier_quotation.py
index 0c659bc..ac59430 100755
--- a/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -18,7 +18,7 @@
       'supplier_name'   : cd and cd[0][4] or '',
       'supplier_address': cd and cd[0][5] or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_rfq_details(self):
     self.doc.clear_table(self.doclist, 'supplier_quotation_details')
@@ -28,12 +28,12 @@
   def update_approval_status(self):
     if not self.doc.approval_status or self.doc.approval_status == 'Not Approved':
       set(self.doc, 'approval_status','Approved')
-      return cstr(self.doc.approval_status)
+      return self.doc.approval_status
     elif self.doc.approval_status == 'Approved':
       pc_obj = get_obj('Purchase Common')
       pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Order', docname = self.doc.name, detail_doctype = 'PO Detail')
       set(self.doc, 'approval_status', 'Not Approved')
-      return cstr(self.doc.approval_status)
+      return self.doc.approval_status
   
   def validate_item_list(self):
     if not getlist(self.doclist, 'supplier_quotation_details'):
@@ -101,4 +101,4 @@
   # Get Supplier Details
   # --------------------
   def get_supplier_details(self, name = ''):
-    return cstr(get_obj('Purchase Common').get_supplier_details(name))
\ No newline at end of file
+    return get_obj('Purchase Common').get_supplier_details(name)
\ No newline at end of file
diff --git a/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.py b/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.py
index 486cc6d..159d393 100644
--- a/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.py
+++ b/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.py
@@ -1,2 +1,3 @@
+msgprint(colwidths)
 colwidths[col_idx['Pending Quantity To Receive']] = '200px'
 colwidths[col_idx['Pending Amount To Receive']] = '200px'
\ No newline at end of file
diff --git a/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.txt b/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.txt
index 062e385..9708db2 100644
--- a/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.txt
+++ b/buying/search_criteria/pending_po_items_to_receive/pending_po_items_to_receive.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all Search Criteria
 	{
-		'add_col': '`tabPO Detail`.qty - ifnull(`tabPO Detail`.received_qty, 0) AS "Pending Quantity To Receive"\n(`tabPO Detail`.qty - ifnull(`tabPO Detail`.received_qty, 0)) * `tabPO Detail`.purchase_rate AS "Pending Amount To Receive\'"',
+		'add_col': '`tabPO Detail`.qty - ifnull(`tabPO Detail`.received_qty, 0) AS "Pending Quantity To Receive"\n(`tabPO Detail`.qty - ifnull(`tabPO Detail`.received_qty, 0)) * `tabPO Detail`.purchase_rate AS "Pending Amount To Receive"',
 		'add_cond': '`tabPO Detail`.qty - ifnull(`tabPO Detail`.received_qty, 0) > 0 \n`tabPurchase Order`.status != "Stopped"',
 		'columns': 'Purchase Order\x01ID,Purchase Order\x01Supplier,Purchase Order\x01Supplier Name,Purchase Order\x01Status,Purchase Order\x01PO Date,Purchase Order\x01Fiscal Year,PO Detail\x01Indent No,PO Detail\x01Item Code,PO Detail\x01Item Name,PO Detail\x01Description,PO Detail\x01Quantity,PO Detail\x01UOM,PO Detail\x01Received Qty',
 		'criteria_name': 'Pending PO Items To Receive',
diff --git a/favicon.ico b/favicon.ico
new file mode 100644
index 0000000..8b2106b
--- /dev/null
+++ b/favicon.ico
Binary files differ
diff --git a/home/page/event_updates/event_updates.css b/home/page/event_updates/event_updates.css
index ed50351..a88fed4 100644
--- a/home/page/event_updates/event_updates.css
+++ b/home/page/event_updates/event_updates.css
@@ -14,4 +14,49 @@
 	font-size: 11px;
 	color: #FFF;
 	background-color: RED;
-}
\ No newline at end of file
+}
+
+div.setup-wizard {
+	display: none;
+	margin: 13px 0px;
+	background-color: #FED;
+	padding: 13px;
+}
+
+div.setup-wizard .header {
+	font-size: 12px;
+	font-weight: bold;
+	color: #322;
+	margin-bottom: 7px;
+}
+
+
+div.setup-wizard .percent-outer {
+	height: 17px;
+	background-color: #FFF;
+	border: 2px solid #322;
+}
+
+div.setup-wizard .percent-inner {
+	height: 17px;
+	background-color: GREEN;
+}
+
+div.setup-wizard .suggestion {
+	margin: 7px 0px;
+	color: #322;	
+}
+
+div.setup-wizard .prev-next {
+	height: 13px;
+}
+
+div.setup-wizard .prev-next span {
+	display: none;
+	float: right;
+	margin-left: 13px;
+	color: #877;
+	font-size: 11px;
+}
+
+
diff --git a/home/page/event_updates/event_updates.js b/home/page/event_updates/event_updates.js
index 7ecfbdc..1574f53 100644
--- a/home/page/event_updates/event_updates.js
+++ b/home/page/event_updates/event_updates.js
@@ -24,8 +24,8 @@
 	wrapper.head = $a(wrapper.body, 'div');
 	
 	wrapper.banner_area = $a(wrapper.head, 'div');
-	wrapper.toolbar_area = $a(wrapper.head, 'div');
 
+	wrapper.setup_wizard_area = $a(wrapper.body, 'div', 'setup-wizard')
 
 	wrapper.system_message_area = $a(wrapper.body, 'div', '', 
 		{marginBottom:'16px', padding:'8px', backgroundColor:'#FFD', border:'1px dashed #AA6', display:'none'})
@@ -612,7 +612,6 @@
 	// get values
 	$c_page('home', 'event_updates', 'get_status_details', user,
 		function(r,rt) { 
-			
 			home_status_bar.render(r.message);
 			
 			// system_messages
@@ -622,6 +621,11 @@
 			// render online users
 			pscript.online_users_obj.render(r.message.online_users);
 			pscript.online_users = r.message.online_users;
+			
+			// setup wizard
+			if(r.message.setup_status) {
+				new SetupWizard(r.message.setup_status)
+			}
 		}
 	);	
 }
@@ -633,7 +637,7 @@
 	var txt = $a(wrapper.system_message_area, 'div', '', {lineHeight:'1.6em'});
 	txt.innerHTML = msg;
 	
-	var span = $ln($a(wrapper.system_message_area, 'div'), 'Dismiss', 
+	var span = $ln($a(wrapper.system_message_area, 'div', '', {textAlign:'right'}), 'Dismiss'.bold(), 
 		function(me) { 
 			me.set_working();
 			$c_obj('Home Control', 'dismiss_message', '', function(r,rt) { 
@@ -729,3 +733,53 @@
 	if(!flag)  alert(msg);
 	return flag;
 }
+
+SetupWizard = function(status) { 
+	var me = this;
+	$.extend(this, {
+		make: function(status) {
+			me.status = status;
+			me.wrapper = page_body.pages['Event Updates'].setup_wizard_area;
+			$ds(me.wrapper);
+			me.make_percent(status.percent);
+			me.make_suggestion(status.ret);
+		},
+		make_percent: function(percent) {
+			$a(me.wrapper, 'div', 'header', {}, 'Your setup is '+percent+'% complete');
+			var o = $a(me.wrapper, 'div', 'percent-outer');
+			$a(o, 'div', 'percent-inner', {width:percent + '%'});
+		},
+		make_suggestion: function(ret) {
+			me.suggest_area = $a(me.wrapper, 'div', 'suggestion');
+			if(me.status.ret.length>1) {
+				me.prev_next = $a(me.wrapper, 'div', 'prev-next');
+
+				// next
+				me.next = $a(me.prev_next, 'span', 'link_type', null, 'Next Suggestion',
+					function() { me.show_suggestion(me.cur_sugg+1) });
+
+				// prev
+				me.prev = $a(me.prev_next, 'span', 'link_type', null, 'Previous Suggestion',
+					function() { me.show_suggestion(me.cur_sugg-1) });
+
+			}
+			if(me.status.ret.length) {
+				me.show_suggestion(0);
+			} else {
+				me.suggest_area.innerHTML = 'Congratulations: '.bold() + 'You are now on your track... Good luck';
+			}
+		},
+		show_suggestion: function(idx) {
+			me.cur_sugg = idx;
+			me.suggest_area.innerHTML = 'What you can do next: '.bold() + me.status.ret[idx];
+
+			// show hide prev, next
+			if(me.status.ret.length>1) {
+				$dh(me.prev); $dh(me.next);
+				if(idx>0) $ds(me.prev);
+				if(idx<me.status.ret.length-1) $ds(me.next);			
+			}
+		}
+	})
+	this.make(status); 
+}
diff --git a/home/page/event_updates/event_updates.py b/home/page/event_updates/event_updates.py
index ce73cd1..6e811e7 100644
--- a/home/page/event_updates/event_updates.py
+++ b/home/page/event_updates/event_updates.py
@@ -35,11 +35,51 @@
 	if msg_id and msg_id != webnotes.conn.get_global('system_message_id', webnotes.session['user']):
 		msg = webnotes.conn.get_global('system_message')
 			
-	return {
+	ret = {
 		'user_count': len(online) or 0, 
 		'unread_messages': get_unread_messages(),
 		'online_users': online or [],
 		'system_message':msg,
 		'is_trial': webnotes.conn.get_global('is_trial'),
-		'days_to_expiry': (webnotes.conn.get_global('days_to_expiry') or '0')
+		'days_to_expiry': (webnotes.conn.get_global('days_to_expiry') or '0'),
+		'setup_status': get_setup_status()
 	}
+	return ret
+
+def get_setup_status():
+	"""
+		Returns the setup status of the current account
+	"""
+	if cint(webnotes.conn.get_global('setup_done')):
+		return ''
+		
+	percent = 20
+	ret = []
+	
+	if not webnotes.conn.get_value('Personalize', None, 'header_html'):
+		ret.append('<a href="#!Form/Personalize/Personalize">Upload your company banner</a>')
+	else:
+		percent += 20
+	
+	def check_type(doctype, ret, percent):	
+		if not webnotes.conn.sql("select count(*) from tab%s" % doctype)[0][0]:
+			ret.append('''
+				<a href="#!Form/%(dt)s/New">
+				Create a new %(dt)s
+				</a> or 
+				<a href="#!Import Data/%(dt)s">
+				Import from a spreadsheet</a>''' % {'dt':doctype})
+		else:
+			percent += 20
+		return ret, percent
+
+	ret, percent = check_type('Item', ret, percent)
+	ret, percent = check_type('Customer', ret, percent)
+	ret, percent = check_type('Supplier', ret, percent)
+	
+	if percent==100:
+		webnotes.conn.set_global('setup_done', '1')
+		return ''
+		
+	return {'ret': ret, 'percent': percent}
+		
\ No newline at end of file
diff --git a/home/page/my_company/my_company.js b/home/page/my_company/my_company.js
index 8b1b44f..0850607 100644
--- a/home/page/my_company/my_company.js
+++ b/home/page/my_company/my_company.js
@@ -143,7 +143,10 @@
 			var c1 = repl(' AND (first_name LIKE "%(txt)s" OR last_name LIKE "%(txt)s" OR name LIKE "%(txt)s")', {txt:'%' + me.search_inp.value + '%'});
 		}
 		
-		this.query = repl("SELECT distinct ifnull(name,''), ifnull(concat_ws(' ', first_name, last_name),''), ifnull(messanger_status,''), ifnull(gender,''), ifnull(file_list,''), 0, enabled from tabProfile where docstatus != 2 AND name not in ('Guest','Administrator') %(cond)s ORDER BY name asc",{cond:c1});
+		this.query = repl("SELECT distinct ifnull(name,''), ifnull(concat_ws(' ', first_name, last_name),''), \
+			ifnull(messanger_status,''), ifnull(gender,''), ifnull(file_list,''), 0, enabled, last_login \
+			from tabProfile where docstatus != 2 AND name not in ('Guest','Administrator') %(cond)s \
+			ORDER BY name asc",{cond:c1});
 	}
 	this.lst.make(this.lst_area);
 	this.lst.show_cell= function(cell, ri, ci, d) {
diff --git a/hr/doctype/appraisal/appraisal.py b/hr/doctype/appraisal/appraisal.py
index 1731559..e13f9f3 100644
--- a/hr/doctype/appraisal/appraisal.py
+++ b/hr/doctype/appraisal/appraisal.py
@@ -26,7 +26,7 @@
     emp_nm = sql("select employee_name from `tabEmployee` where name=%s", self.doc.employee)
     emp_nm= emp_nm and emp_nm[0][0] or ''
     self.doc.employee_name = emp_nm
-    return cstr(emp_nm)
+    return emp_nm
   
   def fetch_kra(self):
     if not self.doc.kra_template:
@@ -88,7 +88,7 @@
       if d.score:
         total = total + flt(d.score_earned)
     ret={'total_score':flt(total)}
-    return cstr(ret)
+    return ret
   
   def declare_completed(self):
     ret={}
diff --git a/hr/doctype/attendance/attendance.py b/hr/doctype/attendance/attendance.py
index d64a8e3..3c687ef 100644
--- a/hr/doctype/attendance/attendance.py
+++ b/hr/doctype/attendance/attendance.py
@@ -34,7 +34,7 @@
     set(self.doc, 'employee_name', emp_nm and emp_nm[0][0] or '')
 
     ret = { 'employee_name' : emp_nm and emp_nm[0][0] or ''}
-    return str(ret)
+    return ret
   
   #validation for duplicate record
   def validate_duplicate_record(self):   
diff --git a/hr/doctype/attendance/attendance.txt b/hr/doctype/attendance/attendance.txt
index a52225e..4f189b1 100644
--- a/hr/doctype/attendance/attendance.txt
+++ b/hr/doctype/attendance/attendance.txt
@@ -141,7 +141,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nPresent\nAbsent\nHalf Day',
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -193,7 +193,7 @@
 		'oldfieldname': 'att_date',
 		'oldfieldtype': 'Date',
 		'reqd': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/hr/doctype/educational_qualifications/educational_qualifications.txt b/hr/doctype/educational_qualifications/educational_qualifications.txt
index 21f4a9a..d57139b 100644
--- a/hr/doctype/educational_qualifications/educational_qualifications.txt
+++ b/hr/doctype/educational_qualifications/educational_qualifications.txt
@@ -75,7 +75,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nGraduate\nPost Graduate\nUnder Graduate',
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/hr/doctype/employee/employee.py b/hr/doctype/employee/employee.py
index 54142db..01ff32d 100644
--- a/hr/doctype/employee/employee.py
+++ b/hr/doctype/employee/employee.py
@@ -41,7 +41,7 @@
     if self.doc.date_of_birth:
       dt = getdate(self.doc.date_of_birth) + datetime.timedelta(21915)
       ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
-    return str(ret)
+    return ret
 
   # check if salary structure exists
   #========================================================================================================
diff --git a/hr/doctype/employee/employee.txt b/hr/doctype/employee/employee.txt
index cbe281d..49a494b 100644
--- a/hr/doctype/employee/employee.txt
+++ b/hr/doctype/employee/employee.txt
@@ -173,7 +173,8 @@
 		'oldfieldname': 'employee_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
@@ -275,7 +276,7 @@
 		'options': '\nActive\nLeft',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -408,7 +409,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Department',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/hr/doctype/expense_voucher/expense_voucher.txt b/hr/doctype/expense_voucher/expense_voucher.txt
index 0f7812e..596d4b5 100644
--- a/hr/doctype/expense_voucher/expense_voucher.txt
+++ b/hr/doctype/expense_voucher/expense_voucher.txt
@@ -189,7 +189,7 @@
 		'oldfieldname': 'employee_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
diff --git a/hr/doctype/leave_allocation/leave_allocation.py b/hr/doctype/leave_allocation/leave_allocation.py
index e11a335..46f7809 100755
--- a/hr/doctype/leave_allocation/leave_allocation.py
+++ b/hr/doctype/leave_allocation/leave_allocation.py
@@ -66,7 +66,7 @@
       'carry_forwarded_leaves'  :  prev_bal,
       'total_leaves_allocated'   :  flt(prev_bal) + flt(self.doc.new_leaves_allocated)
     }
-    return str(ret)
+    return ret
 
 
 # ********************************************** validate *****************************************************
diff --git a/hr/doctype/leave_allocation/leave_allocation.txt b/hr/doctype/leave_allocation/leave_allocation.txt
index 0b0c96c..b147a7f 100644
--- a/hr/doctype/leave_allocation/leave_allocation.txt
+++ b/hr/doctype/leave_allocation/leave_allocation.txt
@@ -136,7 +136,7 @@
 		'in_filter': 1,
 		'label': 'Employee Name',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/hr/doctype/leave_application/leave_application.js b/hr/doctype/leave_application/leave_application.js
index ba00a31..1eda69f 100755
--- a/hr/doctype/leave_application/leave_application.js
+++ b/hr/doctype/leave_application/leave_application.js
@@ -52,12 +52,9 @@
 // to date
 // --------
 cur_frm.cscript.to_date = function(doc, dt, dn) {
-  if(cint(doc.half_day) == 1 && doc.from_date && doc.from_date != doc.to_date){
+  if(cint(doc.half_day) == 1 && cstr(doc.from_date) && doc.from_date != doc.to_date){
     msgprint("To Date should be same as From Date for Half Day leave");
-    return;
-  }
-  if(cint(doc.half_day) == 1){
-    set_multiple(dt,dn,{to_date:doc.from_date});
+    set_multiple(dt,dn,{to_date:doc.from_date});    
   }
   calculate_total_days(doc, dt, dn);
 }
diff --git a/hr/doctype/leave_application/leave_application.txt b/hr/doctype/leave_application/leave_application.txt
index 11d01e6..06b4170 100644
--- a/hr/doctype/leave_application/leave_application.txt
+++ b/hr/doctype/leave_application/leave_application.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2011-02-17 13:25:56',
+		'creation': '2011-02-10 14:10:08',
 		'docstatus': 0,
-		'modified': '2011-07-08 13:28:15',
+		'modified': '2011-07-11 12:48:49',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -54,28 +54,28 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
+		'amend': 1,
+		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 1,
+		'match': 'owner',
 		'permlevel': 0,
-		'role': 'Employee',
-		'submit': 0,
+		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
-		'amend': 1,
-		'cancel': 1,
-		'create': 1,
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 2,
+		'match': 'owner',
 		'permlevel': 0,
-		'role': 'HR User',
-		'submit': 1,
-		'write': 1
+		'submit': 0,
+		'write': 0
 	},
 
 	# DocPerm
@@ -86,6 +86,19 @@
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
+		'role': 'HR User',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocPerm
+	{
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'idx': 4,
+		'permlevel': 0,
 		'role': 'HR Manager',
 		'submit': 1,
 		'write': 1
@@ -93,28 +106,18 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
-		'idx': 4,
+		'idx': 5,
 		'permlevel': 1,
-		'role': 'HR User',
-		'submit': 0,
-		'write': 0
+		'role': 'HR User'
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
-		'idx': 5,
+		'idx': 6,
 		'permlevel': 1,
-		'role': 'HR Manager',
-		'submit': 0,
-		'write': 0
+		'role': 'HR Manager'
 	},
 
 	# DocField
@@ -149,7 +152,7 @@
 		'in_filter': 1,
 		'label': 'Employee Name',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -201,7 +204,7 @@
 		'options': 'link:Fiscal Year',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -234,6 +237,7 @@
 		'idx': 10,
 		'label': 'From Date',
 		'permlevel': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -246,6 +250,7 @@
 		'idx': 11,
 		'label': 'To Date',
 		'permlevel': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
diff --git a/hr/doctype/salary_slip/salary_slip.js b/hr/doctype/salary_slip/salary_slip.js
index 8c76b1e..8f953e6 100644
--- a/hr/doctype/salary_slip/salary_slip.js
+++ b/hr/doctype/salary_slip/salary_slip.js
@@ -29,7 +29,7 @@
 // Calculate total if lwp exists
 // ------------------------------------------------------------------------
 cur_frm.cscript.leave_without_pay = function(doc,dt,dn){
-  doc.payment_days = cint(doc.total_days_in_month) - cint(doc.leave_without_pay);
+  doc.payment_days = flt(doc.total_days_in_month) - flt(doc.leave_without_pay);
   refresh_field('payment_days');
   calculate_all(doc, dt, dn);
 }
diff --git a/hr/doctype/salary_slip/salary_slip.py b/hr/doctype/salary_slip/salary_slip.py
index 9c94885..af55956 100644
--- a/hr/doctype/salary_slip/salary_slip.py
+++ b/hr/doctype/salary_slip/salary_slip.py
@@ -18,210 +18,219 @@
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
-  def __init__(self,doc,doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
-    
-    
-  # autoname
-  #=======================================================
-  def autoname(self):
-    self.doc.name = make_autoname('Sal Slip/' +self.doc.employee + '/.#####') 
+	def __init__(self,doc,doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		
+		
+	# autoname
+	#=======================================================
+	def autoname(self):
+		self.doc.name = make_autoname('Sal Slip/' +self.doc.employee + '/.#####') 
 
-  # Get employee details
-  #=======================================================
-  def get_emp_and_leave_details(self):
-    # Get payment days
-    if self.doc.fiscal_year and self.doc.month:
-      self.get_leave_details()
+	# Get employee details
+	#=======================================================
+	def get_emp_and_leave_details(self):
+		# Get payment days
+		if self.doc.fiscal_year and self.doc.month:
+			self.get_leave_details()
 
-    # check sal structure
-    if self.doc.employee:
-      struct = self.check_sal_struct()
-      if struct:
-        self.pull_sal_struct(struct)
+		# check sal structure
+		if self.doc.employee:
+			struct = self.check_sal_struct()
+			if struct:
+				self.pull_sal_struct(struct)
 
 
-  # Check sal structure
-  #=======================================================
-  def check_sal_struct(self):
-    struct = sql("select name from `tabSalary Structure` where employee ='%s' and is_active = 'Yes' "%self.doc.employee)
-    if not struct:
-      msgprint("Please create Salary Structure for employee '%s'"%self.doc.employee)
-      self.doc.employee = ''
-    return struct and struct[0][0] or ''
+	# Check sal structure
+	#=======================================================
+	def check_sal_struct(self):
+		struct = sql("select name from `tabSalary Structure` where employee ='%s' and is_active = 'Yes' "%self.doc.employee)
+		if not struct:
+			msgprint("Please create Salary Structure for employee '%s'"%self.doc.employee)
+			self.doc.employee = ''
+		return struct and struct[0][0] or ''
 
-  # Pull struct details
-  #=======================================================
-  def pull_sal_struct(self, struct):
-    self.doc.clear_table(self.doclist, 'earning_details')
-    self.doc.clear_table(self.doclist, 'deduction_details')
+	# Pull struct details
+	#=======================================================
+	def pull_sal_struct(self, struct):
+		self.doc.clear_table(self.doclist, 'earning_details')
+		self.doc.clear_table(self.doclist, 'deduction_details')
 
-    get_obj('DocType Mapper', 'Salary Structure-Salary Slip').dt_map('Salary Structure', 'Salary Slip', struct, self.doc, self.doclist, "[['Salary Structure', 'Salary Slip'],['Earning Detail', 'SS Earning Detail'],['Deduction Detail','SS Deduction Detail']]")
+		get_obj('DocType Mapper', 'Salary Structure-Salary Slip').dt_map('Salary Structure', 'Salary Slip', struct, self.doc, self.doclist, "[['Salary Structure', 'Salary Slip'],['Earning Detail', 'SS Earning Detail'],['Deduction Detail','SS Deduction Detail']]")
 
-    basic_info = sql("select bank_name, bank_ac_no, esic_card_no, pf_number from `tabEmployee` where name ='%s'" % self.doc.employee)
-    self.doc.bank_name = basic_info[0][0]
-    self.doc.bank_account_no = basic_info[0][1]
-    self.doc.esic_no = basic_info[0][2]
-    self.doc.pf_no = basic_info[0][3]
+		basic_info = sql("select bank_name, bank_ac_no, esic_card_no, pf_number from `tabEmployee` where name ='%s'" % self.doc.employee)
+		self.doc.bank_name = basic_info[0][0]
+		self.doc.bank_account_no = basic_info[0][1]
+		self.doc.esic_no = basic_info[0][2]
+		self.doc.pf_no = basic_info[0][3]
 
-  # Get leave details
-  #=======================================================
-  def get_leave_details(self):
-    m = self.get_month_details()    
-    lwp = self.calculate_lwp(m)
-    self.doc.total_days_in_month = m[3]
-    self.doc.leave_without_pay = lwp
-    self.doc.payment_days = flt(m[3]) - flt(lwp)
+	# Get leave details
+	#=======================================================
+	def get_leave_details(self):
+		m = self.get_month_details()		
+		lwp = self.calculate_lwp(m)
+		self.doc.total_days_in_month = m[3]
+		self.doc.leave_without_pay = lwp
+		self.doc.payment_days = flt(m[3]) - flt(lwp)
 
-  # Get month details
-  #=======================================================
-  def get_month_details(self):
-    ysd = sql("select year_start_date from `tabFiscal Year` where name ='%s'"%self.doc.fiscal_year)[0][0]
-    if ysd:
-      from dateutil.relativedelta import relativedelta
-      import calendar, datetime
-      mnt = int(self.doc.month)
-      diff_mnt = int(mnt)-int(ysd.month)
-      if diff_mnt<0:
-        diff_mnt = 12-int(ysd.month)+int(mnt)
-      msd = ysd + relativedelta(months=diff_mnt) # month start date
-      month_days = cint(calendar.monthrange(cint(msd.year) ,cint(self.doc.month))[1]) # days in month
-      med = datetime.date(msd.year, cint(self.doc.month), month_days) # month end date
-      return msd.year, msd, med, month_days
+	# Get month details
+	#=======================================================
+	def get_month_details(self):
+		ysd = sql("select year_start_date from `tabFiscal Year` where name ='%s'"%self.doc.fiscal_year)[0][0]
+		if ysd:
+			from dateutil.relativedelta import relativedelta
+			import calendar, datetime
+			mnt = int(self.doc.month)
+			diff_mnt = int(mnt)-int(ysd.month)
+			if diff_mnt<0:
+				diff_mnt = 12-int(ysd.month)+int(mnt)
+			msd = ysd + relativedelta(months=diff_mnt) # month start date
+			month_days = cint(calendar.monthrange(cint(msd.year) ,cint(self.doc.month))[1]) # days in month
+			med = datetime.date(msd.year, cint(self.doc.month), month_days) # month end date
+			return msd.year, msd, med, month_days
 
-  # Calculate LWP
-  #=======================================================
-  def calculate_lwp(self, m):
-    holidays = sql("select t1.holiday_date from `tabHoliday List Detail` t1, tabEmployee t2 where t1.parent = t2.holiday_list and t2.name = '%s' and t1.holiday_date between '%s' and '%s'" % (self.doc.employee, m[1], m[2]))
-    if not holidays:
-      holidays = sql("select t1.holiday_date from `tabHoliday List Detail` t1, `tabHoliday List` t2 where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1 and t2.fiscal_year = '%s'" % self.doc.fiscal_year)
-    holidays = [cstr(i[0]) for i in holidays]
-    lwp = 0
-    for d in range(m[3]):
-      dt = add_days(cstr(m[1]), d)
-      if dt not in holidays:
-        if sql("select t1.name from `tabLeave Application` t1, `tabLeave Type` t2 where t2.name = t1.leave_type and ifnull(t2.is_lwp, 0) = 1 and t1.docstatus = 1 and t1.employee = '%s' and '%s' between from_date and to_date"%(self.doc.employee, dt)):
-          lwp += 1
-    return lwp
-        
-  # Check existing
-  #=======================================================
-  def check_existing(self):
-    ret_exist = sql("select name from `tabSalary Slip` where month = '%s' and fiscal_year = '%s' and docstatus != 2 and employee = '%s' and name !='%s'" % (self.doc.month,self.doc.fiscal_year,self.doc.employee,self.doc.name))
-    if ret_exist:
-      msgprint("Salary Slip of employee '%s' already created for this month" % self.doc.employee)
-      self.doc.employee = ''
-      raise Exception
+	# Calculate LWP
+	#=======================================================
+	def calculate_lwp(self, m):
+		holidays = sql("select t1.holiday_date from `tabHoliday List Detail` t1, tabEmployee t2 where t1.parent = t2.holiday_list and t2.name = '%s' and t1.holiday_date between '%s' and '%s'" % (self.doc.employee, m[1], m[2]))
+		if not holidays:
+			holidays = sql("select t1.holiday_date from `tabHoliday List Detail` t1, `tabHoliday List` t2 where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1 and t2.fiscal_year = '%s'" % self.doc.fiscal_year)
+		holidays = [cstr(i[0]) for i in holidays]
+		lwp = 0
+		for d in range(m[3]):
+			dt = add_days(cstr(m[1]), d)
+			if dt not in holidays:
+				leave = sql("""
+					select t1.name, t1.half_day
+					from `tabLeave Application` t1, `tabLeave Type` t2 
+					where t2.name = t1.leave_type 
+					and ifnull(t2.is_lwp, 0) = 1 
+					and t1.docstatus = 1 
+					and t1.employee = '%s' 
+					and '%s' between from_date and to_date
+				"""%(self.doc.employee, dt))
+				if leave:
+					lwp = cint(leave[0][1]) and lwp + 0.5 or lwp + 1
+		return lwp
+					
+	# Check existing
+	#=======================================================
+	def check_existing(self):
+		ret_exist = sql("select name from `tabSalary Slip` where month = '%s' and fiscal_year = '%s' and docstatus != 2 and employee = '%s' and name !='%s'" % (self.doc.month,self.doc.fiscal_year,self.doc.employee,self.doc.name))
+		if ret_exist:
+			msgprint("Salary Slip of employee '%s' already created for this month" % self.doc.employee)
+			self.doc.employee = ''
+			raise Exception
 
-  # Validate
-  #=======================================================
-  def validate(self):
-    self.check_existing()
-    dcc = TransactionBase().get_company_currency(self.doc.company)
-    self.doc.total_in_words  = get_obj('Sales Common').get_total_in_words(dcc, self.doc.rounded_total)
-    
-  # ON SUBMIT
-  #=======================================================
-  def on_submit(self):
-    if(self.doc.email_check == 1):      
-      self.send_mail_funct()
+	# Validate
+	#=======================================================
+	def validate(self):
+		self.check_existing()
+		dcc = TransactionBase().get_company_currency(self.doc.company)
+		self.doc.total_in_words	= get_obj('Sales Common').get_total_in_words(dcc, self.doc.rounded_total)
+		
+	# ON SUBMIT
+	#=======================================================
+	def on_submit(self):
+		if(self.doc.email_check == 1):			
+			self.send_mail_funct()
 
-  # Send mail
-  #=======================================================
-  def send_mail_funct(self):   
-    emailid_ret=sql("select company_email from `tabEmployee` where name = '%s'"%self.doc.employee)
-    if emailid_ret:
-      receiver = cstr(emailid_ret[0][0]) 
-      subj = 'Salary Slip ' + cstr(self.doc.month) +' '+cstr(self.doc.year)
-      earn_ret=sql("select e_type,e_amount from `tabSS Earning Detail` where parent = '%s'"%self.doc.name)
-      ded_ret=sql("select d_type,d_amount from `tabSS Deduction Detail` where parent = '%s'"%self.doc.name)
-     
-      earn_table = ''
-      ded_table = ''
-      if earn_ret:
-      
-        earn_table += "<table cellspacing= '5' cellpadding='5' >"
-        
-        for e in earn_ret:
-          if not e[1]:
-            earn_table +='<tr><td>%s</td><td>0.00</td></tr>'%(cstr(e[0]))
-          else:
-            earn_table +='<tr><td>%s</td><td>%s</td></tr>'%(cstr(e[0]),cstr(e[1]))
-        earn_table += '</table>'
-      
-      if ded_ret:
-      
-        ded_table += "<table cellspacing= '5' cellpadding='5' >"
-        
-        for d in ded_ret:
-          if not d[1]:
-            ded_table +='<tr><td>%s</td><td>0.00</td></tr>'%(cstr(d[0]))
-          else:
-            ded_table +='<tr><td>%s</td><td>%s</td></tr>'%(cstr(d[0]),cstr(d[1]))
-        ded_table += '</table>'
-      
-      letter_head = sql("select value from `tabSingles` where field = 'letter_head' and doctype = 'Control Panel'")
-      
-      if not letter_head:
-        letter_head = ''
-      
-      msg = ''' %s <br>
-      <table cellspacing= "5" cellpadding="5" >
-      <tr>
-        <td colspan = 4><h4>Salary Slip</h4></td>
-      </tr>
-      <tr>
-        <td colspan = 2><b>Employee Code : %s</b></td>
-        <td colspan = 2><b>Employee Name : %s</b></td>
-      </tr>
-      <tr>
-        <td>Month : %s</td>
-        <td>Year : %s</td>
-        <td colspan = 2>Fiscal Year : %s</td>
-      </tr>
-      <tr>
-        <td>Department : %s</td>
-        <td>Branch : %s</td>
-        <td colspan = 2>Designation : %s</td>
-        
-      </tr>
-      <tr>
-        <td>Grade : %s</td>
-        <td>Bank Account No. : %s</td>
-        <td colspan = 2>Bank Name : %s</td>
-        
-      </tr>
-      <tr>
-        <td>PF No. : %s</td>
-        <td>ESIC No. : %s</td>
-        <td colspan = 2>Arrear Amount : <b>%s</b></td>
-      </tr>
-      <tr>
-        <td>Total days in month : %s</td>
-        <td>Leave Without Pay : %s</td>
-        <td colspan = 2>Payment days : %s</td>
-        
-      </tr>
-      <br><br>
-      <tr>
-        <td colspan = 2><b>Earning</b></td>
-        <td colspan = 2><b>Deduction</b></td>
-      </tr>
-      <tr>
-        <td colspan = 2>%s</td>
-        <td colspan = 2>%s</td>
-      </tr>
-      <br>
-      <tr>
-        <td colspan = 2><b>Gross Pay :</b> %s</td>
-        <td colspan = 2><b>Total Deduction :</b> %s</td>
-      </tr>
-      <tr>
-        <td><b>Net Pay : %s</b></td>
-        <td colspan = 3><b>Net Pay (in words) : %s</b></td>
-      </tr>
-      </table>'''%(cstr(letter_head[0][0]),cstr(self.doc.employee),self.doc.employee_name,cstr(self.doc.month),cstr(self.doc.year),cstr(self.doc.fiscal_year),self.doc.department,self.doc.branch,self.doc.designation,self.doc.grade,cstr(self.doc.bank_account_no),self.doc.bank_name,cstr(self.doc.pf_no),cstr(self.doc.esic_no),cstr(self.doc.arrear_amount),cstr(self.doc.total_days_in_month),cstr(self.doc.leave_without_pay),cstr(self.doc.payment_days),earn_table,ded_table,cstr(self.doc.gross_pay),cstr(self.doc.total_deduction),cstr(self.doc.net_pay),cstr(self.doc.net_pay_in_words))
-      sendmail([receiver], sender='automail@webnotestech.com', subject=subj, parts=[['text/plain', msg]])
-    else:
-      msgprint("Company Email ID not found.")
+	# Send mail
+	#=======================================================
+	def send_mail_funct(self):	 
+		emailid_ret=sql("select company_email from `tabEmployee` where name = '%s'"%self.doc.employee)
+		if emailid_ret:
+			receiver = cstr(emailid_ret[0][0]) 
+			subj = 'Salary Slip ' + cstr(self.doc.month) +' '+cstr(self.doc.year)
+			earn_ret=sql("select e_type,e_amount from `tabSS Earning Detail` where parent = '%s'"%self.doc.name)
+			ded_ret=sql("select d_type,d_amount from `tabSS Deduction Detail` where parent = '%s'"%self.doc.name)
+		 
+			earn_table = ''
+			ded_table = ''
+			if earn_ret:
+			
+				earn_table += "<table cellspacing= '5' cellpadding='5' >"
+				
+				for e in earn_ret:
+					if not e[1]:
+						earn_table +='<tr><td>%s</td><td>0.00</td></tr>'%(cstr(e[0]))
+					else:
+						earn_table +='<tr><td>%s</td><td>%s</td></tr>'%(cstr(e[0]),cstr(e[1]))
+				earn_table += '</table>'
+			
+			if ded_ret:
+			
+				ded_table += "<table cellspacing= '5' cellpadding='5' >"
+				
+				for d in ded_ret:
+					if not d[1]:
+						ded_table +='<tr><td>%s</td><td>0.00</td></tr>'%(cstr(d[0]))
+					else:
+						ded_table +='<tr><td>%s</td><td>%s</td></tr>'%(cstr(d[0]),cstr(d[1]))
+				ded_table += '</table>'
+			
+			letter_head = sql("select value from `tabSingles` where field = 'letter_head' and doctype = 'Control Panel'")
+			
+			if not letter_head:
+				letter_head = ''
+			
+			msg = ''' %s <br>
+			<table cellspacing= "5" cellpadding="5" >
+			<tr>
+				<td colspan = 4><h4>Salary Slip</h4></td>
+			</tr>
+			<tr>
+				<td colspan = 2><b>Employee Code : %s</b></td>
+				<td colspan = 2><b>Employee Name : %s</b></td>
+			</tr>
+			<tr>
+				<td>Month : %s</td>
+				<td>Year : %s</td>
+				<td colspan = 2>Fiscal Year : %s</td>
+			</tr>
+			<tr>
+				<td>Department : %s</td>
+				<td>Branch : %s</td>
+				<td colspan = 2>Designation : %s</td>
+				
+			</tr>
+			<tr>
+				<td>Grade : %s</td>
+				<td>Bank Account No. : %s</td>
+				<td colspan = 2>Bank Name : %s</td>
+				
+			</tr>
+			<tr>
+				<td>PF No. : %s</td>
+				<td>ESIC No. : %s</td>
+				<td colspan = 2>Arrear Amount : <b>%s</b></td>
+			</tr>
+			<tr>
+				<td>Total days in month : %s</td>
+				<td>Leave Without Pay : %s</td>
+				<td colspan = 2>Payment days : %s</td>
+				
+			</tr>
+			<br><br>
+			<tr>
+				<td colspan = 2><b>Earning</b></td>
+				<td colspan = 2><b>Deduction</b></td>
+			</tr>
+			<tr>
+				<td colspan = 2>%s</td>
+				<td colspan = 2>%s</td>
+			</tr>
+			<br>
+			<tr>
+				<td colspan = 2><b>Gross Pay :</b> %s</td>
+				<td colspan = 2><b>Total Deduction :</b> %s</td>
+			</tr>
+			<tr>
+				<td><b>Net Pay : %s</b></td>
+				<td colspan = 3><b>Net Pay (in words) : %s</b></td>
+			</tr>
+			</table>'''%(cstr(letter_head[0][0]),cstr(self.doc.employee),self.doc.employee_name,cstr(self.doc.month),cstr(self.doc.year),cstr(self.doc.fiscal_year),self.doc.department,self.doc.branch,self.doc.designation,self.doc.grade,cstr(self.doc.bank_account_no),self.doc.bank_name,cstr(self.doc.pf_no),cstr(self.doc.esic_no),cstr(self.doc.arrear_amount),cstr(self.doc.total_days_in_month),cstr(self.doc.leave_without_pay),cstr(self.doc.payment_days),earn_table,ded_table,cstr(self.doc.gross_pay),cstr(self.doc.total_deduction),cstr(self.doc.net_pay),cstr(self.doc.net_pay_in_words))
+			sendmail([receiver], sender='automail@webnotestech.com', subject=subj, parts=[['text/plain', msg]])
+		else:
+			msgprint("Company Email ID not found.")
diff --git a/hr/doctype/salary_slip/salary_slip.txt b/hr/doctype/salary_slip/salary_slip.txt
index 2886e42..423b6c0 100644
--- a/hr/doctype/salary_slip/salary_slip.txt
+++ b/hr/doctype/salary_slip/salary_slip.txt
@@ -5,7 +5,7 @@
 	{
 		'creation': '2010-08-08 17:09:20',
 		'docstatus': 0,
-		'modified': '2011-07-14 16:07:20',
+		'modified': '2011-07-27 13:10:28',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -21,7 +21,7 @@
 		'server_code_error': ' ',
 		'show_in_menu': 0,
 		'subject': 'For %(employee_name)s, %(designation)s',
-		'version': 392
+		'version': 393
 	},
 
 	# These values are common for all DocField
@@ -55,19 +55,7 @@
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
-		'match': 'owner',
-		'permlevel': 0,
-		'role': 'Employee',
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
-		'doctype': 'DocPerm',
+		'idx': 1,
 		'match': 'owner',
 		'permlevel': 0,
 		'role': 'Employee',
@@ -80,7 +68,7 @@
 		'amend': 0,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 3,
+		'idx': 2,
 		'permlevel': 0,
 		'role': 'HR User',
 		'submit': 1,
@@ -93,7 +81,7 @@
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 4,
+		'idx': 3,
 		'permlevel': 0,
 		'role': 'HR Manager',
 		'submit': 1,
@@ -103,7 +91,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 5,
+		'idx': 4,
 		'permlevel': 1,
 		'role': 'HR User'
 	},
@@ -111,7 +99,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 6,
+		'idx': 5,
 		'permlevel': 1,
 		'role': 'HR Manager'
 	},
@@ -150,7 +138,7 @@
 		'options': 'Employee',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 0
+		'search_index': 1
 	},
 
 	# DocField
@@ -180,7 +168,7 @@
 		'options': 'Department',
 		'permlevel': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -195,7 +183,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Designation',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -210,7 +198,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Branch',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -225,7 +213,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Grade',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -287,7 +275,7 @@
 		'options': 'Fiscal Year',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/hr/doctype/salary_structure/salary_structure.py b/hr/doctype/salary_structure/salary_structure.py
index fd295ea..36a1855 100644
--- a/hr/doctype/salary_structure/salary_structure.py
+++ b/hr/doctype/salary_structure/salary_structure.py
@@ -42,7 +42,7 @@
         'grade'          : cstr(det[0][4]),
         'backup_employee': cstr(self.doc.employee)
       }
-    return cstr(ret)
+    return ret
     
 
   # Set Salary structure field values
@@ -53,7 +53,7 @@
             'bank_ac_no'  : basic_info and basic_info[0][1] or '',
             'esic_no'     : basic_info and basic_info[0][2] or '',
             'pf_no'       : basic_info and basic_info[0][3] or ''}
-    return cstr(ret)
+    return ret
    
   # Make earning and deduction table    
   #---------------------------------------------------------
diff --git a/knowledge_base/doctype/question/question.txt b/knowledge_base/doctype/question/question.txt
index 428d269..187789c 100644
--- a/knowledge_base/doctype/question/question.txt
+++ b/knowledge_base/doctype/question/question.txt
@@ -115,7 +115,8 @@
 		'label': 'Tag 1',
 		'oldfieldname': 'tag_1',
 		'oldfieldtype': 'Link',
-		'options': 'Question Tag'
+		'options': 'Question Tag',
+		'search_index': 0
 	},
 
 	# DocField
@@ -136,7 +137,8 @@
 		'label': 'Tag 2',
 		'oldfieldname': 'tag_2',
 		'oldfieldtype': 'Link',
-		'options': 'Question Tag'
+		'options': 'Question Tag',
+		'search_index': 0
 	},
 
 	# DocField
@@ -148,7 +150,8 @@
 		'label': 'Tag 3',
 		'oldfieldname': 'tag_3',
 		'oldfieldtype': 'Link',
-		'options': 'Question Tag'
+		'options': 'Question Tag',
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/knowledge_base/page/question_view/question_view.js b/knowledge_base/page/question_view/question_view.js
index 895c6f7..ed11efc 100644
--- a/knowledge_base/page/question_view/question_view.js
+++ b/knowledge_base/page/question_view/question_view.js
@@ -174,4 +174,4 @@
 }
 
 
-$import(knowledge_base.kb_common);
\ No newline at end of file
+$import(knowledge_base/page/kb_common/kb_common.js);
\ No newline at end of file
diff --git a/knowledge_base/page/questions/questions.js b/knowledge_base/page/questions/questions.js
index 993a38e..f268d0b 100644
--- a/knowledge_base/page/questions/questions.js
+++ b/knowledge_base/page/questions/questions.js
@@ -203,4 +203,4 @@
 	this.make()
 }
 
-$import(knowledge_base.kb_common);
\ No newline at end of file
+$import(knowledge_base/page/kb_common/kb_common.js);
\ No newline at end of file
diff --git a/knowledge_base/page/questions/questions.txt b/knowledge_base/page/questions/questions.txt
index d71225a..b45c7dd 100644
--- a/knowledge_base/page/questions/questions.txt
+++ b/knowledge_base/page/questions/questions.txt
@@ -15,7 +15,7 @@
 		'doctype': 'Page',
 		'module': 'Knowledge Base',
 		'name': '__common__',
-		'page_name': 'Questions',
+		'page_name': 'questions',
 		'standard': 'Yes'
 	},
 
diff --git a/master.sql.gz b/master.sql.gz
index 05fc390..273277e 100644
--- a/master.sql.gz
+++ b/master.sql.gz
Binary files differ
diff --git a/patches/erpnext_structure_cleanup.py b/patches/erpnext_structure_cleanup.py
index 8b765de..e78a82e 100644
--- a/patches/erpnext_structure_cleanup.py
+++ b/patches/erpnext_structure_cleanup.py
@@ -195,6 +195,6 @@
 	sync_mapper()
 	delete_unwanted_modules()
 	# landed cost wizard link in stock
-	reload_doc('stock', 'Module Def', 'stock')
+	reload_doc('stock', 'Module Def', 'Stock')
 	
 	sql("commit")
diff --git a/patches/index_patch.py b/patches/index_patch.py
index 8f6c4f2..3ef8ec3 100644
--- a/patches/index_patch.py
+++ b/patches/index_patch.py
@@ -2,6 +2,9 @@
 	This patch removes wrong indexs and add proper indexes in tables
 """
 
+import webnotes
+sql = webnotes.conn.sql
+from webnotes.utils import cint, cstr
 
 def create_proper_index():
 	from webnotes.modules.export_module import export_to_files
@@ -264,29 +267,29 @@
 						'Print Heading': [], 
 						'TDS Rate Detail': ['category']
 					}
-				
-	for dt in dt_index_fields.keys():
-		current_index = sql("show indexes from `tab%s`" % dt)
+	#sql("commit") # only required if run from login
+	exist_dt = [cstr(d[0]) for d in sql("select name from `tabDocType`")]
 	
-		proper_index = dt_index_fields[dt]
+	for dt in [d for d in dt_index_fields.keys() if d in exist_dt]:
+		try:
+			current_index = sql("show indexes from `tab%s`" % dt)
 	
-		for d in current_index:
-			if d[4] not in ['name', 'parent', 'parenttype']:
-				if d[4] not in proper_index:
-					sql("ALTER TABLE `tab%s` DROP INDEX %s" % (dt, d[4]))
-					sql("start transaction")
-					sql("UPDATE `tabDocField` SET search_index = 0 WHERE fieldname = '%s' AND parent = '%s'" % (d[4], dt))
-					sql("commit")
-				else:
-					proper_index.remove(d[4])
+			proper_index = dt_index_fields[dt]
 	
-		for d in proper_index:
-			sql("ALTER TABLE `tab%s` ADD INDEX ( `%s` ) " % (dt, d))
-			sql("start transaction")
-			sql("UPDATE `tabDocField` SET search_index = 1 WHERE fieldname = '%s' AND parent = '%s'" % (d, dt))
-			sql("commit")
-
-		sql("start transaction")		
-		dt_module = sql("select module from `tabDocType` where name = '%s'" % dt)[0][0]
-		export_to_files(record_list = [['DocType', dt]], record_module = dt_module)
-		sql("commit")
+			for d in current_index:
+				if d[4] not in ['name', 'parent', 'parenttype']:
+					if d[4] not in proper_index:
+						sql("ALTER TABLE `tab%s` DROP INDEX %s" % (dt, d[4]))
+						sql("start transaction")
+						sql("UPDATE `tabDocField` SET search_index = 0 WHERE fieldname = '%s' AND parent = '%s'" % (d[4], dt))
+						sql("commit")
+					else:
+						proper_index.remove(d[4])
+	
+			for d in proper_index:
+				sql("ALTER TABLE `tab%s` ADD INDEX ( `%s` ) " % (dt, d))
+				sql("start transaction")
+				sql("UPDATE `tabDocField` SET search_index = 1 WHERE fieldname = '%s' AND parent = '%s'" % (d, dt))
+				sql("commit")
+		except:
+			continue
diff --git a/setup/doctype/support_email_settings/__init__.py b/patches/old_patches/__init__.py
similarity index 100%
copy from setup/doctype/support_email_settings/__init__.py
copy to patches/old_patches/__init__.py
diff --git a/patches/old_patches/customer_address.py b/patches/old_patches/customer_address.py
index 6a031c4..41c97b8 100644
--- a/patches/old_patches/customer_address.py
+++ b/patches/old_patches/customer_address.py
@@ -6,7 +6,7 @@
 
 def make_address():
 	from webnotes.modules.module_manager import reload_doc
-	reload_doc('tools','doctype','address')
+	reload_doc('utilities','doctype','address')
 	
 	from webnotes.model.db_schema import updatedb
 	updatedb('Address')
@@ -113,24 +113,24 @@
 
 def reload_doc_files():
 	from webnotes.modules.module_manager import reload_doc	
-	reload_doc('tools', 'doctype', 'contact')
-	reload_doc('crm', 'doctype', 'customer')
-	reload_doc('maintenance', 'doctype', 'customer_issue')
-	reload_doc('material_management', 'doctype', 'delivery_note')
-	reload_doc('crm', 'doctype', 'enquiry')
-	reload_doc('crm', 'doctype', 'installation_note')
-	reload_doc('crm', 'doctype', 'lead')
-	reload_doc('maintenance', 'doctype', 'maintenance_schedule')
-	reload_doc('maintenance', 'doctype', 'maintenance_visit')
-	reload_doc('srm', 'doctype', 'purchase_order')
-	reload_doc('material_management', 'doctype', 'purchase_receipt')
-	reload_doc('crm', 'doctype', 'quotation')
+	reload_doc('utilities', 'doctype', 'contact')
+	reload_doc('selling', 'doctype', 'customer')
+	reload_doc('support', 'doctype', 'customer_issue')
+	reload_doc('stock', 'doctype', 'delivery_note')
+	reload_doc('selling', 'doctype', 'enquiry')
+	reload_doc('selling', 'doctype', 'installation_note')
+	reload_doc('selling', 'doctype', 'lead')
+	reload_doc('support', 'doctype', 'maintenance_schedule')
+	reload_doc('support', 'doctype', 'maintenance_visit')
+	reload_doc('buying', 'doctype', 'purchase_order')
+	reload_doc('stock', 'doctype', 'purchase_receipt')
+	reload_doc('selling', 'doctype', 'quotation')
 	reload_doc('accounts', 'doctype', 'receivable_voucher')
 	reload_doc('accounts', 'doctype', 'payable_voucher')	
-	reload_doc('crm', 'doctype', 'sales_order')
+	reload_doc('selling', 'doctype', 'sales_order')
 	reload_doc('setup', 'doctype', 'sales_partner')
-	reload_doc('material_management', 'doctype', 'serial_no')
-	reload_doc('srm', 'doctype', 'supplier')
+	reload_doc('stock', 'doctype', 'serial_no')
+	reload_doc('buying', 'doctype', 'supplier')
 	
 def reload_mapper_files():
 	from webnotes.modules.module_manager import reload_doc	
diff --git a/patches/old_patches/feed_patch.py b/patches/old_patches/feed_patch.py
index d368aa0..9d8ab0b 100644
--- a/patches/old_patches/feed_patch.py
+++ b/patches/old_patches/feed_patch.py
@@ -98,6 +98,5 @@
 	
 	webnotes.model.delete_doc('DocType','Support Ticket')
 	reload_doc('setup','doctype','support_email_settings')
-	reload_doc('maintenance','doctype','support_ticket')
-	reload_doc('maintenance','doctype','support_ticket_response')
-	
+	reload_doc('support','doctype','support_ticket')
+	reload_doc('support','doctype','support_ticket_response')
diff --git a/patches/patch.py b/patches/patch.py
index f184197..4a57219 100644
--- a/patches/patch.py
+++ b/patches/patch.py
@@ -1,13 +1,12 @@
 # REMEMBER to update this
 # ========================
 
-last_patch = 325
+last_patch = 339
 
 #-------------------------------------------
 
 def execute(patch_no):
 	import webnotes
-	from webnotes.modules.import_module import import_from_files
 	from webnotes.modules.module_manager import reload_doc
 
 	from webnotes.model.code import get_obj
@@ -47,7 +46,7 @@
 		for d in path_list:
 			doclist = eval(open(d,'r').read())
 			webnotes.conn.sql("update `tab%s` set module = '%s' where name = '%s'" % (doclist[0]['doctype'], doclist[0]['module'], doclist[0]['name']))
-	
+
 	elif patch_no==38:
 		import webnotes
 		webnotes.conn.set_global("system_message", "System Updates: Hello! You would have noticed some changes on the Home Page. As a part of our commitment to make the system more friendly and social, we have re-designed the feed so that now you will only see feed that is relevant to you (either you have created something or you have been mentioned in the document).<br><br>On the individual listings, you can add tags and also color them!<br><br>You will also get time-to-time updates from our side here. Do keep sending your feedback at support@erpnext.com.")
@@ -57,8 +56,8 @@
 		pass
 
 	elif patch_no == 40:
-		
 		import_from_files(record_list=[['material_management','doctype','item']])
+
 	elif patch_no == 42:
 		acc = sql("select name, lft, rgt from tabAccount where account_name in ('Incomes', 'Expenses')")
 		for d in acc:
@@ -66,7 +65,7 @@
 	elif patch_no == 43:
 		import webnotes.model
 		webnotes.model.delete_doc('Page', 'Module Manager')
-	
+
 	# cleanup of Service, Customer Support, Utilities Modules
 	# -------------------------------------------------------
 	elif patch_no == 44:
@@ -87,7 +86,7 @@
 
 		# remove utilities
 		webnotes.conn.sql('delete from `tabModule Def` where name in ("Customer Support", "Utilities")')
-		
+
 	elif patch_no == 45:
 		webnotes.conn.sql('delete from tabDocField where options="Ticket Response Detail"')
 
@@ -126,32 +125,32 @@
 	elif patch_no == 56:
 		sql("delete from `tabModule Def Item` where parent = 'CRM' and doc_type = 'Reports' and doc_name = 'Delivery Note' and display_name = 'Territory, Item Group wise GP'")
 	elif patch_no == 57:
-		
-		import_from_files(record_list=[['crm','doctype','sales_order_detail']])
+		import_from_files(record_list=[['selling','doctype','sales_order_detail']])
+
 	elif patch_no == 58:
 		# module def patches
 		sql("update `tabModule Def` set module_page = NULL where name not in ('Event Updates', 'Setup', 'My Company')")
 		sql("delete from `tabModule Def Item` where doc_type in ('Separator', 'Setup Forms', 'More Reports')")
 		sql("delete from `tabModule Def Item` where doc_name = 'Project Activity'")
 		sql("update `tabModule Def` set module_label = 'People', disabled='No', is_hidden='No' where name = 'My Company'")
-		
+
 		# insert new module items
 		from webnotes.model.doc import make_autoname
 		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Ticket'"):
-			sql("""insert into `tabModule Def Item` 
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values 
+			sql("""insert into `tabModule Def Item`
+				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
 				(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Ticket', 'Task', 1)""", make_autoname('MDI.#####'))
 
 		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Timesheet'"):
-			sql("""insert into `tabModule Def Item` 
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values 
+			sql("""insert into `tabModule Def Item`
+				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
 				(%s, 'Projects', 'Module Def', 'items', 0, 'Forms', 'Timesheet', 'Timesheet', 2)""", make_autoname('MDI.#####'))
-			
+
 		if not sql("select name from `tabModule Def Item` where parent='Projects' and doc_name='Projects'"):
-			sql("""insert into `tabModule Def Item` 
-				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values 
+			sql("""insert into `tabModule Def Item`
+				(name, parent, parenttype, parentfield, docstatus, doc_type, doc_name, display_name, idx) values
 				(%s, 'Projects', 'Module Def', 'items', 0, 'Pages', 'Projects', 'Gantt Chart', 1)""", make_autoname('MDI.#####'))
-				
+
 	elif patch_no == 59:
 		webnotes.conn.set_value('Control Panel',None,'mail_footer','')
 		webnotes.conn.set_global('global_mail_footer','<div style="margin-top:8px; padding: 8px; font-size: 11px; text-align:right; border-top: 1px solid #AAA">Sent via <a href="https://www.erpnext.com">ERPNext</a></div>')
@@ -161,17 +160,17 @@
 		sql("delete from `tabTDS Category Account` where company not in (select name from tabCompany)")
 	elif patch_no == 62:
 		# Import Supplier Quotation
-		
 		import_from_files(record_list=[['srm','doctype','supplier_quotation']])
+
 		# Adding Status Filter
 		sql("update tabDocType set search_fields = concat('status,',search_fields) where name IN ('Delivery Note','Leave Transaction')")
 		# Import Other Charges
-		
+
 		import_from_files(record_list=[['setup','doctype','other_charges']])
 	elif patch_no == 63:
 		sql("update `tabDocField` set permlevel = 1 where fieldname in ('return_date', 'return_details') and parent = 'Sales and Purchase Return Wizard'")
-		
 		import_from_files(record_list = [['accounts', 'doctype', 'rv_detail'], ['material_management', 'doctype', 'sales_and_purchase_return_wizard'], ['material_management', 'doctype', 'stock_entry']])
+
 	elif patch_no == 64:
 		sql("update tabDocField set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where options in ('RFQ','Supplier Quotation')")
 		sql("update tabDocType set `read_only` = 1, in_create = 1 where name in ('RFQ','Supplier Quotation')")
@@ -184,7 +183,7 @@
 		import webnotes
 		webnotes.conn.set_global("system_message", """<h3>UI Updates</h3>Based on user feedback, we have made a couple of changes in the UI:<ul><li>Sidebar menus are now collapsable</li><li>Forms are now scrollable (we removed the confusing tabs)</li><li>Feed is a lot more descriptive</li></ul>Do send us your feedback!""")
 		webnotes.conn.set_global("system_message_id", "4")
-		
+
 		sql("update `tabModule Def Item` set doc_type = 'Setup Forms' where doc_name in ('TDS Payment', 'TDS Return Acknowledgement', 'Form 16A', 'Period Closing Voucher', 'IT Checklist')")
 		from webnotes.session_cache import clear_cache
 		clear_cache(webnotes.session['user'])
@@ -193,7 +192,7 @@
 		sql("delete from `tabModule Def Item` where (display_name = 'Sales Invoice' and parent = 'CRM') or (display_name = 'Purchase Invoice' and parent = 'SRM')")
 	elif patch_no == 68:
 		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['payroll','doctype','employee'],['roles','Role','Employee']])
+		import_from_files(record_list=[['hr','doctype','employee'],['roles','Role','Employee']])
 	elif patch_no == 69:
 		# delete flds from employee master
 		p = get_obj('Patch Util')
@@ -213,7 +212,7 @@
 			for d in fld_map:
 				emp_obj.doc.fields[d] = prof_obj.doc.fields[d]
 			emp_obj.doc.current_accommodation_type = prof_obj.doc.present_accommodation_type
-		 
+
 			# address
 			per_addr = cstr(e[2]) + '\n' + cstr(e[3]) + '\n' + cstr(e[4]) + '\n' + cstr(e[5]) + ', ' + cstr(e[6]) + '\n' + 'PIN - ' + cstr(e[7]) + '\n' + 'Ph. No' + cstr(e[8])
 			cur_addr = cstr(e[9]) + '\n' + cstr(e[10]) + '\n' + cstr(e[11]) + '\n' + cstr(e[12]) + ', ' + cstr(e[13]) + '\n' + 'PIN - ' + cstr(e[14]) + '\n' + 'Ph. No' + cstr(e[15])
@@ -245,7 +244,7 @@
 	elif patch_no == 70:
 		# update search criteria module -> System
 		sql("update tabDocType set module='System' where name='Search Criteria'")
-		
+
 		# Cleanups to Contact
 		sql("update tabDocField set fieldtype='Data' where options='Designation' and parent='Contact'")
 		sql("update tabDocField set fieldtype='Data' where options='Department' and parent='Contact'")
@@ -253,12 +252,12 @@
 
 		# import Contact, Employee
 		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['tools','doctype','contact']])
+		import_from_files(record_list=[['utilities','doctype','contact']])
 
-		
+
 		# remove last_contact_date from Lead
 		sql("delete from tabDocField where fieldname='last_contact_date' and parent='Lead'")
-		
+
 	elif patch_no == 71:
 		# Make Stock Qty and Conversion Factor field editable. Also no need to mention Conversion factor in table can do it directly
 		sql("update `tabDocField` set `permlevel` = 0, `width` = '100px', `trigger` = 'Client' where parent IN ('PO Detail','Purchase Receipt Detail') and fieldname in ('stock_qty','conversion_factor')")
@@ -267,18 +266,18 @@
 	elif patch_no == 72:
 		# Core Patch
 		# ----------
-		
+
 		from webnotes.modules.import_module import import_from_files
-		
+
 		# import module def
 		import_from_files(record_list = [['core', 'Module Def', 'Core']])
 	elif patch_no == 73:
 		# set module in DocTypes
 		sql("update tabDocType set module='Core' where name in ('DocType', 'DocField', 'DocPerm', 'Role', 'UserRole', 'Profile', 'Print Format', 'DocFormat', 'Control Panel', 'Event', 'Event Role', 'Event User', 'DefaultValue', 'Default Home Page', 'File', 'File Group', 'File Data', 'Letter Head', 'Module Def', 'Module Def Item', 'Module Def Role', 'Page', 'Page Role', 'Search Criteria', 'DocType Label', 'DocType Mapper', 'Field Mapper Detail', 'Table Mapper Detail')")
-		
+
 		# set module in Page
 		sql("update tabPage set module='Core' where name='Login Page'")
-		
+
 		# move file browser to Tools
 		sql("update tabPage set module='Tools' where name='File Browser'")
 		sql("update tabDocType set module='Tools' where name='File Browser Control'")
@@ -295,7 +294,7 @@
 		#sal structure patch
 		# import
 		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['payroll','doctype','salary_structure'], ['payroll','doctype','earning_detail'],['payroll','doctype','deduction_detail']])
+		import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr','doctype','earning_detail'],['hr','doctype','deduction_detail']])
 	elif patch_no == 76:
 		# property
 		p = get_obj('Patch Util')
@@ -322,7 +321,7 @@
 		# sal slip patch
 		# import
 		from webnotes.modules.import_module import import_from_files
-		import_from_files(record_list=[['payroll','doctype','salary_slip'], ['payroll','doctype','ss_earning_detail'],['payroll','doctype','ss_deduction_detail'], ['mapper', 'DocType Mapper', 'Salary Structure-Salary Slip']])
+		import_from_files(record_list=[['hr','doctype','salary_slip'], ['hr','doctype','ss_earning_detail'],['hr','doctype','ss_deduction_detail'], ['mapper', 'DocType Mapper', 'Salary Structure-Salary Slip']])
 	elif patch_no == 78:
 		p = get_obj('Patch Util')
 		# delete
@@ -352,8 +351,7 @@
 		p.add_permission('Salary Slip', 'Employee', 1, read = 1, match = 'owner')
 	elif patch_no == 79:
 		# Import Modules
-		
-		import_from_files(record_list=[['payroll','doctype','leave_application'],['payroll','doctype','leave_allocation'],['payroll','doctype','leave_control_panel'],['payroll','doctype','holiday_list'],['payroll','doctype','holiday_list_detail'],['payroll','Module Def','Payroll']])
+		import_from_files(record_list=[['hr','doctype','leave_application'],['hr','doctype','leave_allocation'],['hr','doctype','leave_control_panel'],['hr','doctype','holiday_list'],['hr','doctype','holiday_list_detail'],['hr','Module Def','HR']])
 	elif patch_no == 80:
 		# Holiday List
 		sql("update `tabHoliday List Detail` set description = holiday_name")
@@ -406,8 +404,7 @@
 
 	elif patch_no == 81:
 		# Import Modules
-		
-		import_from_files(record_list=[['payroll','Module Def','Payroll']])
+		import_from_files(record_list=[['hr','Module Def','HR']])
 	elif patch_no == 82:
 		sql("update tabDocType set search_fields = 'employee,leave_type,total_leaves_allocated,fiscal_year' where name = 'Leave Allocation'")
 		sql("update tabDocType set search_fields = 'employee,leave_type,from_date,to_date,total_leave_days,fiscal_year' where name = 'Leave Application'")
@@ -433,14 +430,13 @@
 		sql("update tabDocPerm set `match` = '' where parent = 'Leave Application' and role = 'HR User'")
 	elif patch_no == 86:
 		# Import Modules
-		
-		import_from_files(record_list=[['payroll','doctype','leave_type']])
+		import_from_files(record_list=[['hr','doctype','leave_type']])
 	elif patch_no == 87:
 		sql("update `tabLeave Type` set is_lwp = 1 where name = 'Leave Without Pay'")
 	elif patch_no == 88:
 		# Import Modules
-		
-		import_from_files(record_list=[['payroll','doctype','leave_allocation']])
+		import_from_files(record_list=[['hr','doctype','leave_allocation']])
+
 	elif patch_no == 89:
 		sql("delete from `tabModule Def Item` where doc_type = 'Setup Forms' and doc_name in ('Payroll Rule', 'IT Checklist', 'Employee Profile') and parent = 'Payroll'")
 		sql("update `tabDocField` set `hidden` = 1, `print_hide` = 1, `report_hide` = 1 where parent = 'Leave Type' and fieldname = 'is_encash'")
@@ -458,10 +454,8 @@
 		sql("update `tabTable Mapper Detail` set validation_logic = 'qty > ifnull(billed_qty,0) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail'")
 		sql("update `tabField Mapper Detail` set from_field = 'customer' where to_field = 'customer' and parent = 'Sales Order-Receivable Voucher'")
 	elif patch_no == 94:
-		
-		import_from_files(record_list=[['crm','doctype','sms_center']])
+		import_from_files(record_list=[['selling','doctype','sms_center']])
 	elif patch_no == 95:
-		
 		import_from_files(record_list=[['mapper','DocType Mapper','Sales Order-Receivable Voucher'], ['mapper','DocType Mapper','Delivery Note-Receivable Voucher']])
 	elif patch_no == 96:
 		sql("delete from `tabModule Def Item` where doc_type = 'Reports' and display_name = 'Cenvat Credit - Input or Capital Goods' and parent = 'Accounts'")
@@ -491,8 +485,8 @@
 	elif patch_no == 103:
 		sql("update tabDocField set fieldname = '' where fieldtype = 'HTML'")
 	elif patch_no == 104:
-		
-		import_from_files(record_list=[['payroll','search_criteria','stdsrch_00001'],['payroll','search_criteria','stdsrch_00002'],['payroll','search_criteria','stdsrch_00003'],['payroll','Module Def','Payroll'],['payroll','doctype','leave_application'],['payroll','doctype','leave_allocation']])
+		import_from_files(record_list=[['hr','search_criteria','stdsrch_00001'],['hr','search_criteria','stdsrch_00002'],['hr','search_criteria','stdsrch_00003'],['hr','Module Def','HR'],['hr','doctype','leave_application'],['hr','doctype','leave_allocation']])
+
 	elif patch_no == 105:
 		# Employee Leave Balance
 		sql("delete from `tabModule Def Item` where parent = 'Payroll' and doc_type = 'Reports' and display_name IN ('Employeewise Leave Transaction Details','Employeewise Balance Leave Report')")
@@ -509,11 +503,11 @@
 	elif patch_no == 107:
 		sql("delete from `tabDocField` where fieldname = 'fiscal_year' and parent = 'Employee'")
 	elif patch_no == 108:
-		import_from_files(record_list=[['payroll','search_criteria','srch_std_00013']])
+		import_from_files(record_list=[['hr','search_criteria','srch_std_00013']])
 	elif patch_no == 109:
-		import_from_files(record_list=[['payroll','search_criteria','srch_std_00015']])
+		import_from_files(record_list=[['hr','search_criteria','srch_std_00015']])
 	elif patch_no == 110:
-		import_from_files(record_list=[['payroll','doctype','salary_structure'], ['payroll', 'doctype', 'salary_slip']])
+		import_from_files(record_list=[['hr','doctype','salary_structure'], ['hr', 'doctype', 'salary_slip']])
 	elif patch_no == 111:
 		sql("update tabDocType set search_fields = 'transfer_date, from_warehouse, to_warehouse, purpose, remarks' where name = 'Stock Entry'")
 	elif patch_no == 112:
@@ -536,7 +530,7 @@
 		# patch for timesheet cleanup
 		from webnotes.model import delete_doc
 		delete_doc('DocType', 'Timesheet Detail')
-		
+
 		from webnotes.modules.import_module import import_from_files
 		import_from_files(record_list = [['Projects', 'DocType', 'Timesheet'], ['Projects', 'DocType', 'Timesheet Detail'], ['Projects', 'DocType', 'Activity Type']])
 
@@ -544,7 +538,7 @@
 		# again!
 		from webnotes.model import delete_doc
 		delete_doc('DocType', 'Timesheet Detail')
-		
+
 		from webnotes.modules.import_module import import_from_files
 		import_from_files(record_list = [['Projects', 'DocType', 'Timesheet Detail']])
 	elif patch_no == 117:
@@ -583,7 +577,7 @@
 		p.add_permission('Expense Voucher', 'HR User', 0, read = 1, write = 1, create = 1, submit = 1, cancel = 1, amend = 1)
 	elif patch_no == 128:
 		from webnotes.modules import import_module
-		import_module.import_from_files(record_list=[['crm','doctype','sales_order'], ['crm','doctype','sales_order_detail'],  ['material_management','doctype','delivery_note'], ['material_management','doctype','delivery_note_detail']])
+		import_module.import_from_files(record_list=[['selling','doctype','sales_order'], ['selling','doctype','sales_order_detail'],  ['stock','doctype','delivery_note'], ['stock','doctype','delivery_note_detail']])
 	elif patch_no == 129:
 		sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Sales Order-Receivable Voucher' and from_table = 'Sales Order Detail' and to_table = 'RV Detail'")
 		sql("update `tabTable Mapper Detail` set validation_logic = '(qty > ifnull(billed_qty, 0) or amount > ifnull(billed_amt, 0)) and docstatus = 1' where parent = 'Delivery Note-Receivable Voucher' and from_table = 'Delivery Note Detail' and to_table = 'RV Detail'")
@@ -647,13 +641,13 @@
 	elif patch_no == 142:
 		# fixes to letter head and personalize
 		from webnotes.model import delete_doc
-		
+
 		delete_doc('DocType', 'Batch Settings')
 		delete_doc('DocType', 'Batch Settings Detail')
 		delete_doc('DocType', 'Social Badge')
 		delete_doc('Page', 'Personalize Page')
 		delete_doc('DocType', 'Personalize Page Control')
-		
+
 		import_from_files(record_list=[['core','doctype','letter_head'], ['setup','doctype','personalize']])
 	elif patch_no == 144:
 		webnotes.conn.sql("update tabDocField set fieldtype='Code' where parent='Letter Head' and fieldname='content'")
@@ -681,11 +675,11 @@
 		sql("delete from tabDocField where label = 'Add / Manage Contacts' and fieldtype = 'Button' and parent = 'Customer'")
 		sql("delete from `tabField Mapper Detail` where parent = 'Sales Order-Delivery Note' and from_field = 'note' and to_field = 'note'")
 	elif patch_no == 152:
-		import_from_files(record_list=[['crm','doctype','sales_order'], ['material_management','doctype','delivery_note'], ['crm','doctype','customer'], ['crm','doctype','shipping_address'], ['mapper', 'DocType Mapper', 'Sales Order-Delivery Note']])
+		import_from_files(record_list=[['selling','doctype','sales_order'], ['stock','doctype','delivery_note'], ['selling','doctype','customer'], ['selling','doctype','shipping_address'], ['mapper', 'DocType Mapper', 'Sales Order-Delivery Note']])
 	elif patch_no == 153:
 		sql("delete from `tabDocField` where fieldname = 'sales_person' and parent = 'Customer'")
 	elif patch_no == 154:
-		import_from_files(record_list=[['material_management','doctype','serial_no'], ['maintenance','doctype','customer_issue']])
+		import_from_files(record_list=[['stock','doctype','serial_no'], ['support','doctype','customer_issue']])
 	elif patch_no == 155:
 		for d in sql("select name, item_code from `tabSerial No`"):
 			sql("COMMIT")
@@ -708,16 +702,16 @@
 		sql("update tabDocType set autoname = 'field:batch_id' where name = 'Batch'")
 		sql("update tabDocField set no_copy = 1 where parent = 'Batch' and fieldname = 'batch_id'")
 	elif patch_no == 162:
-		import_from_files(record_list=[['crm', 'search_criteria', 'sales_order_pending_items1']])
+		import_from_files(record_list=[['selling', 'search_criteria', 'sales_order_pending_items1']])
 	elif patch_no == 163:
 		sql("delete from `tabModule Def Item` where display_name = 'Sales Orderwise Pending Packing Item Summary' and parent = 'CRM'")
-		import_from_files(record_list=[['crm', 'search_criteria', 'sales_orderwise_pending_qty_to_deliver'], ['crm', 'search_criteria', 'sales_orderwise_pending_amount_to_bill'], ['crm', 'search_criteria', 'delivered_items_to_be_install']])
+		import_from_files(record_list=[['selling', 'search_criteria', 'sales_orderwise_pending_qty_to_deliver'], ['selling', 'search_criteria', 'sales_orderwise_pending_amount_to_bill'], ['selling', 'search_criteria', 'delivered_items_to_be_install']])
 	elif patch_no == 164:
-		import_from_files(record_list=[['srm', 'search_criteria', 'pending_po_items_to_receive'], ['srm', 'search_criteria', 'pending_po_items_to_bill']])
+		import_from_files(record_list=[['buying', 'search_criteria', 'pending_po_items_to_receive'], ['buying', 'search_criteria', 'pending_po_items_to_bill']])
 	elif patch_no == 165:
 		pass
 	elif patch_no == 166:
-		import_from_files(record_list=[['srm', 'doctype', 'purchase_order']])
+		import_from_files(record_list=[['buying', 'doctype', 'purchase_order']])
 	elif patch_no == 167:
 		if webnotes.conn.get_value('Control Panel', None, 'account_id') not in ['ax0000956', 'ax0001338']:
 			sql("delete from tabDocField where parent = 'Purchase Order' and fieldname in ('test_certificate_required', 'estimated_cost', 'transport', 'vendor_reference', 'transportation_required', 'mode_of_dispatch', 'octroi')")
@@ -728,7 +722,7 @@
 	elif patch_no == 170:
 		import_from_files(record_list=[['mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher']])
 	elif patch_no == 171:
-		import_from_files(record_list=[['srm', 'doctype', 'supplier']])
+		import_from_files(record_list=[['buying', 'doctype', 'supplier']])
 	elif patch_no == 172:
 		import webnotes
 		webnotes.conn.set_global("system_message", """<b>Welcome to the new financial year 2011-2012 !!! </b><br><br> So obvious question in your mind is how to start Entries in the New Fiscal Year in ERPNext? What are the changes you have to make in the system? <br>We have made some guidelines regarding the basic steps you should follow. Please click on link <a href='http://erpnext.blogspot.com/2011/03/how-to-start-entries-in-new-fiscal-year.html'>How to start Entries in the New Fiscal Year in ERPNext?</a>""")
@@ -750,7 +744,7 @@
 		sql("delete from `tabDocField` where label = 'Next Steps' and parent = 'Purchase Order'")
 		sql("update tabDocField set options = 'Material Issue\nMaterial Receipt\nMaterial Transfer\nSales Return\nPurchase Return\nSubcontracting\nProduction Order' where parent = 'Stock Entry' and fieldname = 'purpose'")
 	elif patch_no == 178:
-		import_from_files(record_list = [['payroll', 'doctype', 'salary_slip']])
+		import_from_files(record_list = [['hr', 'doctype', 'salary_slip']])
 	elif patch_no == 179:
 		from webnotes.utils import get_defaults
 		sl = sql("select name, net_pay from `tabSalary Slip`")
@@ -793,21 +787,21 @@
 	elif patch_no == 187:
 		sql("update tabDocType set autoname = '' where name = 'QA Inspection Report'")
 	elif patch_no == 188:
-		import_from_files(record_list = [['srm', 'doctype', 'qa_inspection_report']])
+		import_from_files(record_list = [['buying', 'doctype', 'qa_inspection_report']])
 	elif patch_no == 189:
 		sql("update `tabDocField` set allow_on_submit = 1 where fieldname in ('entries', 'other_charges') and parent = 'Receivable Voucher'")
 	elif patch_no == 190:
 		sql("update tabDocField set permlevel=0 where fieldname = 'fiscal_year' and parent = 'Stock Entry'")
 	elif patch_no == 191:
-		import_from_files(record_list = [['maintenance', 'doctype', 'customer_issue']])
+		import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
 	elif patch_no == 192:
 		sql("delete from `tabModule Def Item` where parent = 'Material Management' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
-		import_from_files(record_list = [['srm', 'Module Def', 'SRM']])
+		import_from_files(record_list = [['buying', 'Module Def', 'SRM']])
 	elif patch_no == 193:
 		sql("update tabDocField set fieldtype='Button', `trigger`='Client' where parent='Letter Head' and fieldname='set_from_image'")
 	elif patch_no == 194:
 		sql("delete from `tabModule Def Item` where parent = 'SRM' and doc_name = 'Landed Cost Wizard' and display_name = 'Landed Cost Wizard'")
-		import_from_files(record_list = [['material_management', 'Module Def', 'Material Management']])
+		import_from_files(record_list = [['stock', 'Module Def', 'Material Management']])
 	elif patch_no == 195:
 		from webnotes.modules.module_manager import reload_doc
 		reload_doc('setup','doctype','manage_account')
@@ -815,7 +809,7 @@
 		sql("update `tabModule Def` set module_page = null where name = 'Material Management'")
 	elif patch_no == 197:
 		sql("update `tabDocField` set permlevel = 0, in_filter = 1 where fieldname = 'warranty_amc_status' and parent = 'Customer Issue'")
-		import_from_files(record_list = [['maintenance', 'doctype', 'customer_issue']])
+		import_from_files(record_list = [['support', 'doctype', 'customer_issue']])
 	elif patch_no == 198:
 		sql("delete from `tabDocField` where (label in ('SMS', 'Send SMS') or fieldname in ('message', 'customer_mobile_no')) and parent in ('Quoattion', 'Sales Order', 'Delivery Note', 'Receivable Voucher')")
 		sql("delete from `tabDocField` where label in ('SMS', 'Send SMS') and parent = 'Purchase Order'")
@@ -843,7 +837,7 @@
 	elif patch_no == 205:
 		sql("update `tabDocField` set `default` = '' where fieldname = 'naming_series' and parent = 'Installation Note'")
 	elif patch_no == 206:
-		reload_doc('crm','doctype','installation_note')
+		reload_doc('selling','doctype','installation_note')
 	elif patch_no == 207:
 		import_from_files(record_list = [['setup', 'doctype', 'company']])
 	elif patch_no == 208:
@@ -858,17 +852,17 @@
 		# reload company because of disturbed UI
 		import_from_files(record_list = [['setup', 'doctype', 'company']])
 	elif patch_no == 213:
-		reload_doc('crm','doctype','lead')
+		reload_doc('selling','doctype','lead')
 		reload_doc('setup','doctype','company')
 	elif patch_no == 214:
-		reload_doc('crm','doctype','sales_order')
+		reload_doc('selling','doctype','sales_order')
 	elif patch_no == 215:
 		# patch for item and image in description
 		sql("update tabDocField set width = '300px' where fieldname='description'")
-		reload_doc('material_management', 'doctype', 'item')
+		reload_doc('stock', 'doctype', 'item')
 		sql("delete from __DocTypeCache")
 	elif patch_no == 216:
-		import_from_files(record_list = [['material_management', 'doctype', 'serial_no'], ['material_management', 'doctype', 'stock_ledger_entry']])
+		import_from_files(record_list = [['stock', 'doctype', 'serial_no'], ['stock', 'doctype', 'stock_ledger_entry']])
 	elif patch_no == 217:
 		sql("update tabDocField set options = '\nIn Store\nDelivered\nNot in Use' where fieldname = 'status' and parent = 'Serial No'")
 		sql("update tabDocField set no_copy = 1 where fieldname = 'serial_no' and parent = 'Delivery Note Detail'")
@@ -902,13 +896,13 @@
 		sql("update tabDocField set hidden = 0 where fieldname in ('pay_to_recd_from', 'total_amount', 'total_amount_in_words') and parent = 'Journal Voucher'")
 		sql("update tabDocField set permlevel = 0 where fieldname = 'pay_to_recd_from' and parent = 'Journal Voucher'")
 	elif patch_no == 224:
-		import_from_files(record_list = [['material_management', 'doctype', 'delivery_note_packing_detail'], ['accounts', 'Print Format', 'Payment Receipt Voucher']])
+		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail'], ['accounts', 'Print Format', 'Payment Receipt Voucher']])
 	elif patch_no == 225:
-		import_from_files(record_list = [['material_management', 'doctype', 'delivery_note_packing_detail']])
+		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
 	elif patch_no == 226:
-		import_from_files(record_list = [['material_management', 'doctype', 'delivery_note_packing_detail']])
+		import_from_files(record_list = [['stock', 'doctype', 'delivery_note_packing_detail']])
 	elif patch_no == 227:
-		reload_doc('material_management', 'doctype', 'item')
+		reload_doc('stock', 'doctype', 'item')
 		if webnotes.conn.get_value('Control Panel', None, 'account_id') != 'axjanak2011':
 			sql("delete from tabDocField where parent = 'Item' and fieldname='alternate_description' limit 1")
 	elif patch_no == 228:
@@ -918,11 +912,11 @@
 		reload_doc('knowledge_base', 'page', 'questions')
 		reload_doc('knowledge_base', 'Module Def', 'Knowledge Base')
 		sql("update `tabModule Def` set disabled='No' where name='Knowledge Base'")
-	elif patch_no == 229:		
+	elif patch_no == 229:
 		reload_doc('knowledge_base', 'page', 'question_view')
 	elif patch_no == 230:
-		reload_doc('srm', 'doctype', 'indent')
-		reload_doc('srm', 'doctype', 'indent_detail')
+		reload_doc('buying', 'doctype', 'indent')
+		reload_doc('buying', 'doctype', 'indent_detail')
 		reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
 	elif patch_no == 231:
 		reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Indent')
@@ -934,7 +928,7 @@
 	elif patch_no == 234:
 		sql("update `tabTable Mapper Detail` set validation_logic = 'docstatus=1' where parent = 'Sales Order-Indent' and from_table = 'Sales Order Detail'")
 	elif patch_no == 235:
-		for sc in sql("""select name from `tabSearch Criteria` where ifnull(name,'') 
+		for sc in sql("""select name from `tabSearch Criteria` where ifnull(name,'')
 			like 'srch%' or ifnull(name,'') like '%stdsrch'"""):
 			try:
 				get_obj('Search Criteria', sc[0]).rename()
@@ -952,12 +946,12 @@
 	elif patch_no == 239:
 		reload_doc('core', 'doctype', 'docfield')
 		reload_doc('core', 'doctype', 'doctype')
-		
-		from patches.feed_patch import set_subjects_and_tagfields
+		from patches.old_patches.feed_patch import set_subjects_and_tagfields
+
 		set_subjects_and_tagfields()
 	elif patch_no == 240:
 		# again for sales order (status)
-		from patches.feed_patch import set_subjects_and_tagfields
+		from patches.old_patches.feed_patch import set_subjects_and_tagfields
 		set_subjects_and_tagfields()
 	elif patch_no == 241:
 		sql("update `tabDocField` set fieldtype = 'Text', options = '', in_filter = '' where fieldname = 'serial_no' and parent = 'Stock Ledger Entry'")
@@ -976,12 +970,12 @@
 		webnotes.conn.set_value('DocType', 'Custom Field', 'module', 'Core')
 		reload_doc('setup', 'doctype', 'company')
 	elif patch_no == 244:
-		reload_doc('material_management', 'search_criteria', 'shortage_to_indent')
+		reload_doc('stock', 'search_criteria', 'shortage_to_indent')
 	elif patch_no == 245:
-		from patches.doctype_permission_patch import set_doctype_permissions
+		from patches.old_patches.doctype_permission_patch import set_doctype_permissions
 		set_doctype_permissions()
 
-		from patches.feed_patch import set_subjects_and_tagfields
+		from patches.old_patches.feed_patch import set_subjects_and_tagfields
 		set_subjects_and_tagfields()
 	elif patch_no == 246:
 		webnotes.conn.set_value('DocType','Stock Entry','tag_fields','purpose')
@@ -993,16 +987,16 @@
 	elif patch_no == 249:
 		sql("update `tabDocPerm` t1, `tabDocType` t2 set t1.role = 'System Manager' where t1.role = 'Administrator' and t1.parent = t2.name and t2.module != 'Core'")
 	elif patch_no == 250:
-		from patches.feed_patch  import support_patch
+		from patches.old_patches.feed_patch  import support_patch
 		support_patch()
 	elif patch_no == 251:
 		from webnotes.model import db_schema
 		db_schema.remove_all_foreign_keys()
-		from patches.customer_address import run_patch
+		from patches.old_patches.customer_address import run_patch
 		run_patch()
 	elif patch_no == 252:
-		reload_doc('maintenance','doctype','support_ticket')
-		reload_doc('maintenance','doctype','support_ticket_response')
+		reload_doc('support','doctype','support_ticket')
+		reload_doc('support','doctype','support_ticket_response')
 	elif patch_no == 253:
 		reload_doc('accounts','doctype','ledger_balance_export')
 		reload_doc('accounts','doctype','ledger_detail')
@@ -1012,22 +1006,22 @@
 		updatedb('Ledger Balance Export')
 		updatedb('Ledger Detail')
 	elif patch_no == 254:
-		reload_doc('settings', 'doctype', 'sms_settings')
-		reload_doc('settings', 'doctype', 'static_parameter_detail')
+		reload_doc('setup', 'doctype', 'sms_settings')
+		reload_doc('setup', 'doctype', 'static_parameter_detail')
 
 		from webnotes.model.db_schema import updatedb
 		updatedb('SMS Settings')
 		updatedb('Static Parameter Detail')
 	elif patch_no == 255:
-		from patches.customer_address import run_old_data_sync_patch
+		from patches.old_patches.customer_address import run_old_data_sync_patch
 		run_old_data_sync_patch()
 	elif patch_no == 256:
 		sql("update `tabLetter Head` set content = replace(content, 'http://46.4.50.84/v170-test/', '')")
 		sql("update `tabSingles` set value = replace(value, 'http://46.4.50.84/v170-test/', '') where field in ('letter_head', 'client_name') and doctype = 'Control Panel'")
 		sql("update `tabItem` set description_html = replace(description_html, 'http://46.4.50.84/v170-test/', '')")
 	elif patch_no == 257:
-		from patches.customer_address import run_old_data_sync_patch
-		run_old_data_sync_patch()	
+		from patches.old_patches.customer_address import run_old_data_sync_patch
+		run_old_data_sync_patch()
 	elif patch_no == 258:
 		sql("update tabDocField set `default`=NULL where fieldname = 'naming_series'")
 	elif patch_no == 259:
@@ -1046,12 +1040,12 @@
 	elif patch_no == 261:
 		sql("update `tabPrint Format` set html = replace(html, 'customer_address', 'address_display')")
 	elif patch_no == 262:
-		from patches.customer_address import sync_lead_phone
+		from patches.old_patches.customer_address import sync_lead_phone
 		sync_lead_phone()
 	elif patch_no == 263:
 		ol = ['','Open','To Reply','Waiting for Customer','Hold','Closed']
 		sql("update tabDocField set options=%s where parent=%s and fieldname=%s", ('\n'.join(ol), 'Support Ticket', 'status'))
-	elif patch_no == 264:	
+	elif patch_no == 264:
 		sql("delete from tabDocField where parent = 'Customer Issue' and (fieldname = 'issue_in' or fieldname = 'issue_category')")
 		sql("update tabDocField set options=NULL where parent='Support Ticket' and label = 'Send'")
 	elif patch_no == 266:
@@ -1075,15 +1069,15 @@
 			except: pass
 	elif patch_no == 271:
 		# tags patch
-		reload_doc('crm','doctype','sales_order')
-		reload_doc('material_management','doctype','delivery_note')
+		reload_doc('selling','doctype','sales_order')
+		reload_doc('stock','doctype','delivery_note')
 		sql("delete from tabDocField where fieldname='per_amt_billed' and parent in ('Sales Order', 'Delivery Note')")
-		
-		sql("""update `tabSales Order` set delivery_status = if(ifnull(per_delivered,0) < 0.001, 'Not Delivered', 
+
+		sql("""update `tabSales Order` set delivery_status = if(ifnull(per_delivered,0) < 0.001, 'Not Delivered',
 				if(per_delivered >= 99.99, 'Fully Delivered', 'Partly Delivered'))""")
-		sql("""update `tabSales Order` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed', 
+		sql("""update `tabSales Order` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
 				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
-		sql("""update `tabDelivery Note` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed', 
+		sql("""update `tabDelivery Note` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
 				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
 	elif patch_no == 272:
 		from webnotes.model import delete_doc
@@ -1097,7 +1091,7 @@
 		sn = sql("select name from `tabSearch Criteria` where criteria_name = 'Sales Personwise Transaction Summary'")
 		for d in sn:
 			delete_doc('Search Criteria', d[0])
-		reload_doc('crm', 'search_criteria', 'sales_personwise_transaction_summary')
+		reload_doc('selling', 'search_criteria', 'sales_personwise_transaction_summary')
 	elif patch_no == 277:
 		webnotes.model.delete_doc('DocType','HomePage Settings')
 		webnotes.model.delete_doc('DocType','Badge Settings')
@@ -1117,7 +1111,7 @@
 			rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tab%s` where modified >= '2011-06-15 01:00:00' group by voucher_no" % t)
 			for d in rec:
 				sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
-			
+
 		other_dt = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note']
 		for dt in other_dt:
 			rec = sql("select name, status from `tab%s` where modified >= '2011-06-15 01:00:00'" % dt)
@@ -1141,7 +1135,7 @@
 		for d in rec:
 			sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
 	elif patch_no == 284:
-		reload_doc('maintenance', 'doctype', 'support_ticket')
+		reload_doc('support', 'doctype', 'support_ticket')
 		sql("update `tabDocField` set in_filter = 1 where fieldname in ('raised_by', 'subject') and parent = 'Support Ticket'")
 	elif patch_no == 286:
 		reload_doc('accounts', 'search_criteria', 'itemwise_sales_register')
@@ -1152,9 +1146,9 @@
 		reload_doc('accounts', 'doctype', 'payable_voucher')
 	elif patch_no == 289:
 		sql("update `tabDocType` set subject = 'From %(supplier_name)s worth %(grand_total)s due on %(due_date)s | %(outstanding_amount)s outstanding' where name = 'Payable Voucher'")
-		sql("update `tabDocType` set search_fields = 'status,transaction_date,customer,lead,order_type' where name = 'Quotation'")		
+		sql("update `tabDocType` set search_fields = 'status,transaction_date,customer,lead,order_type' where name = 'Quotation'")
 	elif patch_no == 290:
-		count = sql("""SELECT * FROM  `tabModule Def` 
+		count = sql("""SELECT * FROM  `tabModule Def`
 			   WHERE `module_name` LIKE 'Home'""")
 		if not count:
 			md = Document('Module Def')
@@ -1162,7 +1156,7 @@
 			md.module_label = 'Home'
 			md.save(1)
 	elif patch_no == 291:
-		reload_doc('tools','doctype','rename_tool')
+		reload_doc('utilities','doctype','rename_tool')
 	elif patch_no == 292:
 		reload_doc('accounts', 'search_criteria', 'trial_balance')
 	elif patch_no == 293:
@@ -1179,14 +1173,14 @@
 		sql("update `tabDocField` set options = 'Billed\nNot Billed\nPartly Billed\nClosed' where parent = 'Sales Order' and fieldname = 'billing_status'")
 	elif patch_no == 296:
 		sql("delete from tabDocField where parent='Support Ticket' and fieldname='contact_no'")
-		reload_doc('maintenance', 'doctype', 'support_ticket')
+		reload_doc('support', 'doctype', 'support_ticket')
 	elif patch_no == 297:
-		reload_doc('payroll', 'doctype', 'employee')
-		reload_doc('payroll', 'doctype', 'attendance')
-		reload_doc('payroll', 'doctype', 'expense_voucher')
-		reload_doc('payroll', 'doctype', 'appraisal')
-		reload_doc('payroll', 'doctype', 'salary_structure')
-		reload_doc('payroll', 'doctype', 'salary_slip')
+		reload_doc('hr', 'doctype', 'employee')
+		reload_doc('hr', 'doctype', 'attendance')
+		reload_doc('hr', 'doctype', 'expense_voucher')
+		reload_doc('hr', 'doctype', 'appraisal')
+		reload_doc('hr', 'doctype', 'salary_structure')
+		reload_doc('hr', 'doctype', 'salary_slip')
 	elif patch_no == 298:
 		sql("update `tabDocField` set options = 'link:Company' where parent = 'Attendance' and fieldname = 'company'")
 		sql("update `tabDocField` set options = 'link:Company' where parent = 'Expense Voucher' and fieldname = 'company'")
@@ -1213,7 +1207,7 @@
 		sql("update `tabDocField` set options = 'link:Item' where parent = 'Raw Materials Supplied' and fieldname = 'po_item'")
 		sql("update `tabDocField` set options = 'Sales Order' where parent = 'Indent Detail' and fieldname = 'sales_order_no'")
 		sql("update `tabDocField` set options = 'link:Company', fieldtype = 'Select' where parent = 'Stock Ledger Entry' and fieldname = 'company'")
-		reload_doc('tools', 'doctype', 'rename_tool')
+		reload_doc('utilities', 'doctype', 'rename_tool')
 	elif patch_no == 307:
 		sql("delete from `tabDocField` where parent = 'company' and label = 'Trash Company' and fieldtype = 'Button'")
 		reload_doc('setup', 'doctype', 'company')
@@ -1237,14 +1231,14 @@
 			rec = sql("select voucher_type, voucher_no, ifnull(is_cancelled, 'No') from `tab%s` where modified >= '2011-07-06 10:00:00' group by voucher_no" % t)
 			for d in rec:
 				sql("update `tab%s` set docstatus = %s where name = '%s'" % (d[0], d[2]=='No' and 1 or 2, d[1]))
-			
+
 		other_dt = ['Enquiry', 'Quotation', 'Sales Order', 'Indent', 'Purchase Order', 'Production Order', 'Customer Issue', 'Installation Note']
 		for dt in other_dt:
 			rec = sql("select name, status from `tab%s` where modified >= '2011-07-06 10:00:00'" % dt)
 			for r in rec:
 				sql("update `tab%s` set docstatus = %s where name = '%s'" % (dt, (r[1] in ['Submitted', 'Closed'] and 1 or r[1]=='Cancelled' and 2 or 0), r[0]))
-				
-				
+
+
 		dt_list = ['Delivery Note', 'Purchase Receipt']
 		for dt in dt_list:
 			sql("update `tab%s` set status = 'Submitted' where docstatus = 1 and modified >='2011-07-06 10:00:00'" % dt)
@@ -1255,7 +1249,7 @@
 			tbl = sql("select options from `tabDocField` where fieldtype = 'Table' and parent = '%s'" % d)
 			for t in tbl:
 				sql("update `tab%s` t1, `tab%s` t2 set t1.docstatus = t2.docstatus where t1.parent = t2.name" % (t[0], d))
-				
+
 	elif patch_no == 314:
 		# delete double feed
 		sql("delete from tabFeed where subject like 'New %'")
@@ -1274,7 +1268,7 @@
 	elif patch_no == 316:
 		pass
 	elif patch_no == 317:
-		sql("update `tabPage` set name = 'profile-settings' where page_name = 'Profile Settings'")	
+		sql("update `tabPage` set name = 'profile-settings' where page_name = 'Profile Settings'")
 	elif patch_no == 318:
 		reload_doc('utilities', 'doctype', 'bulk_rename_tool')
 	elif patch_no == 319:
@@ -1294,3 +1288,122 @@
 	elif patch_no == 325:
 		sql("update `tabDocField` set fieldtype = 'Data' where parent = 'Salary Slip' and fieldname = 'total_days_in_month'")
 		reload_doc('hr', 'doctype', 'salary_slip')
+	elif patch_no == 326:
+		# load the new billing page
+		if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+			reload_doc('server_tools','page','billing')
+	elif patch_no == 327:
+		# patch for support email settings now moved to email settings
+		reload_doc('setup','doctype','email_settings')
+
+		# map fields from support to email settings
+		field_map = {
+			'support_email': 'email',
+			'support_host':'host',
+			'support_username': 'username',
+			'support_password': 'password',
+			'support_use_ssl': 'use_ssl',
+			'sync_support_mails': 'integrate_incoming',
+			'signature': 'support_signature'
+		}
+
+		for key in field_map:
+			webnotes.conn.set_value('Email Settings',None,key, \
+				webnotes.conn.get_value('Support Email Settings',None,field_map[key]))
+
+		# delete support email settings
+		from webnotes.model import delete_doc
+		delete_doc('DocType', 'Support Email Settings')
+
+		reload_doc('support','doctype','support_ticket')
+		sql("delete from tabDocField where fieldname='problem_description' and parent='Support Ticket'")
+	elif patch_no == 328:
+		if webnotes.conn.get_value('Control Panel', None, 'account_id') != 'axjanak2011':
+			sql("delete from `tabDocField` where fieldname = 'supplier_status' and parent = 'Supplier'")
+	elif patch_no == 329:
+		reload_doc('utilities', 'doctype', 'rename_tool')
+		reload_doc('utilities', 'doctype', 'bulk_rename_tool')
+	elif patch_no == 330:
+		reload_doc('accounts', 'doctype', 'lease_agreement')
+		reload_doc('accounts', 'doctype', 'lease_installment')
+
+		reload_doc('accounts', 'search_criteria', 'lease_agreement_list')
+		reload_doc('accounts', 'search_criteria', 'lease_monthly_future_installment_inflows')
+		reload_doc('accounts', 'search_criteria', 'lease_overdue_age_wise')
+		reload_doc('accounts', 'search_criteria', 'lease_over_due_list')
+		reload_doc('accounts', 'search_criteria', 'lease_receipts_client_wise')
+		reload_doc('accounts', 'search_criteria', 'lease_receipt_summary_year_to_date')
+		reload_doc('accounts', 'search_criteria', 'lease_yearly_future_installment_inflows')
+
+		reload_doc('accounts', 'Module Def', 'Accounts')
+	elif patch_no == 331:
+		p = get_obj('Patch Util')
+		# permission
+		p.add_permission('Lease Agreement', 'Accounts Manager', 0, read = 1, write=1,submit=1, cancel=1,amend=1)
+		p.add_permission('Lease Agreement', 'Accounts Manager', 1, read = 1)
+	elif patch_no == 332:
+		sql("update `tabDocField` set permlevel=1, hidden = 1 where parent = 'Bulk Rename Tool' and fieldname = 'file_list'")
+	elif patch_no == 333:
+		sql("update `tabDocPerm` set `create`  =1 where role = 'Accounts Manager' and parent = 'Lease Agreement'")
+
+		p = get_obj('Patch Util')
+		p.add_permission('DocType Mapper', 'System Manager', 0, read = 1, write=1, create=1)
+		p.add_permission('Role', 'System Manager', 0, read = 1, write=1, create=1)
+		p.add_permission('Print Format', 'System Manager', 0, read = 1, write=1, create=1)
+	elif patch_no == 334:
+		reload_doc('knowledge_base', 'doctype', 'answer')
+	elif patch_no == 335:
+		for dt in ['Account', 'Cost Center', 'Territory', 'Item Group', 'Customer Group']:
+			sql("update `tabDocField` set fieldtype = 'Link', options = %s where fieldname = 'old_parent' and parent = %s", (dt, dt))
+	elif patch_no == 336:
+		reload_doc('server_tools','page','billing')
+	elif patch_no == 337:
+		item_list = webnotes.conn.sql("""SELECT name, description_html
+									FROM tabItem""")
+		if item_list:
+			for item, html in item_list:
+				if html and "getfile" in html and "acx" in html:
+					ac_id = webnotes.conn.sql("""SELECT value FROM `tabSingles` WHERE doctype='Control Panel' AND field='account_id'""")
+					sp_acx = html.split("acx=")
+					l_acx = len(sp_acx)
+					if l_acx > 1:
+						for i in range(l_acx-1):
+							sp_quot = sp_acx[i+1].split('"')
+							if len(sp_quot) > 1: sp_quot[0] = str(ac_id[0][0])
+							sp_acx[i+1] = '"'.join(sp_quot)
+					html = "acx=".join(sp_acx)
+					webnotes.conn.sql("""UPDATE tabItem SET description_html=%s WHERE name=%s""", (html, item))
+	elif patch_no == 338:
+		# Patch for billing status based on amount
+		# reload so and dn
+		reload_doc('selling','doctype','sales_order')
+		reload_doc('stock','doctype','delivery_note')
+
+		# delete billed_qty field
+		sql("delete from `tabDocField` where fieldname = 'billed_qty' and parent in ('Sales Order Detail', 'Delivery Note Detail')")
+
+		# update billed amt in item table in so and dn
+		sql("""	update `tabSales Order Detail` so
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `so_detail`= so.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		sql(""" update `tabDelivery Note Detail` dn
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `dn_detail`= dn.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		# calculate % billed based on item table
+		sql("""	update `tabSales Order` so
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabSales Order Detail` where parent = so.name), modified = now()""")
+
+		sql("""	update `tabDelivery Note` dn
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabDelivery Note Detail` where parent = dn.name), modified = now()""")
+
+		# update billing status based on % billed
+		sql("""update `tabSales Order` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+		sql("""update `tabDelivery Note` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+
+		# update name of questions page
+		sql("update tabPage set name='questions' where name='Questions'")
+		sql("update tabPage set name='question-view' where name='Question View'")
+	elif patch_no == 339
+		reload_doc('production','doctype','bill_of_materials')
diff --git a/production/doctype/bill_of_materials/bill_of_materials.py b/production/doctype/bill_of_materials/bill_of_materials.py
index c7bb8df..d7d3db5 100644
--- a/production/doctype/bill_of_materials/bill_of_materials.py
+++ b/production/doctype/bill_of_materials/bill_of_materials.py
@@ -36,7 +36,7 @@
     ret={
       'description'   : item and item[0]['description'] or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_workstation_details(self,workstation):
     ws = sql("select hour_rate, capacity from `tabWorkstation` where name = %s",workstation , as_dict = 1)
@@ -44,7 +44,7 @@
       'hour_rate'            : ws and flt(ws[0]['hour_rate']) or '',
       'workstation_capacity' : ws and flt(ws[0]['capacity']) or ''
     }
-    return cstr(ret)
+    return ret
 
   def get_bom_material_detail(self, arg):
     arg = eval(arg)
diff --git a/production/doctype/bill_of_materials/bill_of_materials.txt b/production/doctype/bill_of_materials/bill_of_materials.txt
index 4e788d7..2590817 100644
--- a/production/doctype/bill_of_materials/bill_of_materials.txt
+++ b/production/doctype/bill_of_materials/bill_of_materials.txt
@@ -12,6 +12,7 @@
 
 	# These values are common for all DocType
 	{
+		'_last_update': '1309508837',
 		'allow_attach': 0,
 		'allow_copy': 0,
 		'allow_email': 0,
@@ -33,7 +34,7 @@
 		'section_style': 'Tabbed',
 		'server_code_error': ' ',
 		'show_in_menu': 0,
-		'subject': '%(item_code)s',
+		'subject': '%(item)s',
 		'version': 170
 	},
 
diff --git a/production/doctype/bom_operation/bom_operation.txt b/production/doctype/bom_operation/bom_operation.txt
index 873faec..9bc7f9e 100644
--- a/production/doctype/bom_operation/bom_operation.txt
+++ b/production/doctype/bom_operation/bom_operation.txt
@@ -114,6 +114,7 @@
 		'options': 'Workstation',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
diff --git a/production/doctype/bom_replace_utility_detail/bom_replace_utility_detail.txt b/production/doctype/bom_replace_utility_detail/bom_replace_utility_detail.txt
index ab18e44..d36f26b 100644
--- a/production/doctype/bom_replace_utility_detail/bom_replace_utility_detail.txt
+++ b/production/doctype/bom_replace_utility_detail/bom_replace_utility_detail.txt
@@ -99,6 +99,7 @@
 		'oldfieldname': 'bom_created',
 		'oldfieldtype': 'Link',
 		'options': 'Bill Of Materials',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/production/doctype/flat_bom_detail/flat_bom_detail.txt b/production/doctype/flat_bom_detail/flat_bom_detail.txt
index 4b8812b..7339300 100644
--- a/production/doctype/flat_bom_detail/flat_bom_detail.txt
+++ b/production/doctype/flat_bom_detail/flat_bom_detail.txt
@@ -162,7 +162,8 @@
 		'label': 'Stock UOM',
 		'oldfieldname': 'stock_uom',
 		'oldfieldtype': 'Link',
-		'options': 'UOM'
+		'options': 'UOM',
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/production/doctype/pp_detail/pp_detail.txt b/production/doctype/pp_detail/pp_detail.txt
index 61a34bd..482fae2 100644
--- a/production/doctype/pp_detail/pp_detail.txt
+++ b/production/doctype/pp_detail/pp_detail.txt
@@ -131,7 +131,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -146,6 +146,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Bill Of Materials',
 		'permlevel': 0,
+		'search_index': 0,
 		'width': '100px'
 	},
 
diff --git a/production/doctype/production_order/production_order.txt b/production/doctype/production_order/production_order.txt
index 7df6397..c927edf 100644
--- a/production/doctype/production_order/production_order.txt
+++ b/production/doctype/production_order/production_order.txt
@@ -180,6 +180,7 @@
 		'options': 'Bill Of Materials',
 		'permlevel': 1,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -306,7 +307,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Warehouse',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -323,7 +325,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Warehouse',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -367,7 +370,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Company',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/production/doctype/production_planning_tool/production_planning_tool.py b/production/doctype/production_planning_tool/production_planning_tool.py
index c548173..d0ae05b 100644
--- a/production/doctype/production_planning_tool/production_planning_tool.py
+++ b/production/doctype/production_planning_tool/production_planning_tool.py
@@ -32,7 +32,7 @@
              'stock_uom'   : item and item[0]['stock_uom'],
              'bom_no'      : item and item[0]['default_bom']
       }
-      return cstr(ret)
+      return ret
     else:
       msgprint("Item %s does not exist in system." %(args['item_code']))
       raise Exception
diff --git a/production/doctype/update_delivery_date_detail/update_delivery_date_detail.txt b/production/doctype/update_delivery_date_detail/update_delivery_date_detail.txt
index f8499ce..646a97e 100644
--- a/production/doctype/update_delivery_date_detail/update_delivery_date_detail.txt
+++ b/production/doctype/update_delivery_date_detail/update_delivery_date_detail.txt
@@ -86,7 +86,8 @@
 		'oldfieldname': 'state',
 		'oldfieldtype': 'Link',
 		'options': 'State',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -100,7 +101,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Territory',
 		'permlevel': 1,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/production/doctype/workstation/workstation.py b/production/doctype/workstation/workstation.py
index aaa4908..45851de 100644
--- a/production/doctype/workstation/workstation.py
+++ b/production/doctype/workstation/workstation.py
@@ -25,7 +25,7 @@
   def update_bom_operation(self):
       bom_list = sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
       for bom_no in bom_list:
-        sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no, self.doc.name))
+        sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
   
   def on_update(self):
     set(self.doc, 'overhead', flt(self.doc.hour_rate_electricity) + flt(self.doc.hour_rate_consumable) + flt(self.doc.hour_rate_rent))
diff --git a/projects/doctype/project/project.py b/projects/doctype/project/project.py
index e68771c..084df6c 100644
--- a/projects/doctype/project/project.py
+++ b/projects/doctype/project/project.py
@@ -38,7 +38,7 @@
       ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
       ret['contact_no'] = contact_det and contact_det[0]['contact_no'] or ''
       ret['email_id'] = contact_det and contact_det[0]['email_id'] or ''    
-      return cstr(ret)
+      return ret
     else:
       msgprint("Customer : %s does not exist in system." % (self.doc.customer))
       raise Exception  
@@ -65,7 +65,7 @@
     #if pft > 0:
     per_pft = (flt(pft) / flt(self.doc.project_value)) * 100
     ret = {'gross_margin_value': pft, 'per_gross_margin': per_pft}
-    return cstr(ret)
+    return ret
     
   # validate
   #================================================
diff --git a/projects/doctype/project/project.txt b/projects/doctype/project/project.txt
index b144246..3d57e12 100644
--- a/projects/doctype/project/project.txt
+++ b/projects/doctype/project/project.txt
@@ -94,7 +94,8 @@
 		'oldfieldname': 'project_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
@@ -112,7 +113,7 @@
 		'options': 'Open\nCompleted\nCancelled',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -356,7 +357,7 @@
 		'oldfieldname': 'customer_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -401,6 +402,7 @@
 		'options': 'Territory',
 		'permlevel': 0,
 		'reqd': 0,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -438,7 +440,8 @@
 		'oldfieldname': 'customer_group',
 		'oldfieldtype': 'Link',
 		'options': 'Customer Group',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/projects/doctype/ticket/ticket.py b/projects/doctype/ticket/ticket.py
index 8d716cc..0f18b21 100644
--- a/projects/doctype/ticket/ticket.py
+++ b/projects/doctype/ticket/ticket.py
@@ -22,18 +22,18 @@
     cust = sql("select customer, customer_name from `tabProject` where name = %s", self.doc.project)
     if cust:
       ret = {'customer': cust and cust[0][0] or '', 'customer_name': cust and cust[0][1] or ''}
-      return cstr(ret)
+      return ret
   
   def get_customer_details(self):
     cust = sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
     if cust:
       ret = {'customer_name': cust and cust[0][0] or ''}
-      return cstr(ret)
+      return ret
   
   def get_allocated_to_name(self):
     as_em = sql("select first_name, last_name from `tabProfile` where name=%s",self.doc.allocated_to)
     ret = { 'allocated_to_name' : as_em and (as_em[0][0] + ' ' + as_em[0][1]) or ''}
-    return cstr(ret)
+    return ret
 
   # validate
   #--------------------------------------------   
diff --git a/projects/doctype/timesheet/timesheet.py b/projects/doctype/timesheet/timesheet.py
index ba921f4..f07975c 100644
--- a/projects/doctype/timesheet/timesheet.py
+++ b/projects/doctype/timesheet/timesheet.py
@@ -32,7 +32,7 @@
     tsk = sql("select name, project, customer, customer_name from `tabTicket` where subject = %s", task_sub)
     if tsk:
       ret = {'task_id': tsk and tsk[0][0] or '', 'project_name': tsk and tsk[0][1] or '', 'customer_name': tsk and tsk[0][3] or ''}
-      return cstr(ret)
+      return ret
   
   def validate(self):
     if getdate(self.doc.timesheet_date) > getdate(nowdate()):
diff --git a/projects/doctype/timesheet/timesheet.txt b/projects/doctype/timesheet/timesheet.txt
index 462b64b..839da19 100644
--- a/projects/doctype/timesheet/timesheet.txt
+++ b/projects/doctype/timesheet/timesheet.txt
@@ -145,7 +145,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Profile',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/projects/doctype/timesheet_detail/timesheet_detail.txt b/projects/doctype/timesheet_detail/timesheet_detail.txt
index a96c14b..0098228 100644
--- a/projects/doctype/timesheet_detail/timesheet_detail.txt
+++ b/projects/doctype/timesheet_detail/timesheet_detail.txt
@@ -75,6 +75,7 @@
 		'options': 'Activity Type',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'width': '200px'
 	},
 
diff --git a/selling/doctype/customer/customer.txt b/selling/doctype/customer/customer.txt
index 364b148..24271ee 100644
--- a/selling/doctype/customer/customer.txt
+++ b/selling/doctype/customer/customer.txt
@@ -5,14 +5,14 @@
 	{
 		'creation': '2010-08-08 17:08:56',
 		'docstatus': 0,
-		'modified': '2011-05-26 17:31:31',
+		'modified': '2011-07-20 10:42:05',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1306834669',
+		'_last_update': '1309508837',
 		'allow_print': 0,
 		'allow_trash': 1,
 		'colour': 'White:FFF',
@@ -26,7 +26,7 @@
 		'show_in_menu': 0,
 		'subject': "eval:'%(customer_name)s'=='%(name)s' ? ' ' : '%(customer_name)s'",
 		'tag_fields': 'customer_group,customer_type',
-		'version': 431
+		'version': 433
 	},
 
 	# These values are common for all DocField
@@ -176,7 +176,7 @@
 		'idx': 4,
 		'label': 'Series',
 		'no_copy': 1,
-		'options': '\nCUST\nCUSTMUM',
+		'options': '\nCUST\nCUSTMUM\nCUSTOM',
 		'permlevel': 0,
 		'print_hide': 0
 	},
@@ -340,7 +340,7 @@
 		'options': 'Company',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/selling/doctype/enquiry/enquiry.py b/selling/doctype/enquiry/enquiry.py
index 61bc4ec..1259702 100644
--- a/selling/doctype/enquiry/enquiry.py
+++ b/selling/doctype/enquiry/enquiry.py
@@ -50,7 +50,7 @@
       ret['contact_no']     = contact_det and contact_det[0]['contact_no'] or ''
       ret['email_id']       = contact_det and contact_det[0]['email_id'] or ''
     
-      return cstr(ret)
+      return ret
     else:
       msgprint("Customer : %s does not exist in system." % (name))
       raise Exception
@@ -64,7 +64,7 @@
       'contact_no' : contact and contact[0]['contact_no'] or '',
       'email_id' : contact and contact[0]['email_id'] or ''
     }
-    return str(ret)   
+    return ret
     
   # ====================================================================================================================
   def on_update(self):
@@ -184,7 +184,7 @@
     else:
       set(self.doc, 'status', 'Enquiry Lost')
       set(self.doc, 'order_lost_reason', arg)
-      return cstr('true')
+      return 'true'
     
   # ====================================================================================================================  
   def update_follow_up(self):
diff --git a/selling/doctype/enquiry/enquiry.txt b/selling/doctype/enquiry/enquiry.txt
index c13ad46..260e077 100644
--- a/selling/doctype/enquiry/enquiry.txt
+++ b/selling/doctype/enquiry/enquiry.txt
@@ -187,7 +187,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -244,6 +244,7 @@
 		'options': 'Lead',
 		'permlevel': 0,
 		'print_hide': 1,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -326,6 +327,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 1,
 		'width': '50px'
 	},
 
@@ -405,7 +407,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -426,7 +428,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -492,7 +494,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -509,7 +511,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/selling/doctype/enquiry_detail/enquiry_detail.txt b/selling/doctype/enquiry_detail/enquiry_detail.txt
index bd9275b..284b436 100644
--- a/selling/doctype/enquiry_detail/enquiry_detail.txt
+++ b/selling/doctype/enquiry_detail/enquiry_detail.txt
@@ -90,7 +90,8 @@
 		'oldfieldname': 'item_group',
 		'oldfieldtype': 'Link',
 		'options': 'Item Group',
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -104,7 +105,8 @@
 		'oldfieldname': 'brand',
 		'oldfieldtype': 'Link',
 		'options': 'Brand',
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -140,6 +142,7 @@
 		'label': 'UOM',
 		'oldfieldname': 'uom',
 		'oldfieldtype': 'Link',
-		'options': 'UOM'
+		'options': 'UOM',
+		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/selling/doctype/installation_note/installation_note.py b/selling/doctype/installation_note/installation_note.py
index ce21363..e0af7ec 100644
--- a/selling/doctype/installation_note/installation_note.py
+++ b/selling/doctype/installation_note/installation_note.py
@@ -29,20 +29,7 @@
   # ---------
   def autoname(self):
     self.doc.name = make_autoname(self.doc.naming_series+'.#####')
-  
-  #fetch customer details
-  #=================================
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name, t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = '%s' and t1.name=t2.customer and t2.is_primary_contact = 'Yes'"%self.doc.customer, as_dict=1)
-    
-  #  ret = {
-  #    'customer_name':  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-
-  #  return str(ret)
+ 
   
   #fetch delivery note details
   #====================================
diff --git a/selling/doctype/installation_note/installation_note.txt b/selling/doctype/installation_note/installation_note.txt
index adfce20..8feb2f5 100644
--- a/selling/doctype/installation_note/installation_note.txt
+++ b/selling/doctype/installation_note/installation_note.txt
@@ -201,7 +201,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -257,7 +257,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -292,7 +292,8 @@
 		'oldfieldname': 'inst_date',
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
@@ -340,7 +341,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
diff --git a/selling/doctype/installed_item_details/installed_item_details.txt b/selling/doctype/installed_item_details/installed_item_details.txt
index 7971cb5..3b4632c 100644
--- a/selling/doctype/installed_item_details/installed_item_details.txt
+++ b/selling/doctype/installed_item_details/installed_item_details.txt
@@ -140,7 +140,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
diff --git a/selling/doctype/lead/lead.py b/selling/doctype/lead/lead.py
index 1bf8c8d..14d14e1 100644
--- a/selling/doctype/lead/lead.py
+++ b/selling/doctype/lead/lead.py
@@ -51,7 +51,7 @@
       'description': it and it[0][3] or '',
       'uom' : it and it[0][4] or ''
       }
-      return cstr(ret)
+      return ret
   
   def validate(self):
     import string
diff --git a/selling/doctype/lead/lead.txt b/selling/doctype/lead/lead.txt
index a476c66..2387323 100644
--- a/selling/doctype/lead/lead.txt
+++ b/selling/doctype/lead/lead.txt
@@ -188,7 +188,7 @@
 		'options': "\nExisting Customer\nReference\nAdvertisement\nCold Calling\nExhibition\nSupplier Reference\nMass Mailing\nCustomer's Vendor\nCampaign\nWebsite",
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -239,7 +239,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -350,7 +350,7 @@
 		'options': '\nHot\nWarm\nCold',
 		'permlevel': 0,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -616,7 +616,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Profile',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -633,7 +633,7 @@
 		'options': '\nLower Income\nMiddle Income\nUpper Income',
 		'permlevel': 0,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/selling/doctype/quotation/quotation.py b/selling/doctype/quotation/quotation.py
index aed868e..1175540 100644
--- a/selling/doctype/quotation/quotation.py
+++ b/selling/doctype/quotation/quotation.py
@@ -45,17 +45,12 @@
 
     self.get_adj_percent()
 
-    return cstr(self.doc.quotation_to)
-    
-  # Get Customer Details
-  # --------------------
-  #def get_customer_details(self):
-  #  return cstr(get_obj('Sales Common').get_customer_details(self))
+    return self.doc.quotation_to
 
   # Get contact person details based on customer selected
   # ------------------------------------------------------
   def get_contact_details(self):
-    return cstr(get_obj('Sales Common').get_contact_details(self,0))
+    return get_obj('Sales Common').get_contact_details(self,0)
   
   # Clear Quotation Details
   # -----------------------
@@ -111,7 +106,7 @@
       'contact_mobile' : details and details[0]['mobile_no'] or '-',
       'contact_email' : details and details[0]['email_id'] or '-'      
     }
-    return cstr(ret)
+    return ret
 
      
 # GET TERMS AND CONDITIONS
@@ -295,7 +290,7 @@
       set(self.doc, 'status', 'Order Lost')
       set(self.doc, 'order_lost_reason', arg)
       self.update_enquiry('order lost')
-      return cstr('true')
+      return 'true'
   
   #check if value entered in item table
   #--------------------------------------
diff --git a/selling/doctype/quotation/quotation.txt b/selling/doctype/quotation/quotation.txt
index e198b86..6763c2d 100644
--- a/selling/doctype/quotation/quotation.txt
+++ b/selling/doctype/quotation/quotation.txt
@@ -414,7 +414,7 @@
 		'permlevel': 0,
 		'print_hide': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -435,7 +435,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -520,7 +520,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -539,7 +539,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -584,7 +584,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client',
 		'width': '100px'
 	},
@@ -1035,7 +1035,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client',
 		'width': '150px'
 	},
@@ -1055,7 +1055,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/selling/doctype/quotation_detail/quotation_detail.txt b/selling/doctype/quotation_detail/quotation_detail.txt
index 074443b..23c86fa 100644
--- a/selling/doctype/quotation_detail/quotation_detail.txt
+++ b/selling/doctype/quotation_detail/quotation_detail.txt
@@ -73,7 +73,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -260,7 +260,7 @@
 		'options': 'Item Group',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -276,7 +276,7 @@
 		'options': 'Brand',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
diff --git a/selling/doctype/return_detail/return_detail.txt b/selling/doctype/return_detail/return_detail.txt
index 7091b3f..4c1e2f7 100644
--- a/selling/doctype/return_detail/return_detail.txt
+++ b/selling/doctype/return_detail/return_detail.txt
@@ -75,7 +75,8 @@
 		'oldfieldname': 'uom',
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/selling/doctype/sales_common/sales_common.py b/selling/doctype/sales_common/sales_common.py
index 25dd960..acdca50 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -118,21 +118,21 @@
 		t = {}
 		for x in tax: t[x[0]] = flt(x[1])
 		ret = {
-			'description'								 : item and item[0]['description_html'] or item[0]['description'],
-			'item_group'									: item and item[0]['item_group'] or '',
-			'item_name'									 : item and item[0]['item_name'] or '',
-			'brand'											 : item and item[0]['brand'] or '',
-			'stock_uom'									 : item and item[0]['stock_uom'] or '',
-			'reserved_warehouse'					: item and item[0]['default_warehouse'] or '',
-			'warehouse'									 : item and item[0]['default_warehouse'] or '',
-			'income_account'							: item and item[0]['default_income_account'] or '',
-			'cost_center'								 : item and item[0]['default_sales_cost_center'] or '',
-			'qty'												 : 1.00,	 # this is done coz if item once fetched is fetched again thn its qty shld be reset to 1
-			'adj_rate'										: 0,
-			'amount'											: 0,
-			'export_amount'							 : 0,
-			'item_tax_rate'							 : str(t),
-			'batch_no'										: ''
+			'description'			: item and item[0]['description_html'] or item[0]['description'],
+			'item_group'			: item and item[0]['item_group'] or '',
+			'item_name'				: item and item[0]['item_name'] or '',
+			'brand'					: item and item[0]['brand'] or '',
+			'stock_uom'				: item and item[0]['stock_uom'] or '',
+			'reserved_warehouse'	: item and item[0]['default_warehouse'] or '',
+			'warehouse'				: item and item[0]['default_warehouse'] or '',
+			'income_account'		: item and item[0]['default_income_account'] or '',
+			'cost_center'			: item and item[0]['default_sales_cost_center'] or '',
+			'qty'					: 1.00,	 # this is done coz if item once fetched is fetched again thn its qty shld be reset to 1
+			'adj_rate'				: 0,
+			'amount'				: 0,
+			'export_amount'			: 0,
+			'item_tax_rate'			: str(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
 			ref_rate =	self.get_ref_rate(item_code, obj.doc.price_list_name, obj.doc.currency)
@@ -143,7 +143,8 @@
 			
 		if obj.doc.doctype == 'Receivable Voucher':
 			return ret
-		return str(ret)
+			
+		return ret
 	
 	# ***************** Get Ref rate as entered in Item Master ********************
 	def get_ref_rate(self, item_code, price_list_name, currency):
@@ -161,7 +162,6 @@
 			d.base_ref_rate = flt(ref_rate) * flt(obj.doc.conversion_rate)
 			d.export_rate = flt(ref_rate)
 
-
 	# Load Default Taxes
 	# ====================
 	def load_default_taxes(self, obj):
@@ -203,7 +203,7 @@
 		ret = {
 			'item_tax_rate'		:	tax and str(t) or ''
 		}
-		return str(ret)
+		return ret
 
 	# Get Serial No Details
 	# ==========================================================================
@@ -220,7 +220,7 @@
 			'description'			: item and item[0]['description'] or '',
 			'item_tax_rate'		: str(t)
 		}
-		return str(ret)
+		return ret
 		
 	# Get Commission rate
 	# =======================================================================
@@ -233,7 +233,7 @@
 				'commission_rate'		 :	comm_rate and flt(comm_rate[0]['commission_rate']) or 0,
 				'total_commission'		:	flt(total_comm)
 			}
-			return str(ret)
+			return ret
 		else:
 			msgprint("Business Associate : %s does not exist in the system." % (sales_partner))
 			raise Exception
@@ -287,7 +287,7 @@
 			ret = {
 				'rate'	:	rate and flt(rate[0]['tax_rate']) or 0
 			}
-		return cstr(ret)
+		return ret
 		
 
 	# Make Packing List from Sales BOM
@@ -324,11 +324,33 @@
 			
 			if self.has_sales_bom(d.item_code):
 				for i in self.get_sales_bom_items(d.item_code):
-					il.append([warehouse, i[0], flt(flt(i[1])* qty), reserved_qty, i[2], d.batch_no, d.serial_no])
+					il.append([warehouse, i[0], flt(flt(i[1])* qty), flt(flt(i[1])*reserved_qty), i[2], d.batch_no, d.serial_no])
 			else:
 				il.append([warehouse, d.item_code, qty, reserved_qty, d.stock_uom, d.batch_no, d.serial_no])
 		return il
 
+	# ---------------------------------------------------------------------------------------------
+	# get qty, amount already billed or delivered against curr line item for current doctype
+	# For Eg: SO-RV get total qty, amount from SO and also total qty, amount against that SO in RV
+	# ---------------------------------------------------------------------------------------------
+	def get_curr_and_ref_doc_details(self, curr_doctype, ref_tab_fname, ref_tab_dn, ref_doc_tname, curr_parent_name, curr_parent_doctype):
+		# Get total qty, amt of current doctype (eg RV) except for qty, amt of this transaction
+		if curr_parent_doctype == 'Installation Note':
+			curr_det = sql("select sum(qty) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
+			qty, amt = curr_det and flt(curr_det[0][0]) or 0, 0
+		else:
+			curr_det = sql("select sum(qty), sum(amount) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
+			qty, amt = curr_det and flt(curr_det[0][0]) or 0, curr_det and flt(curr_det[0][1]) or 0
+
+		# get total qty of ref doctype
+		ref_det = sql("select qty, amount from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn))
+		max_qty, max_amt = ref_det and flt(ref_det[0][0]) or 0, ref_det and flt(ref_det[0][1]) or 0
+
+		return qty, max_qty, amt, max_amt
+
+
+
+
 
 	# -----------------------
 	# add packing list items
@@ -458,26 +480,6 @@
 	def update_prevdoc_detail(self, is_submit, obj):
 		StatusUpdater(obj, is_submit).update()
 
-	# ---------------------------------------------------------------------------------------------
-	# get qty, amount already billed or delivered against curr line item for current doctype
-	# For Eg: SO-RV get total qty, amount from SO and also total qty, amount against that SO in RV
-	# ---------------------------------------------------------------------------------------------
-	def get_curr_and_ref_doc_details(self, curr_doctype, ref_tab_fname, ref_tab_dn, ref_doc_tname, curr_parent_name, curr_parent_doctype):
-		# Get total qty, amt of current doctype (eg RV) except for qty, amt of this transaction
-		if curr_parent_doctype == 'Installation Note':
-			curr_det = sql("select sum(qty) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
-			qty, amt = curr_det and flt(curr_det[0][0]) or 0, 0
-		else:
-			curr_det = sql("select sum(qty), sum(amount) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
-			qty, amt = curr_det and flt(curr_det[0][0]) or 0, curr_det and flt(curr_det[0][1]) or 0
-
-		# get total qty of ref doctype
-		ref_det = sql("select qty, amount from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn))
-		max_qty, max_amt = ref_det and flt(ref_det[0][0]) or 0, ref_det and flt(ref_det[0][1]) or 0
-
-		return qty, max_qty, amt, max_amt
-
-
 
 
 
@@ -496,7 +498,7 @@
 			- Validate over delivery
 			
 		From Receivable Voucher 
-			- Update Billed Qty
+			- Update Billed Amt
 			- Update Percent
 			- Validate over billing
 			
@@ -524,23 +526,33 @@
 			self.validate_qty({
 				'source_dt'		:'Delivery Note Detail',
 				'compare_field'	:'delivered_qty',
+				'compare_ref_field'	:'qty',
 				'target_dt'		:'Sales Order Detail',
 				'join_field'	:'prevdoc_detail_docname'
 			})
 		elif self.obj.doc.doctype=='Receivable Voucher':
 			self.validate_qty({
 				'source_dt'		:'RV Detail',
-				'compare_field'	:'billed_qty',
+				'compare_field'	:'billed_amt',
+				'compare_ref_field'	:'amount',
 				'target_dt'		:'Sales Order Detail',
 				'join_field'	:'so_detail'
 			})
+			self.validate_qty({
+				'source_dt'		:'RV Detail',
+				'compare_field'	:'billed_amt',
+				'compare_ref_field'	:'amount',
+				'target_dt'		:'Delivery Note Detail',
+				'join_field'	:'dn_detail'
+			}, no_tolerance =1)
 		elif self.obj.doc.doctype=='Installation Note':
 			self.validate_qty({
 				'source_dt'		:'Installation Item Details',
 				'compare_field'	:'installed_qty',
+				'compare_ref_field'	:'qty',
 				'target_dt'		:'Delivery Note Detail',
 				'join_field'	:'dn_detail'
-			}, no_tolerance =1);
+			}, no_tolerance =1)
 
 	
 	def get_tolerance_for(self, item_code):
@@ -567,22 +579,22 @@
 		
 		# check if overflow is within tolerance
 		tolerance = self.get_tolerance_for(item['item_code'])
-		overflow_percent = ((item[args['compare_field']] - item['qty']) / item['qty'] * 100)
+		overflow_percent = ((item[args['compare_field']] - item[args['compare_ref_field']]) / item[args['compare_ref_field']] * 100)
 	
 		if overflow_percent - tolerance > 0.0001:
-			item['max_allowed'] = flt(item['qty'] * (100+tolerance)/100)
+			item['max_allowed'] = flt(item[args['compare_ref_field']] * (100+tolerance)/100)
 			item['reduce_by'] = item[args['compare_field']] - item['max_allowed']
 		
 			msgprint("""
-				Row #%(idx)s: Max qty allowed for <b>Item %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>. 
+				Row #%(idx)s: Max %(compare_ref_field)s allowed for <b>Item %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>. 
 				
 				If you want to increase your overflow tolerance, please increase tolerance %% in Global Defaults or Item master. 
 				
-				Or, you must reduce the qty by %(reduce_by)s""" % item, raise_exception=1)
+				Or, you must reduce the %(compare_ref_field)s by %(reduce_by)s""" % item, raise_exception=1)
 
 	def validate_qty(self, args, no_tolerance=None):
 		"""
-			Updates qty at row level
+			Validates qty at row level
 		"""
 		# get unique transactions to update
 		for d in self.obj.doclist:
@@ -591,22 +603,23 @@
 
 				# get all qty where qty > compare_field
 				item = sql("""
-					select item_code, qty, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s` 
-					where qty < `%(compare_field)s` and name="%(name)s" and docstatus=1
+					select item_code, `%(compare_ref_field)s`, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s` 
+					where `%(compare_ref_field)s` < `%(compare_field)s` and name="%(name)s" and docstatus=1
 					""" % args, as_dict=1)
 				
 				if item:
 					item = item[0]
 					item['idx'] = d.idx
-					
+					item['compare_ref_field'] = args['compare_ref_field']
 					if no_tolerance:
-						item['reduce_by'] = item[args['compare_field']] - item['qty']
+						item['reduce_by'] = item[args['compare_field']] - item[args['compare_ref_field']]
 						msgprint("""
-							Row #%(idx)s: Max qty allowed for <b>Item %(item_code)s</b> against 
-							<b>%(parenttype)s %(parent)s</b> is <b>%(qty)s</b>. 
+							Row #%(idx)s: Max %(compare_ref_field)s allowed for <b>Item %(item_code)s</b> against 
+							<b>%(parenttype)s %(parent)s</b> is <b>""" % item 
+							+ cstr(item[args['compare_ref_field']]) + """</b>. 
 							
-							You must reduce the qty by %(reduce_by)s""" % item, raise_exception=1)
-						
+							You must reduce the %(compare_ref_field)s by %(reduce_by)s""" % item, raise_exception=1)
+					
 					else:
 						self.check_overflow_with_tolerance(item, args)
 						
@@ -621,6 +634,7 @@
 				'target_dt'				:'Sales Order Detail',
 				'target_parent_dt'		:'Sales Order',
 				'target_parent_field'	:'per_delivered',
+				'target_ref_field'		:'qty',
 				'source_dt'				:'Delivery Note Detail',
 				'source_field'			:'qty',
 				'join_field'			:'prevdoc_detail_docname',
@@ -631,12 +645,13 @@
 			
 		elif self.obj.doc.doctype=='Receivable Voucher':
 			self.update_qty({
-				'target_field'			:'billed_qty',
+				'target_field'			:'billed_amt',
 				'target_dt'				:'Sales Order Detail',
 				'target_parent_dt'		:'Sales Order',
 				'target_parent_field'	:'per_billed',
+				'target_ref_field'		:'amount',
 				'source_dt'				:'RV Detail',
-				'source_field'			:'qty',
+				'source_field'			:'amount',
 				'join_field'			:'so_detail',
 				'percent_join_field'	:'sales_order',
 				'status_field'			:'billing_status',
@@ -644,12 +659,13 @@
 			})
 
 			self.update_qty({
-				'target_field'			:'billed_qty',
+				'target_field'			:'billed_amt',
 				'target_dt'				:'Delivery Note Detail',
 				'target_parent_dt'		:'Delivery Note',
 				'target_parent_field'	:'per_billed',
+				'target_ref_field'		:'amount',
 				'source_dt'				:'RV Detail',
-				'source_field'			:'qty',
+				'source_field'			:'amount',
 				'join_field'			:'dn_detail',
 				'percent_join_field'	:'delivery_note',
 				'status_field'			:'billing_status',
@@ -662,6 +678,7 @@
 				'target_dt'				:'Delivery Note Detail',
 				'target_parent_dt'		:'Delivery Note',
 				'target_parent_field'	:'per_installed',
+				'target_ref_field'		:'qty',
 				'source_dt'				:'Installed Item Details',
 				'source_field'			:'qty',
 				'join_field'			:'prevdoc_detail_docname',
@@ -692,7 +709,7 @@
 						update 
 							`tab%(target_dt)s` 
 						set 
-							%(target_field)s = (select sum(qty) from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s" and (docstatus=1 %(cond)s))
+							%(target_field)s = (select sum(%(source_field)s) from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s" and (docstatus=1 %(cond)s))
 						where
 							name="%(detail_id)s"            
 					""" % args)			
@@ -708,10 +725,10 @@
 						`tab%(target_parent_dt)s` 
 					set 
 						%(target_parent_field)s = 
-							(select sum(if(qty > ifnull(%(target_field)s, 0), %(target_field)s, qty))/sum(qty)*100 from `tab%(target_dt)s` where parent="%(name)s"), 
+							(select sum(if(%(target_ref_field)s > ifnull(%(target_field)s, 0), %(target_field)s, %(target_ref_field)s))/sum(%(target_ref_field)s)*100 from `tab%(target_dt)s` where parent="%(name)s"), 
 						modified = now()
-						where
-							name="%(name)s"
+					where
+						name="%(name)s"
 					""" % args)
 
 				# update field
diff --git a/selling/doctype/sales_order/sales_order.py b/selling/doctype/sales_order/sales_order.py
index 11842fb..ca5af7a 100644
--- a/selling/doctype/sales_order/sales_order.py
+++ b/selling/doctype/sales_order/sales_order.py
@@ -19,470 +19,469 @@
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
-  def __init__(self, doc, doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
-    self.tname = 'Sales Order Detail'
-    self.fname = 'sales_order_details'
-    self.person_tname = 'Target Detail'
-    self.partner_tname = 'Partner Target Detail'
-    self.territory_tname = 'Territory Target Detail'
+	def __init__(self, doc, doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		self.tname = 'Sales Order Detail'
+		self.fname = 'sales_order_details'
+		self.person_tname = 'Target Detail'
+		self.partner_tname = 'Partner Target Detail'
+		self.territory_tname = 'Territory Target Detail'
 
 # Autoname
 # ===============
-  def autoname(self):
-    self.doc.name = make_autoname(self.doc.naming_series+'.#####')
+	def autoname(self):
+		self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
-    
+		
 # DOCTYPE TRIGGER FUNCTIONS
 # =============================
-  # Pull Quotation Details
-  # -----------------------
-  def pull_quotation_details(self):
-    self.doc.clear_table(self.doclist, 'other_charges')
-    self.doc.clear_table(self.doclist, 'sales_order_details')
-    self.doc.clear_table(self.doclist, 'sales_team')
-    self.doc.clear_table(self.doclist, 'tc_details')
-    if self.doc.quotation_no:        
-      get_obj('DocType Mapper', 'Quotation-Sales Order').dt_map('Quotation', 'Sales Order', self.doc.quotation_no, self.doc, self.doclist, "[['Quotation', 'Sales Order'],['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team'],['TC Detail','TC Detail']]")      
-    else:
-      msgprint("Please select Quotation whose details need to pull")    
+	# Pull Quotation Details
+	# -----------------------
+	def pull_quotation_details(self):
+		self.doc.clear_table(self.doclist, 'other_charges')
+		self.doc.clear_table(self.doclist, 'sales_order_details')
+		self.doc.clear_table(self.doclist, 'sales_team')
+		self.doc.clear_table(self.doclist, 'tc_details')
+		if self.doc.quotation_no:				
+			get_obj('DocType Mapper', 'Quotation-Sales Order').dt_map('Quotation', 'Sales Order', self.doc.quotation_no, self.doc, self.doclist, "[['Quotation', 'Sales Order'],['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team'],['TC Detail','TC Detail']]")			
+		else:
+			msgprint("Please select Quotation whose details need to pull")		
 
-    return cstr(self.doc.quotation_no)
-  
-  #pull project customer
-  #-------------------------
-  def pull_project_customer(self):
-    res = sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name)
-    if res:
-      get_obj('DocType Mapper', 'Project-Sales Order').dt_map('Project', 'Sales Order', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Sales Order']]")
-      
-  
-  # Get Customer Details
-  # ---------------------
-  #def get_customer_details(self):
-  #  sales_com_obj = get_obj('Sales Common')
-  #  sales_com_obj.get_customer_details(self)
-  #  sales_com_obj.get_shipping_details(self)
+		return cstr(self.doc.quotation_no)
+	
+	#pull project customer
+	#-------------------------
+	def pull_project_customer(self):
+		res = sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name)
+		if res:
+			get_obj('DocType Mapper', 'Project-Sales Order').dt_map('Project', 'Sales Order', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Sales Order']]")
+			
+	
+	# Get Customer Details
+	# ---------------------
+	#def get_customer_details(self):
+	#	sales_com_obj = get_obj('Sales Common')
+	#	sales_com_obj.get_customer_details(self)
+	#	sales_com_obj.get_shipping_details(self)
 
-  # Get contact person details based on customer selected
-  # ------------------------------------------------------
-  def get_contact_details(self):
-    get_obj('Sales Common').get_contact_details(self,0)
+	# Get contact person details based on customer selected
+	# ------------------------------------------------------
+	def get_contact_details(self):
+		get_obj('Sales Common').get_contact_details(self,0)
 
-  # Get Commission rate of Sales Partner
-  # -------------------------------------
-  def get_comm_rate(self, sales_partner):
-    return get_obj('Sales Common').get_comm_rate(sales_partner, self)
+	# Get Commission rate of Sales Partner
+	# -------------------------------------
+	def get_comm_rate(self, sales_partner):
+		return get_obj('Sales Common').get_comm_rate(sales_partner, self)
 
-  # Clear Sales Order Details Table
-  # --------------------------------
-  def clear_sales_order_details(self):
-    self.doc.clear_table(self.doclist, 'sales_order_details')
-    
+	# Clear Sales Order Details Table
+	# --------------------------------
+	def clear_sales_order_details(self):
+		self.doc.clear_table(self.doclist, 'sales_order_details')
+		
 
 # SALES ORDER DETAILS TRIGGER FUNCTIONS
 # ================================================================================
-  # Get Item Details
-  # ----------------
-  def get_item_details(self, item_code):
-    return get_obj('Sales Common').get_item_details(item_code, self)
+	# 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)
+	# 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 projected qty of item based on warehouse selected
-  # -----------------------------------------------------
-  def get_available_qty(self,args):
-    args = eval(args)
-    tot_avail_qty = sql("select projected_qty, actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
-    ret = {
-       'projected_qty' : tot_avail_qty and flt(tot_avail_qty[0]['projected_qty']) or 0,
-       'actual_qty' : tot_avail_qty and flt(tot_avail_qty[0]['actual_qty']) or 0
-    }
-    return cstr(ret)
-  
-  
+	# Get projected qty of item based on warehouse selected
+	# -----------------------------------------------------
+	def get_available_qty(self,args):
+		args = eval(args)
+		tot_avail_qty = sql("select projected_qty, actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
+		ret = {
+			 'projected_qty' : tot_avail_qty and flt(tot_avail_qty[0]['projected_qty']) or 0,
+			 'actual_qty' : tot_avail_qty and flt(tot_avail_qty[0]['actual_qty']) or 0
+		}
+		return ret
+	
 # 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)
+	# Pull details from other charges master (Get Other Charges)
+	# ----------------------------------------------------------
+	def get_other_charges(self):
+		return get_obj('Sales Common').get_other_charges(self)
  
  
 # GET TERMS & 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)
 
 #check if maintenance schedule already generated
 #============================================
-  def check_maintenance_schedule(self):
-    nm = sql("select t1.name from `tabMaintenance Schedule` t1, `tabItem Maintenance Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1", self.doc.name)
-    nm = nm and nm[0][0] or ''
-    
-    if not nm:
-      return cstr('No')
+	def check_maintenance_schedule(self):
+		nm = sql("select t1.name from `tabMaintenance Schedule` t1, `tabItem Maintenance Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1", self.doc.name)
+		nm = nm and nm[0][0] or ''
+		
+		if not nm:
+			return 'No'
 
 #check if maintenance visit already generated
 #============================================
-  def check_maintenance_visit(self):
-    nm = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1 and t1.completion_status='Fully Completed'", self.doc.name)
-    nm = nm and nm[0][0] or ''
-    
-    if not nm:
-      return cstr('No')
+	def check_maintenance_visit(self):
+		nm = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1 and t1.completion_status='Fully Completed'", self.doc.name)
+		nm = nm and nm[0][0] or ''
+		
+		if not nm:
+			return 'No'
 
 # VALIDATE
 # =====================================================================================
-  # Fiscal Year Validation
-  # ----------------------
-  def validate_fiscal_year(self):
-    get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Sales Order Date')
-  
-  # Validate values with reference document
-  #----------------------------------------
-  def validate_reference_value(self):
-    get_obj('DocType Mapper', 'Quotation-Sales Order', with_children = 1).validate_reference_value(self, self.doc.name)
+	# Fiscal Year Validation
+	# ----------------------
+	def validate_fiscal_year(self):
+		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Sales Order Date')
+	
+	# Validate values with reference document
+	#----------------------------------------
+	def validate_reference_value(self):
+		get_obj('DocType Mapper', 'Quotation-Sales Order', with_children = 1).validate_reference_value(self, self.doc.name)
 
-  # Validate Mandatory
-  # -------------------
-  def validate_mandatory(self):
-    # validate transaction date v/s delivery date
-    if self.doc.delivery_date:
-      if getdate(self.doc.transaction_date) > getdate(self.doc.delivery_date):
-        msgprint("Expected Delivery Date cannot be before Sales Order Date")
-        raise Exception
+	# Validate Mandatory
+	# -------------------
+	def validate_mandatory(self):
+		# validate transaction date v/s delivery date
+		if self.doc.delivery_date:
+			if getdate(self.doc.transaction_date) > getdate(self.doc.delivery_date):
+				msgprint("Expected Delivery Date cannot be before Sales Order Date")
+				raise Exception
 
-  # Validate P.O Date
-  # ------------------
-  def validate_po_date(self):
-    # validate p.o date v/s delivery date
-    if self.doc.po_date and self.doc.delivery_date and getdate(self.doc.po_date) >= getdate(self.doc.delivery_date):
-      msgprint("Expected Delivery Date cannot be before Purchase Order Date")
-      raise Exception  
-    # amendment date is necessary if document is amended
-    if self.doc.amended_from and not self.doc.amendment_date:
-      msgprint("Please Enter Amendment Date")
-      raise Exception
-  
-  # Validations of Details Table
-  # -----------------------------
-  def validate_for_items(self):
-    check_list,flag = [],0
-    chk_dupl_itm = []
-    # Sales Order Details Validations
-    for d in getlist(self.doclist, 'sales_order_details'):
-      if cstr(self.doc.quotation_no) == cstr(d.prevdoc_docname):
-        flag = 1
-      if d.prevdoc_docname:
-        if self.doc.quotation_date and getdate(self.doc.quotation_date) > getdate(self.doc.transaction_date):
-          msgprint("Sales Order Date cannot be before Quotation Date")
-          raise Exception
-        # validates whether quotation no in doctype and in table is same
-        if not cstr(d.prevdoc_docname) == cstr(self.doc.quotation_no):
-          msgprint("Items in table does not belong to the Quotation No mentioned.")
-          raise Exception
+	# Validate P.O Date
+	# ------------------
+	def validate_po_date(self):
+		# validate p.o date v/s delivery date
+		if self.doc.po_date and self.doc.delivery_date and getdate(self.doc.po_date) >= getdate(self.doc.delivery_date):
+			msgprint("Expected Delivery Date cannot be before Purchase Order Date")
+			raise Exception	
+		# amendment date is necessary if document is amended
+		if self.doc.amended_from and not self.doc.amendment_date:
+			msgprint("Please Enter Amendment Date")
+			raise Exception
+	
+	# Validations of Details Table
+	# -----------------------------
+	def validate_for_items(self):
+		check_list,flag = [],0
+		chk_dupl_itm = []
+		# Sales Order Details Validations
+		for d in getlist(self.doclist, 'sales_order_details'):
+			if cstr(self.doc.quotation_no) == cstr(d.prevdoc_docname):
+				flag = 1
+			if d.prevdoc_docname:
+				if self.doc.quotation_date and getdate(self.doc.quotation_date) > getdate(self.doc.transaction_date):
+					msgprint("Sales Order Date cannot be before Quotation Date")
+					raise Exception
+				# validates whether quotation no in doctype and in table is same
+				if not cstr(d.prevdoc_docname) == cstr(self.doc.quotation_no):
+					msgprint("Items in table does not belong to the Quotation No mentioned.")
+					raise Exception
 
-      # validates whether item is not entered twice
-      e = [d.item_code, d.description, d.reserved_warehouse, d.prevdoc_docname or '']
-      f = [d.item_code, d.description]
+			# validates whether item is not entered twice
+			e = [d.item_code, d.description, d.reserved_warehouse, d.prevdoc_docname or '']
+			f = [d.item_code, d.description]
 
-      #check item is stock item
-      st_itm = sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
+			#check item is stock item
+			st_itm = sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
 
-      if st_itm and st_itm[0][0] == 'Yes':
-        if e in check_list:
-          msgprint("Item %s has been entered twice." % d.item_code)
-        else:
-          check_list.append(e)
-      elif st_itm and st_itm[0][0]== 'No':
-        if f in chk_dupl_itm:
-          msgprint("Item %s has been entered twice." % d.item_code)
-        else:
-          chk_dupl_itm.append(f)
+			if st_itm and st_itm[0][0] == 'Yes':
+				if e in check_list:
+					msgprint("Item %s has been entered twice." % d.item_code)
+				else:
+					check_list.append(e)
+			elif st_itm and st_itm[0][0]== 'No':
+				if f in chk_dupl_itm:
+					msgprint("Item %s has been entered twice." % d.item_code)
+				else:
+					chk_dupl_itm.append(f)
 
-      # used for production plan
-      d.transaction_date = self.doc.transaction_date
-      d.delivery_date = self.doc.delivery_date
+			# used for production plan
+			d.transaction_date = self.doc.transaction_date
+			d.delivery_date = self.doc.delivery_date
 
-      # gets total projected qty of item in warehouse selected (this case arises when warehouse is selected b4 item)
-      tot_avail_qty = sql("select projected_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code,d.reserved_warehouse))
-      d.projected_qty = tot_avail_qty and flt(tot_avail_qty[0][0]) or 0
-    
-    if flag == 0:
-      msgprint("There are no items of the quotation selected.")
-      raise Exception
+			# gets total projected qty of item in warehouse selected (this case arises when warehouse is selected b4 item)
+			tot_avail_qty = sql("select projected_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code,d.reserved_warehouse))
+			d.projected_qty = tot_avail_qty and flt(tot_avail_qty[0][0]) or 0
+		
+		if flag == 0:
+			msgprint("There are no items of the quotation selected.")
+			raise Exception
 
-  # validate sales/ service item against order type
-  #----------------------------------------------------
-  def validate_sales_mntc_item(self):
-    if self.doc.order_type == 'Maintenance':
-      item_field = 'is_service_item'
-      order_type = 'Maintenance Order'
-      item_type = 'service item'
-    else :
-      item_field = 'is_sales_item'
-      order_type = 'Sales Order'
-      item_type = 'sales item'
-    
-    for d in getlist(self.doclist, 'sales_order_details'):
-      res = sql("select %s from `tabItem` where name='%s'"% (item_field,d.item_code))
-      res = res and res[0][0] or 'No'
-      
-      if res == 'No':
-        msgprint("You can not select non "+item_type+" "+d.item_code+" in "+order_type)
-        raise Exception
-  
-  # validate sales/ maintenance quotation against order type
-  #------------------------------------------------------------------
-  def validate_sales_mntc_quotation(self):
-    for d in getlist(self.doclist, 'sales_order_details'):
-      if d.prevdoc_docname:
-        res = sql("select order_type from `tabQuotation` where name=%s", (d.prevdoc_docname))
-        res = res and res[0][0] or ''
-        
-        if self.doc.order_type== 'Maintenance' and res != 'Maintenance':
-          msgprint("You can not select non Maintenance Quotation against Maintenance Order")
-          raise Exception
-        elif self.doc.order_type != 'Maintenance' and res == 'Maintenance':
-          msgprint("You can not select non Sales Quotation against Sales Order")
-          raise Exception
+	# validate sales/ service item against order type
+	#----------------------------------------------------
+	def validate_sales_mntc_item(self):
+		if self.doc.order_type == 'Maintenance':
+			item_field = 'is_service_item'
+			order_type = 'Maintenance Order'
+			item_type = 'service item'
+		else :
+			item_field = 'is_sales_item'
+			order_type = 'Sales Order'
+			item_type = 'sales item'
+		
+		for d in getlist(self.doclist, 'sales_order_details'):
+			res = sql("select %s from `tabItem` where name='%s'"% (item_field,d.item_code))
+			res = res and res[0][0] or 'No'
+			
+			if res == 'No':
+				msgprint("You can not select non "+item_type+" "+d.item_code+" in "+order_type)
+				raise Exception
+	
+	# validate sales/ maintenance quotation against order type
+	#------------------------------------------------------------------
+	def validate_sales_mntc_quotation(self):
+		for d in getlist(self.doclist, 'sales_order_details'):
+			if d.prevdoc_docname:
+				res = sql("select order_type from `tabQuotation` where name=%s", (d.prevdoc_docname))
+				res = res and res[0][0] or ''
+				
+				if self.doc.order_type== 'Maintenance' and res != 'Maintenance':
+					msgprint("You can not select non Maintenance Quotation against Maintenance Order")
+					raise Exception
+				elif self.doc.order_type != 'Maintenance' and res == 'Maintenance':
+					msgprint("You can not select non Sales Quotation against Sales Order")
+					raise Exception
 
-  #do not allow sales item/quotation in maintenance order and service item/quotation in sales order
-  #-----------------------------------------------------------------------------------------------
-  def validate_order_type(self):
-    #validate delivery date
-    if self.doc.order_type != 'Maintenance' and not self.doc.delivery_date:
-      msgprint("Please enter 'Expected Delivery Date'")
-      raise Exception
-    
-    self.validate_sales_mntc_quotation()
-    self.validate_sales_mntc_item()
+	#do not allow sales item/quotation in maintenance order and service item/quotation in sales order
+	#-----------------------------------------------------------------------------------------------
+	def validate_order_type(self):
+		#validate delivery date
+		if self.doc.order_type != 'Maintenance' and not self.doc.delivery_date:
+			msgprint("Please enter 'Expected Delivery Date'")
+			raise Exception
+		
+		self.validate_sales_mntc_quotation()
+		self.validate_sales_mntc_item()
 
-  #check for does customer belong to same project as entered..
-  #-------------------------------------------------------------------------------------------------
-  def validate_proj_cust(self):
-    if self.doc.project_name and self.doc.customer_name:
-      res = sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
-      if not res:
-        msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in project - %s."%(self.doc.customer,self.doc.project_name,self.doc.project_name))
-        raise Exception
-       
+	#check for does customer belong to same project as entered..
+	#-------------------------------------------------------------------------------------------------
+	def validate_proj_cust(self):
+		if self.doc.project_name and self.doc.customer_name:
+			res = sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
+			if not res:
+				msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in project - %s."%(self.doc.customer,self.doc.project_name,self.doc.project_name))
+				raise Exception
+			 
 
-  # Validate
-  # ---------
-  def validate(self):
-    self.validate_fiscal_year()
-    self.validate_order_type()
-    self.validate_mandatory()
-    self.validate_proj_cust()
-    self.validate_po_date()
-    #self.validate_reference_value()
-    self.validate_for_items()
-    sales_com_obj = get_obj(dt = 'Sales Common')
-    sales_com_obj.check_active_sales_items(self)
-    sales_com_obj.check_conversion_rate(self)
+	# Validate
+	# ---------
+	def validate(self):
+		self.validate_fiscal_year()
+		self.validate_order_type()
+		self.validate_mandatory()
+		self.validate_proj_cust()
+		self.validate_po_date()
+		#self.validate_reference_value()
+		self.validate_for_items()
+		sales_com_obj = get_obj(dt = 'Sales Common')
+		sales_com_obj.check_active_sales_items(self)
+		sales_com_obj.check_conversion_rate(self)
 
-        # verify whether rate is not greater than max_discount
-    sales_com_obj.validate_max_discount(self,'sales_order_details')
-        # this is to verify that the allocated % of sales persons is 100%
-    sales_com_obj.get_allocated_sum(self)
-    sales_com_obj.make_packing_list(self,'sales_order_details')
-    
-        # 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)
-    
-    # set SO status
-    self.doc.status='Draft'
-    if not self.doc.billing_status: self.doc.billing_status = 'Not Billed'
-    if not self.doc.delivery_status: self.doc.delivery_status = 'Not Delivered'
-    
+				# verify whether rate is not greater than max_discount
+		sales_com_obj.validate_max_discount(self,'sales_order_details')
+				# this is to verify that the allocated % of sales persons is 100%
+		sales_com_obj.get_allocated_sum(self)
+		sales_com_obj.make_packing_list(self,'sales_order_details')
+		
+				# 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)
+		
+		# set SO status
+		self.doc.status='Draft'
+		if not self.doc.billing_status: self.doc.billing_status = 'Not Billed'
+		if not self.doc.delivery_status: self.doc.delivery_status = 'Not Delivered'
+		
 
 # ON SUBMIT
 # ===============================================================================================
-  # Checks Quotation Status
-  # ------------------------
-  def check_prev_docstatus(self):
-    for d in getlist(self.doclist, 'sales_order_details'):
-      cancel_quo = sql("select name from `tabQuotation` where docstatus = 2 and name = '%s'" % d.prevdoc_docname)
-      if cancel_quo:
-        msgprint("Quotation :" + cstr(cancel_quo[0][0]) + " is already cancelled !")
-        raise Exception , "Validation Error. "
-  
-  def update_enquiry_status(self, prevdoc, flag):
-    enq = sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Detail` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
-    if enq:
-      sql("update `tabEnquiry` set status = %s where name=%s",(flag,enq[0][0]))
+	# Checks Quotation Status
+	# ------------------------
+	def check_prev_docstatus(self):
+		for d in getlist(self.doclist, 'sales_order_details'):
+			cancel_quo = sql("select name from `tabQuotation` where docstatus = 2 and name = '%s'" % d.prevdoc_docname)
+			if cancel_quo:
+				msgprint("Quotation :" + cstr(cancel_quo[0][0]) + " is already cancelled !")
+				raise Exception , "Validation Error. "
+	
+	def update_enquiry_status(self, prevdoc, flag):
+		enq = sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Detail` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
+		if enq:
+			sql("update `tabEnquiry` set status = %s where name=%s",(flag,enq[0][0]))
 
-  #update status of quotation, enquiry
-  #----------------------------------------
-  def update_prevdoc_status(self, flag):
-    for d in getlist(self.doclist, 'sales_order_details'):
-      if d.prevdoc_docname:
-        if flag=='submit':
-          sql("update `tabQuotation` set status = 'Order Confirmed' where name=%s",d.prevdoc_docname)
-          
-          #update enquiry
-          self.update_enquiry_status(d.prevdoc_docname, 'Order Confirmed')
-        elif flag == 'cancel':
-          chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t2.prevdoc_docname=%s and t1.name!=%s and t1.docstatus=1", (d.prevdoc_docname,self.doc.name))
-          if not chk:
-            sql("update `tabQuotation` set status = 'Submitted' where name=%s",d.prevdoc_docname)
-            
-            #update enquiry
-            self.update_enquiry_status(d.prevdoc_docname, 'Quotation Sent')
-  
-  # Submit
-  # -------
-  def on_submit(self):
-    self.check_prev_docstatus()    
-    self.update_stock_ledger(update_stock = 1)
-    self.set_sms_msg(1)
-    # update customer's last sales order no.
-    update_customer = sql("update `tabCustomer` set last_sales_order = '%s', modified = '%s' where name = '%s'" %(self.doc.name, self.doc.modified, self.doc.customer))
-    get_obj('Sales Common').check_credit(self,self.doc.grand_total)
-    
-    # Check for Approving Authority
-    get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.grand_total, self)
-    
-    #update prevdoc status
-    self.update_prevdoc_status('submit')
-    # set SO status
-    set(self.doc, 'status', 'Submitted')
-  
-    # on submit notification    
-    if self.doc.email_id:
-      get_obj('Notification Control').notify_contact('Sales Order',self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
-        
+	#update status of quotation, enquiry
+	#----------------------------------------
+	def update_prevdoc_status(self, flag):
+		for d in getlist(self.doclist, 'sales_order_details'):
+			if d.prevdoc_docname:
+				if flag=='submit':
+					sql("update `tabQuotation` set status = 'Order Confirmed' where name=%s",d.prevdoc_docname)
+					
+					#update enquiry
+					self.update_enquiry_status(d.prevdoc_docname, 'Order Confirmed')
+				elif flag == 'cancel':
+					chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t2.prevdoc_docname=%s and t1.name!=%s and t1.docstatus=1", (d.prevdoc_docname,self.doc.name))
+					if not chk:
+						sql("update `tabQuotation` set status = 'Submitted' where name=%s",d.prevdoc_docname)
+						
+						#update enquiry
+						self.update_enquiry_status(d.prevdoc_docname, 'Quotation Sent')
+	
+	# Submit
+	# -------
+	def on_submit(self):
+		self.check_prev_docstatus()		
+		self.update_stock_ledger(update_stock = 1)
+		self.set_sms_msg(1)
+		# update customer's last sales order no.
+		update_customer = sql("update `tabCustomer` set last_sales_order = '%s', modified = '%s' where name = '%s'" %(self.doc.name, self.doc.modified, self.doc.customer))
+		get_obj('Sales Common').check_credit(self,self.doc.grand_total)
+		
+		# Check for Approving Authority
+		get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.grand_total, self)
+		
+		#update prevdoc status
+		self.update_prevdoc_status('submit')
+		# set SO status
+		set(self.doc, 'status', 'Submitted')
+	
+		# on submit notification		
+		if self.doc.email_id:
+			get_obj('Notification Control').notify_contact('Sales Order',self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
+				
  
 # ON CANCEL
 # ===============================================================================================
-  def on_cancel(self):
-    # Cannot cancel stopped SO
-    if self.doc.status == 'Stopped':
-      msgprint("Sales Order : '%s' cannot be cancelled as it is Stopped. Unstop it for any further transactions" %(self.doc.name))
-      raise Exception
-    self.check_nextdoc_docstatus()
-    self.update_stock_ledger(update_stock = -1)
-    self.set_sms_msg()
-    
-    #update prevdoc status
-    self.update_prevdoc_status('cancel')
-    
-    # ::::::::: SET SO STATUS ::::::::::
-    set(self.doc, 'status', 'Cancelled')
-    
-  # CHECK NEXT DOCSTATUS
-  # does not allow to cancel document if DN or RV made against it is SUBMITTED 
-  # ----------------------------------------------------------------------------
-  def check_nextdoc_docstatus(self):
-    # Checks Delivery Note
-    submit_dn = sql("select t1.name from `tabDelivery Note` t1,`tabDelivery Note Detail` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
-    if submit_dn:
-      msgprint("Delivery Note : " + cstr(submit_dn[0][0]) + " has been submitted against " + cstr(self.doc.doctype) + ". Please cancel Delivery Note : " + cstr(submit_dn[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
-    # Checks Receivable Voucher
-    submit_rv = sql("select t1.name from `tabReceivable Voucher` t1,`tabRV Detail` t2 where t1.name = t2.parent and t2.sales_order = '%s' and t1.docstatus = 1" % (self.doc.name))
-    if submit_rv:
-      msgprint("Sales Invoice : " + cstr(submit_rv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Sales Invoice : "+ cstr(submit_rv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
-    #check maintenance schedule
-    submit_ms = sql("select t1.name from `tabMaintenance Schedule` t1, `tabItem Maintenance Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
-    if submit_ms:
-      msgprint("Maintenance Schedule : " + cstr(submit_ms[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Schedule : "+ cstr(submit_ms[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
-    submit_mv = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
-    if submit_mv:
-      msgprint("Maintenance Visit : " + cstr(submit_mv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Visit : " + cstr(submit_mv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
+	def on_cancel(self):
+		# Cannot cancel stopped SO
+		if self.doc.status == 'Stopped':
+			msgprint("Sales Order : '%s' cannot be cancelled as it is Stopped. Unstop it for any further transactions" %(self.doc.name))
+			raise Exception
+		self.check_nextdoc_docstatus()
+		self.update_stock_ledger(update_stock = -1)
+		self.set_sms_msg()
+		
+		#update prevdoc status
+		self.update_prevdoc_status('cancel')
+		
+		# ::::::::: SET SO STATUS ::::::::::
+		set(self.doc, 'status', 'Cancelled')
+		
+	# CHECK NEXT DOCSTATUS
+	# does not allow to cancel document if DN or RV made against it is SUBMITTED 
+	# ----------------------------------------------------------------------------
+	def check_nextdoc_docstatus(self):
+		# Checks Delivery Note
+		submit_dn = sql("select t1.name from `tabDelivery Note` t1,`tabDelivery Note Detail` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
+		if submit_dn:
+			msgprint("Delivery Note : " + cstr(submit_dn[0][0]) + " has been submitted against " + cstr(self.doc.doctype) + ". Please cancel Delivery Note : " + cstr(submit_dn[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
+		# Checks Receivable Voucher
+		submit_rv = sql("select t1.name from `tabReceivable Voucher` t1,`tabRV Detail` t2 where t1.name = t2.parent and t2.sales_order = '%s' and t1.docstatus = 1" % (self.doc.name))
+		if submit_rv:
+			msgprint("Sales Invoice : " + cstr(submit_rv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Sales Invoice : "+ cstr(submit_rv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
+		#check maintenance schedule
+		submit_ms = sql("select t1.name from `tabMaintenance Schedule` t1, `tabItem Maintenance Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
+		if submit_ms:
+			msgprint("Maintenance Schedule : " + cstr(submit_ms[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Schedule : "+ cstr(submit_ms[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
+		submit_mv = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Detail` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
+		if submit_mv:
+			msgprint("Maintenance Visit : " + cstr(submit_mv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Visit : " + cstr(submit_mv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
 
 
-  def check_modified_date(self):
-    mod_db = sql("select modified from `tabSales 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
+	def check_modified_date(self):
+		mod_db = sql("select modified from `tabSales 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
 
-  # STOP SALES ORDER
-  # ==============================================================================================      
-  # Stops Sales Order & no more transactions will be created against this Sales Order
-  def stop_sales_order(self):
-    self.check_modified_date()
-    self.update_stock_ledger(update_stock = -1,clear = 1)
-    # ::::::::: SET SO STATUS ::::::::::
-    set(self.doc, 'status', 'Stopped')
-    msgprint(self.doc.doctype + ": " + self.doc.name + " has been Stopped. To make transactions against this Sales Order you need to Unstop it.")
+	# STOP SALES ORDER
+	# ==============================================================================================			
+	# Stops Sales Order & no more transactions will be created against this Sales Order
+	def stop_sales_order(self):
+		self.check_modified_date()
+		self.update_stock_ledger(update_stock = -1,clear = 1)
+		# ::::::::: SET SO STATUS ::::::::::
+		set(self.doc, 'status', 'Stopped')
+		msgprint(self.doc.doctype + ": " + self.doc.name + " has been Stopped. To make transactions against this Sales Order you need to Unstop it.")
 
-  # UNSTOP SALES ORDER
-  # ==============================================================================================      
-  # Unstops Sales Order & now transactions can be continued against this Sales Order
-  def unstop_sales_order(self):
-    self.check_modified_date()
-    self.update_stock_ledger(update_stock = 1,clear = 1)
-    # ::::::::: SET SO STATUS ::::::::::
-    set(self.doc, 'status', 'Submitted')
-    msgprint(self.doc.doctype + ": " + self.doc.name + " has been Unstopped.")
+	# UNSTOP SALES ORDER
+	# ==============================================================================================			
+	# Unstops Sales Order & now transactions can be continued against this Sales Order
+	def unstop_sales_order(self):
+		self.check_modified_date()
+		self.update_stock_ledger(update_stock = 1,clear = 1)
+		# ::::::::: SET SO STATUS ::::::::::
+		set(self.doc, 'status', 'Submitted')
+		msgprint(self.doc.doctype + ": " + self.doc.name + " has been Unstopped.")
 
-  # UPDATE STOCK LEDGER
-  # ===============================================================================================
-  def update_stock_ledger(self, update_stock, clear = 0):
-    for d in self.get_item_list(clear):
-      stock_item = sql("SELECT is_stock_item FROM tabItem where name = '%s'"%(d[1]),as_dict = 1)       # stock ledger will be updated only if it is a stock item
-      if stock_item and stock_item[0]['is_stock_item'] == "Yes":
-        if not d[0]:
-          msgprint("Message: Please enter Reserved Warehouse for item %s as it is stock item."% d[1])
-          raise Exception
-        bin = get_obj('Warehouse', d[0]).update_bin( 0, flt(update_stock) * flt(d[2]), 0, 0, 0, d[1], self.doc.transaction_date)
+	# UPDATE STOCK LEDGER
+	# ===============================================================================================
+	def update_stock_ledger(self, update_stock, clear = 0):
+		for d in self.get_item_list(clear):
+			stock_item = sql("SELECT is_stock_item FROM tabItem where name = '%s'"%(d[1]),as_dict = 1)			 # stock ledger will be updated only if it is a stock item
+			if stock_item and stock_item[0]['is_stock_item'] == "Yes":
+				if not d[0]:
+					msgprint("Message: Please enter Reserved Warehouse for item %s as it is stock item."% d[1])
+					raise Exception
+				bin = get_obj('Warehouse', d[0]).update_bin( 0, flt(update_stock) * flt(d[2]), 0, 0, 0, d[1], self.doc.transaction_date)
+	
+	# Gets Items from packing list
+	#=================================
+	def get_item_list(self, clear):
+		return get_obj('Sales Common').get_item_list( self, clear)
+		
+	# SET MESSAGE FOR SMS
+	#======================
+	def set_sms_msg(self, is_submitted = 0):
+		if is_submitted:
+			if not self.doc.amended_from:
+				msg = 'Sales Order: '+self.doc.name+' has been made against PO no: '+cstr(self.doc.po_no)
+				set(self.doc, 'message', msg)
+			else:
+				msg = 'Sales Order has been amended. New SO no:'+self.doc.name
+				set(self.doc, 'message', msg)
+		else:
+			msg = 'Sales Order: '+self.doc.name+' has been cancelled.'
+			set(self.doc, 'message', msg)
+		
+	# 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.customer_mobile_no,], self.doc.message))
 
-  # Gets Items from packing list
-  #=================================
-  def get_item_list(self, clear):
-    return get_obj('Sales Common').get_item_list( self, clear)
-    
-  # SET MESSAGE FOR SMS
-  #======================
-  def set_sms_msg(self, is_submitted = 0):
-    if is_submitted:
-      if not self.doc.amended_from:
-        msg = 'Sales Order: '+self.doc.name+' has been made against PO no: '+cstr(self.doc.po_no)
-        set(self.doc, 'message', msg)
-      else:
-        msg = 'Sales Order has been amended. New SO no:'+self.doc.name
-        set(self.doc, 'message', msg)
-    else:
-      msg = 'Sales Order: '+self.doc.name+' has been cancelled.'
-      set(self.doc, 'message', msg)
-    
-  # 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.customer_mobile_no,], self.doc.message))
+	# on update
+	def on_update(self):
+		pass
 
-  # on update
-  def on_update(self):
-    pass
-
-  # Repair Sales Order
-  # ===========================================
-  def repair_sales_order(self):
-    get_obj('Sales Common', 'Sales Common').repair_curr_doctype_details(self)
+	# Repair Sales Order
+	# ===========================================
+	def repair_sales_order(self):
+		get_obj('Sales Common', 'Sales Common').repair_curr_doctype_details(self)
diff --git a/selling/doctype/sales_order/sales_order.txt b/selling/doctype/sales_order/sales_order.txt
index 69773dd..98833d1 100644
--- a/selling/doctype/sales_order/sales_order.txt
+++ b/selling/doctype/sales_order/sales_order.txt
@@ -5,15 +5,14 @@
 	{
 		'creation': '2010-08-08 17:09:21',
 		'docstatus': 0,
-		'modified': '2011-06-27 16:05:56',
+		'modified': '2011-08-09 17:06:09',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309170956',
-		'client_script': "cur_frm.add_fetch('customer','sales_person','sales_person');",
+		'_last_update': '1311621379',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'document_type': 'Transaction',
@@ -28,7 +27,7 @@
 		'show_in_menu': 0,
 		'subject': 'From %(customer_name)s on %(transaction_date)s worth %(currency)s %(grand_total_export)s | %(per_delivered)s% delivered | %(per_billed)s% billed',
 		'tag_fields': 'delivery_status,billing_status',
-		'version': 593
+		'version': 597
 	},
 
 	# These values are common for all DocField
@@ -58,28 +57,23 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 1,
-		'permlevel': 1,
-		'role': 'Sales Manager',
-		'submit': 0,
-		'write': 0
+		'permlevel': 0,
+		'role': 'Production Manager'
 	},
 
 	# DocPerm
 	{
-		'amend': 1,
-		'cancel': 1,
-		'create': 1,
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 2,
-		'permlevel': 0,
+		'permlevel': 1,
 		'role': 'Sales Manager',
-		'submit': 1,
-		'write': 1
+		'submit': 0,
+		'write': 0
 	},
 
 	# DocPerm
@@ -90,6 +84,19 @@
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
+		'role': 'Sales Manager',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocPerm
+	{
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'idx': 4,
+		'permlevel': 0,
 		'role': 'Sales User',
 		'submit': 1,
 		'write': 1
@@ -101,7 +108,7 @@
 		'cancel': 0,
 		'create': 0,
 		'doctype': 'DocPerm',
-		'idx': 4,
+		'idx': 5,
 		'permlevel': 1,
 		'role': 'Sales User',
 		'submit': 0,
@@ -111,7 +118,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 5,
+		'idx': 6,
 		'match': 'customer_name',
 		'permlevel': 0,
 		'role': 'Customer'
@@ -120,7 +127,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 6,
+		'idx': 7,
 		'permlevel': 2,
 		'role': 'Accounts User',
 		'write': 1
@@ -132,7 +139,7 @@
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 7,
+		'idx': 8,
 		'permlevel': 0,
 		'role': 'Maintenance Manager',
 		'submit': 1,
@@ -142,7 +149,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 8,
+		'idx': 9,
 		'permlevel': 1,
 		'role': 'Maintenance Manager'
 	},
@@ -153,7 +160,7 @@
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 9,
+		'idx': 10,
 		'permlevel': 0,
 		'role': 'Maintenance User',
 		'submit': 1,
@@ -163,7 +170,7 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 10,
+		'idx': 11,
 		'permlevel': 1,
 		'role': 'Maintenance User'
 	},
@@ -204,7 +211,7 @@
 		'no_copy': 1,
 		'oldfieldname': 'naming_series',
 		'oldfieldtype': 'Select',
-		'options': 'SO\nSO/10-11/',
+		'options': 'PI/2011/\nSO\nSO/10-11/\nSO1112',
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1
@@ -504,7 +511,7 @@
 		'fieldtype': 'Currency',
 		'idx': 23,
 		'in_filter': 1,
-		'label': '% Qty Billed',
+		'label': '% Amount Billed',
 		'no_copy': 1,
 		'oldfieldname': 'per_billed',
 		'oldfieldtype': 'Currency',
@@ -607,12 +614,22 @@
 
 	# DocField
 	{
+		'doctype': 'DocField',
+		'fieldname': 'vehicle_detail',
+		'fieldtype': 'Small Text',
+		'idx': 30,
+		'label': 'Vehicle Detail',
+		'permlevel': 0
+	},
+
+	# DocField
+	{
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldname': 'quotation_date',
 		'fieldtype': 'Date',
 		'hidden': 1,
-		'idx': 30,
+		'idx': 31,
 		'label': 'Quotation Date',
 		'no_copy': 0,
 		'oldfieldname': 'quotation_date',
@@ -627,7 +644,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 31,
+		'idx': 32,
 		'label': 'Pull Quotation Details',
 		'oldfieldtype': 'Button',
 		'options': 'pull_quotation_details',
@@ -642,7 +659,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'price_list_name',
 		'fieldtype': 'Select',
-		'idx': 32,
+		'idx': 33,
 		'label': 'Price List',
 		'oldfieldname': 'price_list_name',
 		'oldfieldtype': 'Select',
@@ -658,7 +675,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 33,
+		'idx': 34,
 		'permlevel': 0,
 		'width': '50%'
 	},
@@ -670,7 +687,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'currency',
 		'fieldtype': 'Select',
-		'idx': 34,
+		'idx': 35,
 		'label': 'Currency',
 		'oldfieldname': 'currency',
 		'oldfieldtype': 'Select',
@@ -689,7 +706,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'conversion_rate',
 		'fieldtype': 'Currency',
-		'idx': 35,
+		'idx': 36,
 		'label': 'Conversion Rate',
 		'oldfieldname': 'conversion_rate',
 		'oldfieldtype': 'Currency',
@@ -704,7 +721,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 36,
+		'idx': 37,
 		'permlevel': 0
 	},
 
@@ -715,7 +732,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_order_details',
 		'fieldtype': 'Table',
-		'idx': 37,
+		'idx': 38,
 		'label': 'Sales Order Details',
 		'oldfieldname': 'sales_order_details',
 		'oldfieldtype': 'Table',
@@ -729,7 +746,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 38,
+		'idx': 39,
 		'label': 'Clear Table',
 		'oldfieldtype': 'Button',
 		'options': 'clear_sales_order_details',
@@ -741,7 +758,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 39,
+		'idx': 40,
 		'label': 'Re-Calculate Values',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -755,7 +772,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'net_total',
 		'fieldtype': 'Currency',
-		'idx': 40,
+		'idx': 41,
 		'label': 'Net Total*',
 		'oldfieldname': 'net_total',
 		'oldfieldtype': 'Currency',
@@ -770,7 +787,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 41,
+		'idx': 42,
 		'label': 'Note1',
 		'oldfieldtype': 'HTML',
 		'options': '<b>NOTE :</b> * In Base Currency',
@@ -783,7 +800,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 42,
+		'idx': 43,
 		'label': 'Taxes',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -795,7 +812,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'charge',
 		'fieldtype': 'Link',
-		'idx': 43,
+		'idx': 44,
 		'label': 'Select Charges Master',
 		'oldfieldname': 'charge',
 		'oldfieldtype': 'Link',
@@ -808,7 +825,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 44,
+		'idx': 45,
 		'label': 'Get Charges',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -820,7 +837,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'other_charges',
 		'fieldtype': 'Table',
-		'idx': 45,
+		'idx': 46,
 		'label': 'Other Charges',
 		'oldfieldname': 'other_charges',
 		'oldfieldtype': 'Table',
@@ -832,7 +849,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 46,
+		'idx': 47,
 		'label': 'Calculate Charges',
 		'oldfieldtype': 'Button',
 		'permlevel': 0,
@@ -845,7 +862,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'other_charges_total',
 		'fieldtype': 'Currency',
-		'idx': 47,
+		'idx': 48,
 		'label': 'Charges Total*',
 		'oldfieldname': 'other_charges_total',
 		'oldfieldtype': 'Currency',
@@ -859,7 +876,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'grand_total',
 		'fieldtype': 'Currency',
-		'idx': 48,
+		'idx': 49,
 		'label': 'Grand Total*',
 		'oldfieldname': 'grand_total',
 		'oldfieldtype': 'Currency',
@@ -873,7 +890,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 49,
+		'idx': 50,
 		'label': 'OT Notes',
 		'oldfieldtype': 'HTML',
 		'options': '<b>NOTE :</b> * In Base Currency',
@@ -885,7 +902,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 50,
+		'idx': 51,
 		'label': 'Other Charges Calculation',
 		'oldfieldtype': 'HTML',
 		'permlevel': 0,
@@ -897,7 +914,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 51,
+		'idx': 52,
 		'label': 'Totals',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -909,7 +926,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'rounded_total',
 		'fieldtype': 'Currency',
-		'idx': 52,
+		'idx': 53,
 		'label': 'Rounded Total',
 		'oldfieldname': 'rounded_total',
 		'oldfieldtype': 'Currency',
@@ -925,7 +942,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'in_words',
 		'fieldtype': 'Data',
-		'idx': 53,
+		'idx': 54,
 		'label': 'In Words',
 		'oldfieldname': 'in_words',
 		'oldfieldtype': 'Data',
@@ -938,7 +955,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 54,
+		'idx': 55,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -950,7 +967,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'grand_total_export',
 		'fieldtype': 'Currency',
-		'idx': 55,
+		'idx': 56,
 		'label': 'Grand Total (Export)',
 		'oldfieldname': 'grand_total_export',
 		'oldfieldtype': 'Currency',
@@ -965,7 +982,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'rounded_total_export',
 		'fieldtype': 'Currency',
-		'idx': 56,
+		'idx': 57,
 		'label': 'Rounded Total (Export)',
 		'oldfieldname': 'rounded_total_export',
 		'oldfieldtype': 'Currency',
@@ -981,7 +998,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'in_words_export',
 		'fieldtype': 'Data',
-		'idx': 57,
+		'idx': 58,
 		'label': 'In Words (Export)',
 		'oldfieldname': 'in_words_export',
 		'oldfieldtype': 'Data',
@@ -995,7 +1012,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 58,
+		'idx': 59,
 		'label': 'Terms',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1007,7 +1024,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'tc_name',
 		'fieldtype': 'Link',
-		'idx': 59,
+		'idx': 60,
 		'label': 'Select Terms',
 		'oldfieldname': 'tc_name',
 		'oldfieldtype': 'Link',
@@ -1021,7 +1038,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 60,
+		'idx': 61,
 		'label': 'Get Terms',
 		'oldfieldtype': 'Button',
 		'options': 'get_tc_details',
@@ -1033,7 +1050,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 61,
+		'idx': 62,
 		'label': 'Terms HTML',
 		'oldfieldtype': 'HTML',
 		'options': 'You can add Terms and Notes that will be printed in the Transaction',
@@ -1046,7 +1063,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'terms',
 		'fieldtype': 'Text Editor',
-		'idx': 62,
+		'idx': 63,
 		'label': 'Term Details',
 		'oldfieldname': 'terms',
 		'oldfieldtype': 'Text Editor',
@@ -1060,7 +1077,7 @@
 		'description': 'Filling in additional information about the Sales Order will help you analyze your data better.',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 63,
+		'idx': 64,
 		'label': 'More Info',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1071,7 +1088,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 64,
+		'idx': 65,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -1084,7 +1101,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'letter_head',
 		'fieldtype': 'Select',
-		'idx': 65,
+		'idx': 66,
 		'label': 'Letter Head',
 		'oldfieldname': 'letter_head',
 		'oldfieldtype': 'Select',
@@ -1100,7 +1117,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'company',
 		'fieldtype': 'Link',
-		'idx': 66,
+		'idx': 67,
 		'in_filter': 1,
 		'label': 'Company',
 		'oldfieldname': 'company',
@@ -1119,7 +1136,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'fiscal_year',
 		'fieldtype': 'Select',
-		'idx': 67,
+		'idx': 68,
 		'in_filter': 1,
 		'label': 'Fiscal Year',
 		'oldfieldname': 'fiscal_year',
@@ -1139,7 +1156,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'select_print_heading',
 		'fieldtype': 'Link',
-		'idx': 68,
+		'idx': 69,
 		'label': 'Select Print Heading',
 		'no_copy': 1,
 		'oldfieldname': 'select_print_heading',
@@ -1154,7 +1171,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 69,
+		'idx': 70,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 0,
 		'print_hide': 1,
@@ -1167,7 +1184,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'source',
 		'fieldtype': 'Select',
-		'idx': 70,
+		'idx': 71,
 		'label': 'Source',
 		'oldfieldname': 'source',
 		'oldfieldtype': 'Select',
@@ -1183,7 +1200,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'campaign',
 		'fieldtype': 'Link',
-		'idx': 71,
+		'idx': 72,
 		'label': 'Campaign',
 		'oldfieldname': 'campaign',
 		'oldfieldtype': 'Link',
@@ -1198,7 +1215,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'note',
 		'fieldtype': 'Text',
-		'idx': 72,
+		'idx': 73,
 		'label': 'Note',
 		'oldfieldname': 'note',
 		'oldfieldtype': 'Text',
@@ -1213,7 +1230,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'cancel_reason',
 		'fieldtype': 'Data',
-		'idx': 73,
+		'idx': 74,
 		'label': 'Cancel Reason',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1229,7 +1246,7 @@
 		'fieldname': 'delivery_status',
 		'fieldtype': 'Select',
 		'hidden': 1,
-		'idx': 74,
+		'idx': 75,
 		'label': 'Delivery Status',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1244,7 +1261,7 @@
 		'fieldname': 'billing_status',
 		'fieldtype': 'Select',
 		'hidden': 1,
-		'idx': 75,
+		'idx': 76,
 		'label': 'Billing Status',
 		'no_column': 0,
 		'no_copy': 1,
@@ -1260,7 +1277,7 @@
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
 		'hidden': 0,
-		'idx': 76,
+		'idx': 77,
 		'label': 'Packing List',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1273,7 +1290,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'packing_details',
 		'fieldtype': 'Table',
-		'idx': 77,
+		'idx': 78,
 		'label': 'Packing Details',
 		'oldfieldname': 'packing_details',
 		'oldfieldtype': 'Table',
@@ -1286,7 +1303,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 78,
+		'idx': 79,
 		'label': 'Sales Team',
 		'oldfieldtype': 'Section Break',
 		'permlevel': 0,
@@ -1300,7 +1317,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_partner',
 		'fieldtype': 'Link',
-		'idx': 79,
+		'idx': 80,
 		'in_filter': 1,
 		'label': 'Sales Partner',
 		'oldfieldname': 'sales_partner',
@@ -1318,7 +1335,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'commission_rate',
 		'fieldtype': 'Currency',
-		'idx': 80,
+		'idx': 81,
 		'label': 'Commission Rate',
 		'oldfieldname': 'commission_rate',
 		'oldfieldtype': 'Currency',
@@ -1333,7 +1350,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'total_commission',
 		'fieldtype': 'Currency',
-		'idx': 81,
+		'idx': 82,
 		'label': 'Total Commission',
 		'oldfieldname': 'total_commission',
 		'oldfieldtype': 'Currency',
@@ -1347,7 +1364,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'sales_team',
 		'fieldtype': 'Table',
-		'idx': 82,
+		'idx': 83,
 		'label': 'Sales Team1',
 		'oldfieldname': 'sales_team',
 		'oldfieldtype': 'Table',
@@ -1361,7 +1378,7 @@
 		'allow_on_submit': 1,
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 83,
+		'idx': 84,
 		'label': 'Repair Sales Order',
 		'oldfieldtype': 'Button',
 		'options': 'repair_sales_order',
diff --git a/selling/doctype/sales_order_detail/sales_order_detail.txt b/selling/doctype/sales_order_detail/sales_order_detail.txt
index e89768c..7e46d74 100644
--- a/selling/doctype/sales_order_detail/sales_order_detail.txt
+++ b/selling/doctype/sales_order_detail/sales_order_detail.txt
@@ -394,7 +394,7 @@
 		'options': 'Brand',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -410,7 +410,7 @@
 		'options': 'Item Group',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/authorization_rule/authorization_rule.txt b/setup/doctype/authorization_rule/authorization_rule.txt
index ef20f36..a436495 100644
--- a/setup/doctype/authorization_rule/authorization_rule.txt
+++ b/setup/doctype/authorization_rule/authorization_rule.txt
@@ -79,7 +79,8 @@
 		'oldfieldname': 'company',
 		'oldfieldtype': 'Link',
 		'options': 'Company',
-		'reqd': 0
+		'reqd': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -157,7 +158,8 @@
 		'label': 'Applicable To (Employee)',
 		'oldfieldname': 'to_emp',
 		'oldfieldtype': 'Link',
-		'options': 'Employee'
+		'options': 'Employee',
+		'search_index': 0
 	},
 
 	# DocField
@@ -171,7 +173,8 @@
 		'label': 'Applicable To (Designation)',
 		'oldfieldname': 'to_designation',
 		'oldfieldtype': 'Link',
-		'options': 'Designation'
+		'options': 'Designation',
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/company/company.js b/setup/doctype/company/company.js
index e27052c..c82b95c 100644
--- a/setup/doctype/company/company.js
+++ b/setup/doctype/company/company.js
@@ -2,6 +2,32 @@
   if(doc.abbr && !doc.__islocal) set_field_permlevel('abbr',1);
 }
 
+cur_frm.cscript.has_special_chars = function(t) {
+  var iChars = "!@#$%^*+=-[]\\\';,/{}|\":<>?";
+  for (var i = 0; i < t.length; i++) {
+    if (iChars.indexOf(t.charAt(i)) != -1) {
+      return true;
+    }
+  }
+  return false;
+}
+
+cur_frm.cscript.company_name = function(doc){
+  if(doc.company_name && cur_frm.cscript.has_special_chars(doc.company_name)){   
+    msgprint("<font color=red>Special Characters <b>! @ # $ % ^ * + = - [ ] ' ; , / { } | : < > ?</b> are not allowed for</font>\nCompany Name <b>" + doc.company_name +"</b>")        
+    doc.company_name = '';
+    refresh_field('company_name');
+  }
+}
+
+cur_frm.cscript.abbr = function(doc){
+  if(doc.abbr && cur_frm.cscript.has_special_chars(doc.abbr)){   
+    msgprint("<font color=red>Special Characters <b>! @ # $ % ^ * + = - [ ] ' ; , / { } | : < > ?</b> are not allowed for</font>\nAbbr <b>" + doc.abbr +"</b>")        
+    doc.abbr = '';
+    refresh_field('abbr');
+  }
+}
+
 cur_frm.fields_dict.default_bank_account.get_query = function(doc) {    
   return 'SELECT `tabAccount`.name, `tabAccount`.debit_or_credit, `tabAccount`.group_or_ledger FROM `tabAccount` WHERE `tabAccount`.company = "'+doc.name+'" AND `tabAccount`.group_or_ledger = "Ledger" AND `tabAccount`.docstatus != 2 AND `tabAccount`.account_type = "Bank or Cash" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name LIMIT 50';   
 }
diff --git a/setup/doctype/company/company.txt b/setup/doctype/company/company.txt
index a7498d6..15ba781 100644
--- a/setup/doctype/company/company.txt
+++ b/setup/doctype/company/company.txt
@@ -5,7 +5,7 @@
 	{
 		'creation': '2010-08-08 17:08:55',
 		'docstatus': 0,
-		'modified': '2011-07-06 11:42:34',
+		'modified': '2011-07-01 17:43:29',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
diff --git a/setup/doctype/email_settings/email_settings.py b/setup/doctype/email_settings/email_settings.py
index 12c2464..ef0a763 100644
--- a/setup/doctype/email_settings/email_settings.py
+++ b/setup/doctype/email_settings/email_settings.py
@@ -1,44 +1,42 @@
-# Please edit this list and import only required elements
 import webnotes
-
-from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
-from webnotes.model import db_exists
-from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
-from webnotes.model.doclist import getlist, copy_doclist
-from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
-from webnotes import session, form, is_testing, msgprint, errprint
-
-set = webnotes.conn.set
 sql = webnotes.conn.sql
-get_value = webnotes.conn.get_value
-in_transaction = webnotes.conn.in_transaction
-convert_to_lists = webnotes.conn.convert_to_lists
 	
-# -----------------------------------------------------------------------------------------
-
+from webnotes.utils import cint, cstr
 
 class DocType:
-  def __init__(self,doc,doclist):
-    self.doc,self.doclist = doc,doclist
+	def __init__(self,doc,doclist):
+		self.doc,self.doclist = doc,doclist
 
-  def set_vals(self):
-    res = sql("select field, value from `tabSingles` where doctype = 'Control Panel' and field IN ('outgoing_mail_server','mail_login','mail_password','auto_email_id','mail_port','use_ssl')")
-    ret = {}
-    for r in res:
-      ret[cstr(r[0])]=r[1] and cstr(r[1]) or ''
-        
-    return str(ret)
+	def set_vals(self):
+		res = sql("select field, value from `tabSingles` where doctype = 'Control Panel' and field IN ('outgoing_mail_server','mail_login','mail_password','auto_email_id','mail_port','use_ssl')")
+		ret = {}
+		for r in res:
+			ret[cstr(r[0])]=r[1] and cstr(r[1]) or ''
+				
+		return ret
 
-  def on_update(self):
-    if self.doc.outgoing_mail_server:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'outgoing_mail_server'"%self.doc.outgoing_mail_server)
-    if self.doc.mail_login:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'mail_login'"%self.doc.mail_login)
-    if self.doc.mail_password:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'mail_password'"%self.doc.mail_password)
-    if self.doc.auto_email_id:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'auto_email_id'"%self.doc.auto_email_id)
-    if self.doc.mail_port:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'mail_port'"%self.doc.mail_port)
-    if self.doc.use_ssl:
-      sql("update `tabSingles` set value ='%s' where doctype = 'Control Panel' and field = 'use_ssl'"%self.doc.use_ssl)
\ No newline at end of file
+	def set_cp_value(self, key):
+		"""
+			Update value in control panel
+		"""
+		if self.doc.fields.get(key):
+			webnotes.conn.set_value('Control Panel', None, key, self.doc.fields[key])
+		
+	def on_update(self):
+		"""
+			Sets or cancels the event in the scheduler
+		"""
+		# update control panel
+		for f in ('outgoing_mail_server', 'mail_login', 'mail_password', 'auto_email_id', 'mail_port', 'use_ssl'):
+			self.set_cp_value(f)
+
+		# setup scheduler for support emails
+		if cint(self.doc.sync_support_mails):
+			if not (self.doc.support_host and self.doc.support_username and self.doc.support_password):
+				webnotes.msgprint("You must give the incoming POP3 settings for support emails to activiate mailbox integration", raise_exception=1)
+			
+			from webnotes.utils.scheduler import set_event
+			set_event('support.doctype.support_ticket.get_support_mails', 60*5, 1)
+		else:
+			from webnotes.utils.scheduler import cancel_event
+			cancel_event('support.doctype.support_ticket.get_support_mails')
\ No newline at end of file
diff --git a/setup/doctype/email_settings/email_settings.txt b/setup/doctype/email_settings/email_settings.txt
index 31bc932..ef6efe6 100644
--- a/setup/doctype/email_settings/email_settings.txt
+++ b/setup/doctype/email_settings/email_settings.txt
@@ -5,14 +5,14 @@
 	{
 		'creation': '2010-08-08 17:08:59',
 		'docstatus': 0,
-		'modified': '2011-01-04 11:21:25',
-		'modified_by': 'umair@iwebnotes.com',
+		'modified': '2011-07-25 15:03:51',
+		'modified_by': 'Administrator',
 		'owner': 'harshada@webnotestech.com'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1307707462',
+		'_last_update': '1311586371',
 		'allow_copy': 1,
 		'allow_email': 1,
 		'allow_print': 1,
@@ -24,7 +24,7 @@
 		'name': '__common__',
 		'section_style': 'Simple',
 		'server_code_error': ' ',
-		'version': 27
+		'version': 34
 	},
 
 	# These values are common for all DocField
@@ -72,9 +72,26 @@
 	# DocField
 	{
 		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 1,
+		'label': 'Outgoing Mails'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'HTML',
+		'idx': 2,
+		'label': '1',
+		'options': '<div class="help_box">Set your outgoing mail settings here. All system generated notifications, emails will go from this mail server</div>'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
 		'fieldname': 'outgoing_mail_server',
 		'fieldtype': 'Data',
-		'idx': 1,
+		'idx': 3,
 		'label': 'Outgoing Mail Server'
 	},
 
@@ -83,7 +100,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'mail_port',
 		'fieldtype': 'Data',
-		'idx': 2,
+		'idx': 4,
 		'label': 'Mail Port'
 	},
 
@@ -92,7 +109,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'use_ssl',
 		'fieldtype': 'Check',
-		'idx': 3,
+		'idx': 5,
 		'label': 'Use SSL'
 	},
 
@@ -101,7 +118,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'mail_login',
 		'fieldtype': 'Data',
-		'idx': 4,
+		'idx': 6,
 		'label': 'Login Id'
 	},
 
@@ -110,7 +127,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'mail_password',
 		'fieldtype': 'Password',
-		'idx': 5,
+		'idx': 7,
 		'label': 'Mail Password'
 	},
 
@@ -119,7 +136,122 @@
 		'doctype': 'DocField',
 		'fieldname': 'auto_email_id',
 		'fieldtype': 'Data',
-		'idx': 6,
+		'idx': 8,
 		'label': 'Auto Email Id'
+	},
+
+	# DocField
+	{
+		'description': 'Set the POP3 email settings to pull emails directly from a mailbox and create Support Tickets',
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 9,
+		'label': 'Support Ticket Mail Settings'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'HTML',
+		'idx': 10,
+		'label': '2',
+		'options': '<div class="help_box">To automatically create Support Tickets from your incoming mail, set your pop3 settings here.</div>'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Section Break',
+		'idx': 11,
+		'options': 'Simple'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Check this to pull emails from your mailbox',
+		'doctype': 'DocField',
+		'fieldname': 'sync_support_mails',
+		'fieldtype': 'Check',
+		'idx': 12,
+		'label': 'Sync Support Mails'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Your support email id - must be a valid email - this is where your emails will come!',
+		'doctype': 'DocField',
+		'fieldname': 'support_email',
+		'fieldtype': 'Data',
+		'idx': 13,
+		'label': 'Support Email'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'POP3 mail server (e.g. pop.gmail.com)',
+		'doctype': 'DocField',
+		'fieldname': 'support_host',
+		'fieldtype': 'Data',
+		'idx': 14,
+		'label': 'POP3 Mail Server'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'support_use_ssl',
+		'fieldtype': 'Check',
+		'idx': 15,
+		'label': 'Use SSL'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'support_username',
+		'fieldtype': 'Data',
+		'idx': 16,
+		'label': 'User Name'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'support_password',
+		'fieldtype': 'Password',
+		'idx': 17,
+		'label': 'Support Password'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Column Break',
+		'idx': 18
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Signature to be appended at the end of every email',
+		'doctype': 'DocField',
+		'fieldname': 'support_signature',
+		'fieldtype': 'Text',
+		'idx': 19,
+		'label': 'Signature'
+	},
+
+	# DocField
+	{
+		'colour': 'White:FFF',
+		'description': 'Autoreply when a new mail is received',
+		'doctype': 'DocField',
+		'fieldname': 'support_autoreply',
+		'fieldtype': 'Text',
+		'idx': 20,
+		'label': 'Autoreply'
 	}
 ]
\ No newline at end of file
diff --git a/setup/doctype/naming_series_options/naming_series_options.txt b/setup/doctype/naming_series_options/naming_series_options.txt
index f30686d..b964556 100644
--- a/setup/doctype/naming_series_options/naming_series_options.txt
+++ b/setup/doctype/naming_series_options/naming_series_options.txt
@@ -66,7 +66,8 @@
 		'idx': 1,
 		'label': 'Doc Type',
 		'oldfieldname': 'doc_type',
-		'oldfieldtype': 'Data'
+		'oldfieldtype': 'Data',
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/setup/doctype/other_charges/other_charges.txt b/setup/doctype/other_charges/other_charges.txt
index b9908fc..ac9c6c5 100644
--- a/setup/doctype/other_charges/other_charges.txt
+++ b/setup/doctype/other_charges/other_charges.txt
@@ -160,7 +160,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -186,7 +186,7 @@
 		'options': 'Company',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/personalize/personalize.py b/setup/doctype/personalize/personalize.py
index 6a15102..3264546 100644
--- a/setup/doctype/personalize/personalize.py
+++ b/setup/doctype/personalize/personalize.py
@@ -28,4 +28,4 @@
 	#
 	def set_html_from_image(self):
 		file_name = self.doc.file_list.split(',')[0]
-		self.doc.header_html = '<div><img src="cgi-bin/getfile.cgi?name=' + file_name + '"/></div>'
+		self.doc.header_html = '<div><img style="max-height: 120px; max-width: 600px" src="index.cgi?cmd=get_file&fname=' + file_name + '"/></div>'
diff --git a/setup/doctype/sales_partner/sales_partner.txt b/setup/doctype/sales_partner/sales_partner.txt
index a61a9fb..18b3abb 100644
--- a/setup/doctype/sales_partner/sales_partner.txt
+++ b/setup/doctype/sales_partner/sales_partner.txt
@@ -191,7 +191,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nChannel Partner\nDistributor\nDealer\nAgent\nRetailer\nImplementation Partner\nReseller',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/sales_person/sales_person.txt b/setup/doctype/sales_person/sales_person.txt
index 0ffcd74..0680c38 100644
--- a/setup/doctype/sales_person/sales_person.txt
+++ b/setup/doctype/sales_person/sales_person.txt
@@ -156,7 +156,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -281,7 +281,7 @@
 		'oldfieldtype': 'Select',
 		'options': 'link:Country',
 		'permlevel': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -297,7 +297,7 @@
 		'oldfieldtype': 'Select',
 		'options': 'link:State',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -324,7 +324,8 @@
 		'oldfieldname': 'territory',
 		'oldfieldtype': 'Link',
 		'options': 'Territory',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -397,7 +398,8 @@
 		'oldfieldname': 'distribution_id',
 		'oldfieldtype': 'Link',
 		'options': 'Budget Distribution',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/setup_control/setup_control.py b/setup/doctype/setup_control/setup_control.py
index e01e60a..61e3a82 100644
--- a/setup/doctype/setup_control/setup_control.py
+++ b/setup/doctype/setup_control/setup_control.py
@@ -13,7 +13,6 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-
 	
 # -----------------------------------------------------------------------------------------
 
@@ -37,9 +36,11 @@
 	#-----------------------
 	def set_account_details(self, args):
 		args = eval(args)
-		#webnotes.logger.error("args in set_account_details of setup_control: " + str(args))
+
 		self.set_cp_defaults(args['company'], args['industry'], args['time_zone'], args['country'], args['account_name'])
 		self.create_profile(args['user'], args['first_name'], args['last_name'])	
+	
+		from server_tools.gateway_utils import update_client_control
 		update_client_control(args['total_users'])
 		
 	
@@ -182,7 +183,7 @@
 		Validates if setup has been performed after database allocation
 		"""
 
-		from server_tools.gateway_utils import update_client_control, get_total_users
+		from server_tools.gateway_utils import get_total_users
 		
 		args = eval(args)
 		#webnotes.logger.error("args in set_account_details of setup_control: " + str(args))
diff --git a/setup/doctype/support_email_settings/support_email_settings.py b/setup/doctype/support_email_settings/support_email_settings.py
deleted file mode 100644
index 44d8735..0000000
--- a/setup/doctype/support_email_settings/support_email_settings.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import webnotes
-from webnotes.utils import cint
-
-class DocType:
-	def __init__(self,dt,dn):
-		self.doc, self.doctype = dt,dn
-		
-	def on_update(self):
-		"""
-			Sets or cancels the event in the scheduler
-		"""
-		if cint(self.doc.integrate_incoming):
-			from webnotes.utils.scheduler import set_event
-			set_event('support.doctype.support_ticket.get_support_mails', 60*5, 1)
-		else:
-			from webnotes.utils.scheduler import cancel_event
-			cancel_event('support.doctype.support_ticket.get_support_mails')
-			
diff --git a/setup/doctype/support_email_settings/support_email_settings.txt b/setup/doctype/support_email_settings/support_email_settings.txt
deleted file mode 100644
index 6079567..0000000
--- a/setup/doctype/support_email_settings/support_email_settings.txt
+++ /dev/null
@@ -1,144 +0,0 @@
-# DocType, Support Email Settings
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2011-05-23 14:50:45',
-		'docstatus': 0,
-		'modified': '2011-05-28 09:25:53',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
-	},
-
-	# These values are common for all DocType
-	{
-		'_last_update': '1306554355',
-		'colour': 'White:FFF',
-		'doctype': 'DocType',
-		'in_dialog': 1,
-		'issingle': 1,
-		'module': 'Setup',
-		'name': '__common__',
-		'read_only': 1,
-		'section_style': 'Simple',
-		'show_in_menu': 1,
-		'version': 8
-	},
-
-	# These values are common for all DocField
-	{
-		'doctype': 'DocField',
-		'name': '__common__',
-		'parent': 'Support Email Settings',
-		'parentfield': 'fields',
-		'parenttype': 'DocType',
-		'permlevel': 0
-	},
-
-	# These values are common for all DocPerm
-	{
-		'create': 1,
-		'doctype': 'DocPerm',
-		'idx': 1,
-		'name': '__common__',
-		'parent': 'Support Email Settings',
-		'parentfield': 'permissions',
-		'parenttype': 'DocType',
-		'permlevel': 0,
-		'read': 1,
-		'role': 'System Manager',
-		'write': 1
-	},
-
-	# DocType, Support Email Settings
-	{
-		'doctype': 'DocType',
-		'name': 'Support Email Settings'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'description': 'The full email id of your incoming support emails',
-		'doctype': 'DocField',
-		'fieldname': 'email',
-		'fieldtype': 'Data',
-		'idx': 1,
-		'label': 'Email',
-		'options': 'Email'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'description': 'By checking this, your incoming mails will automatically be integrated with the Support Ticket',
-		'doctype': 'DocField',
-		'fieldname': 'integrate_incoming',
-		'fieldtype': 'Check',
-		'idx': 2,
-		'label': 'Integrate Incoming'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'description': 'Signature appended to the outgoing email (Text / HTML)',
-		'doctype': 'DocField',
-		'fieldname': 'signature',
-		'fieldtype': 'Text',
-		'idx': 3,
-		'label': 'Signature'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldtype': 'Column Break',
-		'idx': 4
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'use_ssl',
-		'fieldtype': 'Check',
-		'idx': 5,
-		'label': 'Use SSL'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'description': 'eg. pop.gmail.com',
-		'doctype': 'DocField',
-		'fieldname': 'host',
-		'fieldtype': 'Data',
-		'idx': 6,
-		'label': 'Host'
-	},
-
-	# DocField
-	{
-		'colour': 'White:FFF',
-		'description': 'Support Email Id',
-		'doctype': 'DocField',
-		'fieldname': 'username',
-		'fieldtype': 'Data',
-		'idx': 7,
-		'label': 'Username'
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
-		'fieldname': 'password',
-		'fieldtype': 'Password',
-		'idx': 8,
-		'label': 'Password'
-	}
-]
\ No newline at end of file
diff --git a/setup/doctype/term/term.txt b/setup/doctype/term/term.txt
index f169780..fe3bd75 100644
--- a/setup/doctype/term/term.txt
+++ b/setup/doctype/term/term.txt
@@ -155,7 +155,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/territory/territory.txt b/setup/doctype/territory/territory.txt
index 0bf94f3..a4de2d6 100644
--- a/setup/doctype/territory/territory.txt
+++ b/setup/doctype/territory/territory.txt
@@ -160,7 +160,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Sales Person',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -267,7 +267,8 @@
 		'oldfieldname': 'distribution_id',
 		'oldfieldtype': 'Link',
 		'options': 'Budget Distribution',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/doctype/support_email_settings/__init__.py b/setup/doctype/upload_accounts_transactions/__init__.py
similarity index 100%
rename from setup/doctype/support_email_settings/__init__.py
rename to setup/doctype/upload_accounts_transactions/__init__.py
diff --git a/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.js b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.js
new file mode 100644
index 0000000..041638f
--- /dev/null
+++ b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.js
@@ -0,0 +1,18 @@
+
+//--------- ONLOAD -------------
+cur_frm.cscript.onload = function(doc, cdt, cdn) {
+}
+
+cur_frm.cscript.refresh = function(doc, cdt, cdn) {
+	if(!doc.file_list) {
+		set_field_options('Upload Accounts Transactions Help', '<div class="help_box">To upload transactions, please attach a (.csv) file with 5 columns - <b>Date, Transaction Number, Account, Debit Amount, Credit Amount</b> (no headings necessary). See attachments box in the right column</div>')
+	} else {
+		set_field_options('Upload Accounts Transactions Help', '<div class="help_box">To update transactions from the attachment, please click on "Upload Accounts Transactions"</div>')
+	}
+}
+
+cur_frm.cscript['Upload Accounts Transactions'] = function(doc, cdt, cdn) {
+	if(confirm("This action will append all transactions and cannot be un-done. Are you sure you want to continue?")) {
+		$c_obj([doc], 'upload_accounts_transactions', '', function(r, rt) { });
+	}
+}
diff --git a/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py
new file mode 100644
index 0000000..2028e5f
--- /dev/null
+++ b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.py
@@ -0,0 +1,103 @@
+# Please edit this list and import only required elements
+import webnotes
+
+from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
+from webnotes.model import db_exists
+from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
+from webnotes.model.doclist import getlist, copy_doclist
+from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
+from webnotes import session, form, is_testing, msgprint, errprint
+
+set = webnotes.conn.set
+sql = webnotes.conn.sql
+get_value = webnotes.conn.get_value
+in_transaction = webnotes.conn.in_transaction
+convert_to_lists = webnotes.conn.convert_to_lists
+
+# -----------------------------------------------------------------------------------------
+
+class DocType:
+	def __init__(self, d, dl):
+		self.doc, self.doclist = d, dl
+		self.cl = []
+
+	# upload transactions
+	def upload_accounts_transactions(self):
+		import csv
+		data = csv.reader(self.get_csv_data().splitlines())
+
+		abbr = sql("select concat(' - ',abbr) as abbr from tabCompany where name=%s",self.doc.company)
+		updated = 0
+		jv_name=''
+#		jv = Document('Journal Voucher')
+		global line,jv,name,jv_go
+		for line in data:
+			if len(line)>=7: #Minimum no of fields
+				if line[3]!=jv_name: #Create JV
+					if jv_name!='':
+						jv_go = get_obj('Journal Voucher',name, with_children=1)
+						jv_go.validate()
+						jv_go.on_submit()
+
+					jv_name=line[3]
+					jv = Document('Journal Voucher')
+					jv.voucher_type = line[0]
+					jv.naming_series = line[1]
+					jv.voucher_date = formatdate(line[2])
+					jv.posting_date = formatdate(line[2])
+#					jv.name = line[3]
+					jv.fiscal_year = self.doc.fiscal_year
+					jv.company = self.doc.company
+					jv.remark = len(line)==8 and line[3]+' '+line[7] or line[3]+' Uploaded Record'
+					jv.docstatus=1
+					jv.save(1)
+					name=jv.name
+
+					jc = addchild(jv,'entries','Journal Voucher Detail',0)
+					jc.account = line[4]+abbr[0][0]
+					jc.cost_center=len(line)==9 and line[8] or self.doc.default_cost_center
+					if line[5]!='':
+						jc.debit = line[5]
+					else:
+						jc.credit = line[6]
+					jc.save()
+
+				else: #Create JV Child
+					jc = addchild(jv,'entries','Journal Voucher Detail',0)
+					jc.account = line[4]+abbr[0][0]
+					jc.cost_center=len(line)==9 and line[8] or self.doc.default_cost_center
+					if line[5]!='':
+						jc.debit = line[5]
+					else:
+						jc.credit = line[6]
+					jc.save()
+			else:
+				msgprint("[Ignored] Incorrect format: %s" % str(line))
+		if jv_name!='':
+			jv_go = get_obj('Journal Voucher',name, with_children=1)
+			jv_go.validate()
+			jv_go.on_submit()
+
+		msgprint("<b>%s</b> items updated" % updated)
+
+	# clear prices
+	def clear_prices(self):
+		cnt = sql("select count(*) from `tabRef Rate Detail` where price_list_name = %s", self.doc.name)
+		sql("delete from `tabRef Rate Detail` where price_list_name = %s", self.doc.name)
+		msgprint("%s prices cleared" % cnt[0][0])
+
+	# Update CSV data
+	def get_csv_data(self):
+		if not self.doc.file_list:
+		  msgprint("File not attached!")
+		  raise Exception
+
+		fid = self.doc.file_list.split(',')[1]
+
+		from webnotes.utils import file_manager
+		fn, content = file_manager.get_file(fid)
+
+		if not type(content) == str:
+		  content = content.tostring()
+
+		return content
diff --git a/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.txt b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.txt
new file mode 100644
index 0000000..d637a88
--- /dev/null
+++ b/setup/doctype/upload_accounts_transactions/upload_accounts_transactions.txt
@@ -0,0 +1,126 @@
+# DocType, Upload Accounts Transactions
+[
+
+	# These values are common in all dictionaries
+	{
+		'creation': '2011-07-18 14:56:48',
+		'docstatus': 0,
+		'modified': '2011-07-19 12:19:13',
+		'modified_by': 'Administrator',
+		'owner': 'Administrator'
+	},
+
+	# These values are common for all DocType
+	{
+		'_last_update': '1310985428',
+		'allow_attach': 1,
+		'colour': 'White:FFF',
+		'doctype': 'DocType',
+		'issingle': 1,
+		'max_attachments': 1,
+		'module': 'Setup',
+		'name': '__common__',
+		'section_style': 'Simple',
+		'show_in_menu': 1,
+		'version': 5
+	},
+
+	# These values are common for all DocField
+	{
+		'doctype': 'DocField',
+		'name': '__common__',
+		'parent': 'Upload Accounts Transactions',
+		'parentfield': 'fields',
+		'parenttype': 'DocType',
+		'permlevel': 0
+	},
+
+	# These values are common for all DocPerm
+	{
+		'cancel': 1,
+		'create': 1,
+		'doctype': 'DocPerm',
+		'execute': 1,
+		'idx': 1,
+		'name': '__common__',
+		'parent': 'Upload Accounts Transactions',
+		'parentfield': 'permissions',
+		'parenttype': 'DocType',
+		'permlevel': 0,
+		'read': 1,
+		'role': 'Accounts Manager',
+		'submit': 1,
+		'write': 1
+	},
+
+	# DocType, Upload Accounts Transactions
+	{
+		'doctype': 'DocType',
+		'name': 'Upload Accounts Transactions'
+	},
+
+	# DocPerm
+	{
+		'doctype': 'DocPerm'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'HTML',
+		'idx': 1,
+		'label': 'Usage',
+		'options': '<div class="help_box">\n<b>Upload Account Transactions Help</b>\n<p>To update the account transactions, upload a CSV file with five columns Date, Transaction Number, Account Name, Credit and Debit amount and click on the "Upload Account Transactions" button. The system will add the transactions.\n</div>'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'fiscal_year',
+		'fieldtype': 'Link',
+		'idx': 2,
+		'label': 'Fiscal Year',
+		'options': 'Fiscal Year',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'company',
+		'fieldtype': 'Link',
+		'idx': 3,
+		'label': 'Company',
+		'options': 'Company',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'default_cost_center',
+		'fieldtype': 'Link',
+		'idx': 4,
+		'label': 'Default Cost Center',
+		'options': 'Cost Center',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'file_list',
+		'fieldtype': 'Small Text',
+		'hidden': 1,
+		'idx': 5,
+		'label': 'File List'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldtype': 'Button',
+		'idx': 6,
+		'label': 'Upload Accounts Transactions'
+	}
+]
\ No newline at end of file
diff --git a/setup/doctype/workflow_rule/workflow_rule.txt b/setup/doctype/workflow_rule/workflow_rule.txt
index d95a481..7c35826 100644
--- a/setup/doctype/workflow_rule/workflow_rule.txt
+++ b/setup/doctype/workflow_rule/workflow_rule.txt
@@ -106,7 +106,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nActive\nInactive',
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/setup/page/import_data/import_data.html b/setup/page/import_data/import_data.html
index a4b30f4..5b30dd2 100644
--- a/setup/page/import_data/import_data.html
+++ b/setup/page/import_data/import_data.html
@@ -32,7 +32,7 @@
 </tbody>
 </table>
 </form>
-<div style="background-color: #FFE; padding: 10px; margin: 10px;">
+<div style="background-color: #FFE; padding: 13px; margin: 17px;">
 <h3>Data Import Guide</h3>
 <ol>
 <li>Get the template of the DocType for which you want to import in CSV (Comma seperated values) format.</li>
diff --git a/setup/page/import_data/import_data.js b/setup/page/import_data/import_data.js
index aa0bdbd..f1601e7 100644
--- a/setup/page/import_data/import_data.js
+++ b/setup/page/import_data/import_data.js
@@ -1,45 +1,55 @@
 pscript['onload_Import Data'] = function() {
-  
-  //alert(profile.can_get_report);
+	
+	//alert(profile.can_get_report);
 
-  callback = function(r,rt) {
-    var h = new PageHeader('di_header','Import Data','Tool to download template and upload data');
-    var sel = $i('import_template');
-    if(r.message){
-      add_sel_options(sel, r.message);
-      sel.onchange=function(){
-        $i('child_tab_lst').innerHTML ='';
-        if(sel.value != 'Select Master...'){
-          $c_obj('Import Data Control','get_child_lst',sel.value,
-            function(r,rt){
-              var me = this;
-              $y($i('child_tab_lst'),{backgroundColor:'#EEEEEE'})
-              var desc = $a($i('child_tab_lst'), 'div', '', {padding:'8px'});
-              
-              desc.innerHTML = "<h4>Please click on following link(s) to download template.</h4>";
+	callback = function(r,rt) {
+		var h = new PageHeader('di_header','Import Data','Tool to download template and upload data');
+		var sel = $i('import_template');
+		if(r.message){
+			add_sel_options(sel, r.message);
+
+			// please collapse here when editing :)
+			sel.onchange=function(){
+				$i('child_tab_lst').innerHTML ='';
+				if(sel.value != 'Select Master...'){
+					$c_obj('Import Data Control','get_child_lst',sel.value,
+						function(r,rt){
+							var me = this;
+							$y($i('child_tab_lst'),{backgroundColor:'#EEEEEE', margin: '17px 17px', padding: '13px'})
+							var desc = $a($i('child_tab_lst'), 'div', '', {padding:'4px'});
+							
+							desc.innerHTML = "<b>Download template(s) for importing "+sel_val(sel)+"</b>";
  
-              
-              var parent = $a($i('child_tab_lst'), 'div');
-              var tab = make_table(parent,r.message.length,1,'100%',[],{padding:'8px',fontSize:'15px',borderCollapse: 'collapse'});
-              
-              for(var i=0;i<r.message.length;i++){
-                var dt= $a($td(tab,i,0), 'span', 'link_type');
-                dt.innerHTML = r.message[i];
-                dt.nm = r.message[i];
-                
-
-                dt.onclick = function(){ 
-					var ovr = $('input[name="overwrite"]:checked').length;
-                    window.location = outUrl + '?cmd=get_template&dt=' + this.nm + (ovr ? '&overwrite=1' : '');
-                }
-              }
-            }  
-          );
-        }
-      }
-    }
-  }
-  $c_obj('Import Data Control','get_master_lst','',callback);
-  
+							
+							var parent = $a($i('child_tab_lst'), 'div');
+							var tab = make_table(parent,r.message.length,1,'100%',[],{padding:'3px',borderCollapse: 'collapse'});
+							
+							for(var i=0;i<r.message.length;i++){
+								var dt= $a($td(tab,i,0), 'span', 'link_type');
+								dt.innerHTML = r.message[i];
+								dt.nm = r.message[i];
+								
+								dt.onclick = function(){ 
+									var ovr = $('input[name="overwrite"]:checked').length;
+										window.location = outUrl + '?cmd=get_template&dt=' + this.nm + (ovr ? '&overwrite=1' : '');
+								}
+							}
+						}	
+					);
+				}
+			}
+		}
+	
+		// set the default (if given in url)
+		if(window.location.hash) {
+			var to_set = window.location.hash.split('/').slice(-1)[0];
+			if(in_list(r.message, to_set)) {
+				sel.value = to_set;
+				sel.onchange();
+			}
+		}
+	}
+	$c_obj('Import Data Control','get_master_lst','',callback);
+	
 
 }
diff --git a/setup/page/setup/setup.js b/setup/page/setup/setup.js
index c0ba3d4..b29e7ad 100644
--- a/setup/page/setup/setup.js
+++ b/setup/page/setup/setup.js
@@ -183,6 +183,7 @@
     ['Country',1,'Country','','Country master'],
     ['State',1,'State','','State master'],
     ['Rename Tool',3,'Rename Tool','','Rename a record'],
+    ['Bulk Rename Tool',3,'Bulk Rename Tool','','Rename multiple records at a time'],
     ['Activty Type',1,'Activity Type','','Types of activities that you can select in your Timesheet'],
     ['City',1,'City','','City master']]};
   
diff --git a/startup/event_handlers.py b/startup/event_handlers.py
index 2bd8fae..53b979e 100644
--- a/startup/event_handlers.py
+++ b/startup/event_handlers.py
@@ -33,7 +33,7 @@
 		webnotes.conn.set_global('days_to_expiry', webnotes.form_dict.get('days_to_expiry'))
 
 	if webnotes.form_dict.get('first_name'):
-		from server_tools.server_tools.gateway_utils import update_user_details
+		from server_tools.gateway_utils import update_user_details
 		update_user_details()
 		
 #
@@ -43,6 +43,7 @@
 	# login from
 	if webnotes.form_dict.get('login_from'):
 		webnotes.session['data']['login_from'] = webnotes.form.getvalue('login_from')
+		webnotes.session_obj.update()
 
 	update_account_details()
 
@@ -51,7 +52,7 @@
 #
 def on_logout(login_manager):
 	if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
-		from server_tools.server_tools.gateway_utils import logout_sso
+		from server_tools.gateway_utils import logout_sso
 		logout_sso()
 
 #
diff --git a/startup/startup.css b/startup/startup.css
index f4fd39e..67393aa 100644
--- a/startup/startup.css
+++ b/startup/startup.css
@@ -2,7 +2,7 @@
 	background-color: #e2e2e2;
 }
 
-div.layout_wrapper {
+.layout_wrapper {
 	padding: 13px;
 	margin: 7px;
 	-moz-box-shadow: 1px 1px 6px #AAA;
diff --git a/startup/startup.js b/startup/startup.js
index a93906c..1280e0f 100644
--- a/startup/startup.js
+++ b/startup/startup.js
@@ -46,11 +46,11 @@
 	// for logout and payment
 	var callback = function(r,rt) {
 		if(r.message){
-			login_file = r.message;
+			login_file = 'http://' + r.message;
 		}
 		else {
 			
-			login_file = 'https://www.erpnext.com';
+			login_file = 'http://www.erpnext.com';
 			}
 		// setup toolbar
 		pscript.startup_setup_toolbar();
diff --git a/stock/doctype/bin/bin.txt b/stock/doctype/bin/bin.txt
index 2ecbcf0..6a40297 100644
--- a/stock/doctype/bin/bin.txt
+++ b/stock/doctype/bin/bin.txt
@@ -162,7 +162,7 @@
 		'label': 'Reserved Quantity',
 		'oldfieldname': 'reserved_qty',
 		'oldfieldtype': 'Currency',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -176,7 +176,7 @@
 		'label': 'Actual Quantity',
 		'oldfieldname': 'actual_qty',
 		'oldfieldtype': 'Currency',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -190,7 +190,7 @@
 		'label': 'Ordered Quantity',
 		'oldfieldname': 'ordered_qty',
 		'oldfieldtype': 'Currency',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -204,7 +204,7 @@
 		'label': 'Indented Quantity',
 		'oldfieldname': 'indented_qty',
 		'oldfieldtype': 'Currency',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -217,7 +217,7 @@
 		'label': 'Planned Qty',
 		'oldfieldname': 'planned_qty',
 		'oldfieldtype': 'Currency',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -258,7 +258,7 @@
 		'label': 'UOM',
 		'oldfieldname': 'stock_uom',
 		'oldfieldtype': 'Data',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/stock/doctype/delivery_note/delivery_note.py b/stock/doctype/delivery_note/delivery_note.py
index 74e6f8a..3534dad 100644
--- a/stock/doctype/delivery_note/delivery_note.py
+++ b/stock/doctype/delivery_note/delivery_note.py
@@ -40,15 +40,10 @@
   def validate_fiscal_year(self):
     get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
 
-  # ******************* Get Customer Details ***********************
-  #def get_customer_details(self):
-  #  sales_com_obj = get_obj('Sales Common')
-  #  sales_com_obj.get_customer_details(self)
-  #  sales_com_obj.get_shipping_details(self)
 
   # ****** Get contact person details based on customer selected ****
   def get_contact_details(self):
-    return cstr(get_obj('Sales Common').get_contact_details(self,0))
+    return get_obj('Sales Common').get_contact_details(self,0)
 
   # *********** Get Commission rate of Sales Partner ****************
   def get_comm_rate(self, sales_partner):
@@ -122,7 +117,7 @@
     ret = {
        'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
     }
-    return cstr(ret)
+    return ret
 
     
 # OTHER CHARGES TRIGGER FUNCTIONS
diff --git a/stock/doctype/delivery_note/delivery_note.txt b/stock/doctype/delivery_note/delivery_note.txt
index 0c1cc52..b77a6a5 100644
--- a/stock/doctype/delivery_note/delivery_note.txt
+++ b/stock/doctype/delivery_note/delivery_note.txt
@@ -3,16 +3,16 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2010-08-08 17:08:57',
+		'creation': '2011-04-18 15:58:20',
 		'docstatus': 0,
-		'modified': '2011-06-27 16:42:01',
+		'modified': '2011-08-09 17:10:45',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309173122',
+		'_last_update': '1311621379',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'document_type': 'Transaction',
@@ -27,7 +27,7 @@
 		'show_in_menu': 0,
 		'subject': 'To %(customer_name)s on %(transaction_date)s | %(per_billed)s% billed',
 		'tag_fields': 'billing_status',
-		'version': 444
+		'version': 446
 	},
 
 	# These values are common for all DocField
@@ -70,15 +70,15 @@
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 2,
-		'permlevel': 1,
-		'role': 'Material User',
-		'submit': 0,
-		'write': 0
+		'permlevel': 0,
+		'role': 'Sales User',
+		'submit': 1,
+		'write': 1
 	},
 
 	# DocPerm
@@ -89,22 +89,22 @@
 		'doctype': 'DocPerm',
 		'idx': 3,
 		'permlevel': 0,
-		'role': 'Material Manager',
+		'role': 'Material Master Manager',
 		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 4,
-		'permlevel': 1,
+		'permlevel': 0,
 		'role': 'Material Manager',
-		'submit': 0,
-		'write': 0
+		'submit': 1,
+		'write': 1
 	},
 
 	# DocPerm
@@ -115,60 +115,25 @@
 		'doctype': 'DocPerm',
 		'idx': 5,
 		'permlevel': 0,
-		'role': 'Sales User',
+		'role': 'Sales Manager',
 		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 6,
 		'permlevel': 1,
-		'role': 'Sales User',
-		'submit': 0,
-		'write': 0
+		'role': 'All'
 	},
 
 	# DocPerm
 	{
-		'cancel': 0,
-		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 7,
-		'permlevel': 0,
-		'role': 'Accounts User',
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 8,
-		'permlevel': 1,
-		'role': 'Accounts User'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 9,
-		'match': 'customer_name',
-		'permlevel': 0,
-		'role': 'Customer'
-	},
-
-	# DocPerm
-	{
-		'doctype': 'DocPerm',
-		'idx': 10,
 		'permlevel': 2,
-		'role': 'All',
-		'write': 1
+		'role': 'All'
 	},
 
 	# DocField
@@ -366,7 +331,7 @@
 		'fieldtype': 'Currency',
 		'idx': 15,
 		'in_filter': 1,
-		'label': '% Qty Billed',
+		'label': '% Amount Billed',
 		'no_copy': 1,
 		'oldfieldname': 'per_billed',
 		'oldfieldtype': 'Currency',
diff --git a/stock/doctype/delivery_note/tests.py b/stock/doctype/delivery_note/tests.py
deleted file mode 100644
index df04c41..0000000
--- a/stock/doctype/delivery_note/tests.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import unittest
-import webnotes
-
-from webnotes.model.code import get_obj
-
-class SubmissionTest(unittest.TestCase):
-	def setUp(self):
-		self.dn = webnotes.testing.create('Delivery Note')
-		self.dn_items = []
-		
-		# get a line item for testing
-		for d in self.dn.doclist:
-			if d.doctype=='Delivery Note Detail':
-				self.dn_items.append(d)
-				
-		self.old_bin = get_obj('Warehouse', self.line_item[0].warehouse).get_bin(self.line_item[0].item_code)
-		self.dn.on_submit()
-
-	def test_bin_is_updated(self):
-		"tests if bin quantity is affected when on submission"
-		bin = get_obj('Warehouse', self.line_item.warehouse).get_bin(self.line_item[0].item_code)
-		self.assertTrue(bin.actual_qty == self.old_bin.actual_qty - self.line_item[0].qty)
-		
-	def test_sales_order_is_updated(self):
-		"tests if"
\ No newline at end of file
diff --git a/stock/doctype/delivery_note_detail/delivery_note_detail.txt b/stock/doctype/delivery_note_detail/delivery_note_detail.txt
index f5dd8bf..78aea32 100644
--- a/stock/doctype/delivery_note_detail/delivery_note_detail.txt
+++ b/stock/doctype/delivery_note_detail/delivery_note_detail.txt
@@ -285,7 +285,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Batch',
 		'permlevel': 0,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -299,7 +300,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Item Group',
 		'permlevel': 1,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -314,6 +316,7 @@
 		'options': 'Brand',
 		'permlevel': 1,
 		'print_hide': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -423,7 +426,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -455,7 +458,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '150px'
 	},
 
diff --git a/stock/doctype/delivery_note_packing_detail/delivery_note_packing_detail.txt b/stock/doctype/delivery_note_packing_detail/delivery_note_packing_detail.txt
index 10fdfda..3924c13 100644
--- a/stock/doctype/delivery_note_packing_detail/delivery_note_packing_detail.txt
+++ b/stock/doctype/delivery_note_packing_detail/delivery_note_packing_detail.txt
@@ -178,7 +178,8 @@
 		'oldfieldname': 'uom',
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/stock/doctype/item/item.py b/stock/doctype/item/item.py
index ae67749..d51fb3a 100644
--- a/stock/doctype/item/item.py
+++ b/stock/doctype/item/item.py
@@ -27,7 +27,7 @@
 		ret = {
 			'tax_rate'	:	rate and flt(rate[0][0]) or 0
 		}
-		return str(ret)
+		return ret
 
 	def on_update(self):
 		bin = sql("select stock_uom from `tabBin` where item_code = '%s' " % self.doc.item_code)
@@ -178,3 +178,7 @@
 
 		sle = sql("select name from `tabStock Ledger Entry` where item_code = %s and ifnull(is_cancelled, 'No') = 'No'", self.doc.name)
 		return sle and 'exists' or 'not exists'
+		
+	def on_rename(self,newdn,olddn):
+		sql("update tabItem set item_code = %s where name = %s", (newdn, olddn))	
+		
diff --git a/stock/doctype/item/item.txt b/stock/doctype/item/item.txt
index a20c968..ec42ff4 100644
--- a/stock/doctype/item/item.txt
+++ b/stock/doctype/item/item.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1308741898',
+		'_last_update': '1309508838',
 		'allow_attach': 1,
 		'allow_trash': 1,
 		'autoname': 'field:item_code',
@@ -197,7 +197,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -241,7 +241,8 @@
 		'options': 'Brand',
 		'permlevel': 0,
 		'print_hide': 1,
-		'reqd': 0
+		'reqd': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -312,7 +313,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -355,7 +357,8 @@
 		'oldfieldname': 'default_warehouse',
 		'oldfieldtype': 'Link',
 		'options': 'Warehouse',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -556,6 +559,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Account',
 		'permlevel': 0,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -571,7 +575,8 @@
 		'oldfieldname': 'cost_center',
 		'oldfieldtype': 'Link',
 		'options': 'Cost Center',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -719,7 +724,8 @@
 		'idx': 43,
 		'label': 'Default Income Account',
 		'options': 'Account',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -730,7 +736,8 @@
 		'idx': 44,
 		'label': 'Cost Center',
 		'options': 'Cost Center',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -872,7 +879,8 @@
 		'oldfieldname': 'default_bom',
 		'oldfieldtype': 'Link',
 		'options': 'Bill Of Materials',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -912,19 +920,6 @@
 	# DocField
 	{
 		'doctype': 'DocField',
-		'fieldname': 'item_attachments_details',
-		'fieldtype': 'Table',
-		'idx': 58,
-		'label': 'Item Attachments Details',
-		'oldfieldname': 'item_attachments_details',
-		'oldfieldtype': 'Table',
-		'options': 'Item Attachments Detail',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'doctype': 'DocField',
 		'fieldname': 'file_list',
 		'fieldtype': 'Text',
 		'hidden': 1,
diff --git a/stock/doctype/landed_cost_detail/landed_cost_detail.txt b/stock/doctype/landed_cost_detail/landed_cost_detail.txt
index 78efae5..57c7370 100644
--- a/stock/doctype/landed_cost_detail/landed_cost_detail.txt
+++ b/stock/doctype/landed_cost_detail/landed_cost_detail.txt
@@ -49,7 +49,8 @@
 		'label': 'Account Head',
 		'oldfieldname': 'account_head',
 		'oldfieldtype': 'Link',
-		'options': 'Account'
+		'options': 'Account',
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/stock/doctype/landed_cost_master/landed_cost_master.txt b/stock/doctype/landed_cost_master/landed_cost_master.txt
index e405274..71374f8 100644
--- a/stock/doctype/landed_cost_master/landed_cost_master.txt
+++ b/stock/doctype/landed_cost_master/landed_cost_master.txt
@@ -12,6 +12,7 @@
 
 	# These values are common for all DocType
 	{
+		'_last_update': '1309508838',
 		'autoname': 'field:title',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
diff --git a/stock/doctype/lc_pr_detail/lc_pr_detail.txt b/stock/doctype/lc_pr_detail/lc_pr_detail.txt
index 706af56..d09285d 100644
--- a/stock/doctype/lc_pr_detail/lc_pr_detail.txt
+++ b/stock/doctype/lc_pr_detail/lc_pr_detail.txt
@@ -48,7 +48,8 @@
 		'label': 'Purchase Receipt No',
 		'oldfieldname': 'purchase_receipt_no',
 		'oldfieldtype': 'Link',
-		'options': 'Purchase Receipt'
+		'options': 'Purchase Receipt',
+		'search_index': 1
 	},
 
 	# DocField
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.py b/stock/doctype/purchase_receipt/purchase_receipt.py
index 0eda680..4329980 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -42,18 +42,15 @@
 #-----------------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')
-    
-  # Get Supplier Details 
-  #def get_supplier_details(self, name = ''):
-  #  return cstr(get_obj(dt='Purchase Common').get_supplier_details(name))
+   
   
   # Get Item Details
   def get_item_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').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 cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
+    return get_obj(dt='Purchase Common').get_uom_details(arg)
   
   # GET TERMS & CONDITIONS
   # =====================================================================================
@@ -62,7 +59,7 @@
 
   # get available qty at warehouse
   def get_bin_details(self, arg = ''):
-    return cstr(get_obj(dt='Purchase Common').get_bin_details(arg))
+    return get_obj(dt='Purchase Common').get_bin_details(arg)f
 
   # Pull Purchase Order
   def get_po_details(self):
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.txt b/stock/doctype/purchase_receipt/purchase_receipt.txt
index 9759630..31f6cd6 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.txt
+++ b/stock/doctype/purchase_receipt/purchase_receipt.txt
@@ -338,7 +338,7 @@
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client',
 		'width': '100px'
 	},
@@ -359,7 +359,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -888,7 +888,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -906,7 +906,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
diff --git a/stock/doctype/purchase_receipt_detail/purchase_receipt_detail.txt b/stock/doctype/purchase_receipt_detail/purchase_receipt_detail.txt
index d030b9e..a8e0d47 100644
--- a/stock/doctype/purchase_receipt_detail/purchase_receipt_detail.txt
+++ b/stock/doctype/purchase_receipt_detail/purchase_receipt_detail.txt
@@ -100,6 +100,7 @@
 		'options': 'UOM',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client',
 		'width': '100px'
 	},
@@ -324,6 +325,7 @@
 		'options': 'Batch',
 		'permlevel': 0,
 		'print_hide': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -342,6 +344,7 @@
 		'options': 'Warehouse',
 		'permlevel': 1,
 		'print_hide': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -358,7 +361,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'QA Inspection Report',
 		'permlevel': 0,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -373,7 +377,8 @@
 		'oldfieldtype': 'Link',
 		'options': 'Brand',
 		'permlevel': 1,
-		'print_hide': 1
+		'print_hide': 1,
+		'search_index': 0
 	},
 
 	# DocField
@@ -390,7 +395,7 @@
 		'options': 'Item Group',
 		'permlevel': 1,
 		'print_hide': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -474,7 +479,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
diff --git a/stock/doctype/ref_rate_detail/ref_rate_detail.txt b/stock/doctype/ref_rate_detail/ref_rate_detail.txt
index 078fadc..1774b08 100644
--- a/stock/doctype/ref_rate_detail/ref_rate_detail.txt
+++ b/stock/doctype/ref_rate_detail/ref_rate_detail.txt
@@ -34,8 +34,7 @@
 		'parent': 'Ref Rate Detail',
 		'parentfield': 'fields',
 		'parenttype': 'DocType',
-		'permlevel': 0,
-		'search_index': 1
+		'permlevel': 0
 	},
 
 	# DocType, Ref Rate Detail
@@ -54,7 +53,8 @@
 		'oldfieldname': 'price_list_name',
 		'oldfieldtype': 'Select',
 		'options': 'link:Price List',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
@@ -66,7 +66,8 @@
 		'label': 'Ref Rate',
 		'oldfieldname': 'ref_rate',
 		'oldfieldtype': 'Currency',
-		'reqd': 0
+		'reqd': 0,
+		'search_index': 0
 	},
 
 	# DocField
@@ -79,6 +80,7 @@
 		'oldfieldname': 'ref_currency',
 		'oldfieldtype': 'Select',
 		'options': 'link:Currency',
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/sales_bom/sales_bom.py b/stock/doctype/sales_bom/sales_bom.py
index 3bd6fa5..ce4567e 100644
--- a/stock/doctype/sales_bom/sales_bom.py
+++ b/stock/doctype/sales_bom/sales_bom.py
@@ -38,7 +38,7 @@
   def get_item_details(self, name):
     det = sql("select description, stock_uom from `tabItem` where name = '%s' " % cstr(name))
     rate = sql("select ref_rate from `tabRef Rate Detail` where price_list_name = %s and parent = %s and ref_currency = %s", (self.doc.price_list, name, self.doc.currency))
-    return cstr({'description' : det and det[0][0] or '', 'uom': det and det[0][1] or '', 'rate': rate and flt(rate[0][0]) or 0.00})
+    return {'description' : det and det[0][0] or '', 'uom': det and det[0][1] or '', 'rate': rate and flt(rate[0][0]) or 0.00}
 
 
   def get_main_item(self):
diff --git a/stock/doctype/sales_bom/sales_bom.txt b/stock/doctype/sales_bom/sales_bom.txt
index 8863eb2..b97458a 100644
--- a/stock/doctype/sales_bom/sales_bom.txt
+++ b/stock/doctype/sales_bom/sales_bom.txt
@@ -268,6 +268,7 @@
 		'oldfieldname': 'stock_uom',
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
-		'permlevel': 0
+		'permlevel': 0,
+		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/sales_bom_detail/sales_bom_detail.txt b/stock/doctype/sales_bom_detail/sales_bom_detail.txt
index 31d2f1a..3b104e7 100644
--- a/stock/doctype/sales_bom_detail/sales_bom_detail.txt
+++ b/stock/doctype/sales_bom_detail/sales_bom_detail.txt
@@ -114,6 +114,7 @@
 		'oldfieldname': 'uom',
 		'oldfieldtype': 'Link',
 		'options': 'UOM',
-		'permlevel': 1
+		'permlevel': 1,
+		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/serial_no/serial_no.txt b/stock/doctype/serial_no/serial_no.txt
index dd250ee..9aa6119 100644
--- a/stock/doctype/serial_no/serial_no.txt
+++ b/stock/doctype/serial_no/serial_no.txt
@@ -193,7 +193,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -628,7 +628,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nUnder Warranty\nOut of Warranty\nUnder AMC\nOut of AMC',
 		'permlevel': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -715,7 +715,7 @@
 		'options': 'link:Company',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -729,7 +729,7 @@
 		'options': 'link:Fiscal Year',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index b380995..47f0394 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -54,7 +54,7 @@
 			'conversion_factor'		: 1,
      		'batch_no'          	: ''
 		}
-		return str(ret)
+		return ret
 
 
 	# Get UOM Details
@@ -70,7 +70,7 @@
 				'conversion_factor'		: flt(uom[0]['conversion_factor']),
 				'transfer_qty'			: flt(arg['qty']) * flt(uom[0]['conversion_factor']),
 			}
-		return str(ret)
+		return ret
 
 		
 	# get stock and incoming rate on posting date
@@ -396,7 +396,7 @@
 			'customer_name'		: res and res[0][1] or '',
 			'customer_address' : res and res[0][2] or ''}
 
-		return str(ret)
+		return ret
 
 
 	def get_cust_addr(self):
@@ -405,7 +405,7 @@
 			'customer_name'		: res and res[0][0] or '',
 			'customer_address' : res and res[0][1] or ''}
 
-		return str(ret)
+		return ret
 
 
 		
@@ -415,7 +415,7 @@
 			'supplier' : res and res[0][0] or '',
 			'supplier_name' :res and res[0][1] or '',
 			'supplier_address' : res and res[0][2] or ''}
-		return str(ret)
+		return ret
 		
 
 	def get_supp_addr(self):
@@ -423,4 +423,4 @@
 		ret = {
 			'supplier_name' : res and res[0][0] or '',
 			'supplier_address' : res and res[0][1] or ''}
-		return str(ret)
+		return ret
diff --git a/stock/doctype/stock_entry/stock_entry.txt b/stock/doctype/stock_entry/stock_entry.txt
index 951986f..d7477c2 100644
--- a/stock/doctype/stock_entry/stock_entry.txt
+++ b/stock/doctype/stock_entry/stock_entry.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2009-05-12 16:46:45',
+		'creation': '2010-08-08 17:09:25',
 		'docstatus': 0,
-		'modified': '2011-07-10 14:12:39',
+		'modified': '2011-07-11 12:48:52',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -76,7 +76,7 @@
 		'doctype': 'DocPerm',
 		'idx': 1,
 		'permlevel': 0,
-		'role': 'Material User',
+		'role': 'Material Manager',
 		'submit': 1,
 		'write': 1
 	},
@@ -89,28 +89,35 @@
 		'doctype': 'DocPerm',
 		'idx': 2,
 		'permlevel': 1,
-		'role': 'Material User',
+		'role': 'Material Manager',
 		'submit': 0,
 		'write': 0
 	},
 
 	# DocPerm
 	{
-		'create': 0,
+		'amend': 1,
+		'cancel': 1,
+		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 3,
-		'permlevel': 2,
-		'role': 'Production User',
+		'permlevel': 0,
+		'role': 'Material User',
+		'submit': 1,
 		'write': 1
 	},
 
 	# DocPerm
 	{
+		'amend': 0,
+		'cancel': 0,
+		'create': 0,
 		'doctype': 'DocPerm',
 		'idx': 4,
-		'permlevel': 2,
-		'role': 'Production Manager',
-		'write': 1
+		'permlevel': 1,
+		'role': 'Material User',
+		'submit': 0,
+		'write': 0
 	},
 
 	# DocPerm
@@ -136,11 +143,21 @@
 
 	# DocPerm
 	{
+		'create': 0,
+		'doctype': 'DocPerm',
+		'idx': 7,
+		'permlevel': 2,
+		'role': 'Production User',
+		'write': 1
+	},
+
+	# DocPerm
+	{
 		'amend': 1,
 		'cancel': 1,
 		'create': 1,
 		'doctype': 'DocPerm',
-		'idx': 7,
+		'idx': 8,
 		'permlevel': 0,
 		'role': 'Production Manager',
 		'submit': 1,
@@ -150,34 +167,17 @@
 	# DocPerm
 	{
 		'doctype': 'DocPerm',
-		'idx': 8,
+		'idx': 9,
 		'permlevel': 1,
 		'role': 'Production Manager'
 	},
 
 	# DocPerm
 	{
-		'amend': 0,
-		'cancel': 0,
-		'create': 0,
-		'doctype': 'DocPerm',
-		'idx': 9,
-		'permlevel': 1,
-		'role': 'Material Manager',
-		'submit': 0,
-		'write': 0
-	},
-
-	# DocPerm
-	{
-		'amend': 1,
-		'cancel': 1,
-		'create': 1,
 		'doctype': 'DocPerm',
 		'idx': 10,
-		'permlevel': 0,
-		'role': 'Material Manager',
-		'submit': 1,
+		'permlevel': 2,
+		'role': 'Production Manager',
 		'write': 1
 	},
 
@@ -209,14 +209,13 @@
 		'doctype': 'DocField',
 		'fieldname': 'naming_series',
 		'fieldtype': 'Select',
-		'hidden': 0,
 		'idx': 3,
 		'in_filter': 0,
 		'label': 'Series',
 		'no_copy': 1,
 		'oldfieldname': 'naming_series',
 		'oldfieldtype': 'Select',
-		'options': '\nSTE',
+		'options': 'STE',
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
@@ -231,7 +230,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'amendment_date',
 		'fieldtype': 'Date',
-		'hidden': 0,
 		'idx': 4,
 		'in_filter': 0,
 		'label': 'Amendment Date',
@@ -241,7 +239,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -252,7 +249,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'purpose',
 		'fieldtype': 'Select',
-		'hidden': 0,
 		'idx': 5,
 		'in_filter': 1,
 		'label': 'Purpose',
@@ -261,7 +257,6 @@
 		'oldfieldtype': 'Select',
 		'options': 'Material Issue\nMaterial Receipt\nMaterial Transfer\nSales Return\nPurchase Return\nSubcontracting\nProduction Order',
 		'permlevel': 0,
-		'print_hide': 0,
 		'report_hide': 0,
 		'reqd': 1,
 		'search_index': 0,
@@ -286,8 +281,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
-		'search_index': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -309,8 +303,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
-		'search_index': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -345,7 +338,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0,
 		'trigger': 'Client'
 	},
@@ -356,7 +348,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'supplier_name',
 		'fieldtype': 'Data',
-		'hidden': 0,
 		'idx': 10,
 		'in_filter': 0,
 		'label': 'Supplier Name',
@@ -364,9 +355,7 @@
 		'oldfieldname': 'supplier_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -385,9 +374,7 @@
 		'oldfieldname': 'supplier_address',
 		'oldfieldtype': 'Small Text',
 		'permlevel': 0,
-		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0,
 		'trigger': 'Client'
 	},
@@ -410,7 +397,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0,
 		'trigger': 'Client'
 	},
@@ -429,9 +415,7 @@
 		'oldfieldname': 'customer_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -449,9 +433,7 @@
 		'oldfieldname': 'customer_address',
 		'oldfieldtype': 'Small Text',
 		'permlevel': 0,
-		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -473,7 +455,6 @@
 		'permlevel': 2,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0,
 		'trigger': 'Client'
 	},
@@ -496,8 +477,7 @@
 		'permlevel': 2,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
-		'search_index': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -507,7 +487,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'fg_completed_qty',
 		'fieldtype': 'Currency',
-		'hidden': 0,
 		'idx': 17,
 		'in_filter': 0,
 		'label': 'FG Completed Qty',
@@ -517,7 +496,6 @@
 		'permlevel': 2,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0,
 		'trigger': 'Client'
 	},
@@ -527,15 +505,13 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'hidden': 0,
 		'idx': 18,
 		'label': 'Warehouse HTML',
 		'no_copy': 0,
 		'oldfieldtype': 'HTML',
 		'options': "<div class='columnHeading'>Warehouse</div>",
 		'permlevel': 0,
-		'print_hide': 1,
-		'reqd': 0
+		'print_hide': 1
 	},
 
 	# DocField
@@ -545,7 +521,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'from_warehouse',
 		'fieldtype': 'Link',
-		'hidden': 0,
 		'idx': 19,
 		'in_filter': 0,
 		'label': 'Source Warehouse',
@@ -569,7 +544,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'to_warehouse',
 		'fieldtype': 'Link',
-		'hidden': 0,
 		'idx': 20,
 		'in_filter': 0,
 		'label': 'Target Warehouse',
@@ -581,7 +555,7 @@
 		'print_hide': 1,
 		'report_hide': 0,
 		'reqd': 0,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -616,7 +590,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'transfer_date',
 		'fieldtype': 'Date',
-		'hidden': 0,
 		'idx': 23,
 		'in_filter': 1,
 		'label': 'Transfer Date',
@@ -627,7 +600,7 @@
 		'print_hide': 0,
 		'report_hide': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -637,7 +610,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'posting_date',
 		'fieldtype': 'Date',
-		'hidden': 0,
 		'idx': 24,
 		'in_filter': 1,
 		'label': 'Posting Date',
@@ -657,7 +629,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'posting_time',
 		'fieldtype': 'Time',
-		'hidden': 0,
 		'idx': 25,
 		'in_filter': 0,
 		'label': 'Posting Time',
@@ -677,7 +648,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'amended_from',
 		'fieldtype': 'Link',
-		'hidden': 0,
 		'idx': 26,
 		'in_filter': 0,
 		'label': 'Amended From',
@@ -688,7 +658,6 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -698,7 +667,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'transporter',
 		'fieldtype': 'Data',
-		'hidden': 0,
 		'idx': 27,
 		'in_filter': 0,
 		'label': 'Transporter',
@@ -708,7 +676,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -718,7 +685,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'is_excisable_goods',
 		'fieldtype': 'Select',
-		'hidden': 0,
 		'idx': 28,
 		'in_filter': 0,
 		'label': 'Is Excisable Goods',
@@ -729,7 +695,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -739,7 +704,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'excisable_goods',
 		'fieldtype': 'Select',
-		'hidden': 0,
 		'idx': 29,
 		'in_filter': 0,
 		'label': 'Excisable Goods',
@@ -750,7 +714,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -771,7 +734,6 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -781,7 +743,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'remarks',
 		'fieldtype': 'Text',
-		'hidden': 0,
 		'idx': 31,
 		'in_filter': 0,
 		'label': 'Remarks',
@@ -839,25 +800,6 @@
 
 	# DocField
 	{
-		'allow_on_submit': 0,
-		'doctype': 'DocField',
-		'fieldtype': 'Button',
-		'hidden': 0,
-		'idx': 35,
-		'in_filter': 0,
-		'label': 'Get Current Stock',
-		'no_copy': 0,
-		'oldfieldtype': 'Button',
-		'options': 'get_stock_and_rate',
-		'permlevel': 0,
-		'print_hide': 1,
-		'report_hide': 0,
-		'reqd': 0,
-		'search_index': 0
-	},
-
-	# DocField
-	{
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
 		'idx': 36,
@@ -881,7 +823,6 @@
 		'permlevel': 2,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -902,7 +843,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'mtn_details',
 		'fieldtype': 'Table',
-		'hidden': 0,
 		'idx': 39,
 		'in_filter': 0,
 		'label': 'MTN Details',
@@ -913,7 +853,6 @@
 		'permlevel': 0,
 		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -923,7 +862,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'total_amount',
 		'fieldtype': 'Currency',
-		'hidden': 0,
 		'idx': 40,
 		'in_filter': 0,
 		'label': 'Total Amount',
@@ -933,7 +871,6 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	},
 
@@ -953,7 +890,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'company',
 		'fieldtype': 'Link',
-		'hidden': 0,
 		'idx': 42,
 		'in_filter': 1,
 		'label': 'Company',
@@ -965,7 +901,7 @@
 		'print_hide': 1,
 		'report_hide': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -974,7 +910,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'fiscal_year',
 		'fieldtype': 'Select',
-		'hidden': 0,
 		'idx': 43,
 		'in_filter': 0,
 		'label': 'Fiscal Year',
@@ -986,7 +921,7 @@
 		'print_hide': 1,
 		'report_hide': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -995,7 +930,6 @@
 		'doctype': 'DocField',
 		'fieldname': 'select_print_heading',
 		'fieldtype': 'Link',
-		'hidden': 0,
 		'idx': 44,
 		'in_filter': 0,
 		'label': 'Select Print Heading',
@@ -1004,9 +938,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Print Heading',
 		'permlevel': 0,
-		'print_hide': 0,
 		'report_hide': 0,
-		'reqd': 0,
 		'search_index': 0
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/stock_entry_detail/stock_entry_detail.txt b/stock/doctype/stock_entry_detail/stock_entry_detail.txt
index b4fca09..50b7154 100644
--- a/stock/doctype/stock_entry_detail/stock_entry_detail.txt
+++ b/stock/doctype/stock_entry_detail/stock_entry_detail.txt
@@ -135,6 +135,7 @@
 		'options': 'Batch',
 		'permlevel': 0,
 		'print_hide': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -152,7 +153,7 @@
 		'permlevel': 1,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -196,6 +197,7 @@
 		'options': 'UOM',
 		'permlevel': 0,
 		'reqd': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -251,7 +253,8 @@
 		'no_copy': 1,
 		'oldfieldname': 'serial_no',
 		'oldfieldtype': 'Text',
-		'permlevel': 0
+		'permlevel': 0,
+		'reqd': 0
 	},
 
 	# DocField
@@ -278,4 +281,4 @@
 		'oldfieldtype': 'Currency',
 		'permlevel': 1
 	}
-]
\ No newline at end of file
+]
diff --git a/stock/doctype/stock_ledger_entry/stock_ledger_entry.txt b/stock/doctype/stock_ledger_entry/stock_ledger_entry.txt
index 603f095..823837a 100644
--- a/stock/doctype/stock_ledger_entry/stock_ledger_entry.txt
+++ b/stock/doctype/stock_ledger_entry/stock_ledger_entry.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1307707462',
+		'_last_update': '1309508840',
 		'autoname': 'SLE/.########',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
@@ -163,7 +163,7 @@
 		'oldfieldtype': 'Select',
 		'options': 'link:Warehouse Type',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -194,7 +194,7 @@
 		'oldfieldname': 'posting_time',
 		'oldfieldtype': 'Time',
 		'permlevel': 1,
-		'search_index': 0,
+		'search_index': 1,
 		'width': '100px'
 	},
 
@@ -210,7 +210,7 @@
 		'oldfieldname': 'transaction_date',
 		'oldfieldtype': 'Date',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -225,7 +225,7 @@
 		'oldfieldname': 'voucher_type',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -240,7 +240,7 @@
 		'oldfieldname': 'voucher_no',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -394,7 +394,7 @@
 		'oldfieldname': 'company',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -409,7 +409,7 @@
 		'oldfieldname': 'fiscal_year',
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '150px'
 	},
 
@@ -425,7 +425,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nYes\nNo',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '100px'
 	},
 
@@ -441,7 +441,7 @@
 		'oldfieldtype': 'Select',
 		'options': '\nYes\nNo',
 		'permlevel': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'width': '100px'
 	}
 ]
\ No newline at end of file
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.py b/stock/doctype/stock_reconciliation/stock_reconciliation.py
index 69710f0..f040df3 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -118,7 +118,7 @@
 	# ------------------
 	def get_current_stock(self, item_code, warehouse):
 		bin = sql("select name from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, warehouse))
-		prev_sle = bin and get_obj('Bin', bin[0][0]).get_prev_sle(self.doc.reconciliation_date,self.doc.reconciliation_time) or 0
+		prev_sle = bin and get_obj('Bin', bin[0][0]).get_prev_sle(self.doc.reconciliation_date,self.doc.reconciliation_time) or {}
 		stock_uom = sql("select stock_uom from `tabItem` where name = %s",item_code)
 		return {'actual_qty': prev_sle.get('bin_aqat', 0), 'stock_uom': stock_uom[0][0]}
 
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.txt b/stock/doctype/stock_reconciliation/stock_reconciliation.txt
index 1080a27..771068d 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.txt
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.txt
@@ -12,7 +12,7 @@
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1307707462',
+		'_last_update': '1309508840',
 		'allow_attach': 1,
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
@@ -131,7 +131,8 @@
 		'oldfieldname': 'reconciliation_date',
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
-		'reqd': 1
+		'reqd': 1,
+		'search_index': 1
 	},
 
 	# DocField
@@ -185,7 +186,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Company',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -200,7 +201,7 @@
 		'oldfieldtype': 'Select',
 		'options': 'link:Fiscal Year',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
index e603d1f..f8ac737 100644
--- a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
+++ b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
@@ -22,7 +22,7 @@
     self.doc, self.doclist = d,dl
 
   def get_stock_uom(self, item_code):
-    return cstr({'current_stock_uom': cstr(get_value('Item', item_code, 'stock_uom'))})
+    return {'current_stock_uom': cstr(get_value('Item', item_code, 'stock_uom'))}
   
   def validate_mandatory(self):
     if not cstr(self.doc.item_code):
diff --git a/stock/doctype/warehouse/warehouse.txt b/stock/doctype/warehouse/warehouse.txt
index 3d69b07..1363eef 100644
--- a/stock/doctype/warehouse/warehouse.txt
+++ b/stock/doctype/warehouse/warehouse.txt
@@ -244,7 +244,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Company',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/customer_issue/customer_issue.py b/support/doctype/customer_issue/customer_issue.py
index db63cc2..12a8ebd 100644
--- a/support/doctype/customer_issue/customer_issue.py
+++ b/support/doctype/customer_issue/customer_issue.py
@@ -27,37 +27,6 @@
   def autoname(self):
     #self.doc.name = make_autoname('CI/' + self.doc.fiscal_year + '/.######')
     self.doc.name = make_autoname(self.doc.naming_series + '.######')
-
-  #def get_customer_details(self):
-  #  details = sql("select address, territory, customer_group, customer_name from `tabCustomer` where name = '%s' and docstatus != 2" %(self.doc.customer), as_dict = 1)
-  #  if details:
-  #    ret = {
-  #      'customer_address'  :  details and details[0]['address'] or '',
-  #      'customer_name'  :  details and details[0]['customer_name'] or '',
-  #      'territory'       :  details and details[0]['territory'] or '',
-  #      'customer_group'    :  details and details[0]['customer_group'] or ''
-  #    }
-  #    # ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
-  #    contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where customer_name = '%s' and is_customer = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(self.doc.customer), as_dict = 1)
-  #    ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
-  #    ret['contact_no']     = contact_det and contact_det[0]['contact_no'] or ''
-  #    ret['email_id']       = contact_det and contact_det[0]['email_id'] or ''
-  #  
-  #    return cstr(ret)
-  #  else:
-  #    msgprint("Customer : %s does not exist in system." % (name))
-  #    raise Exception
-
-  # Get customer's contact person details
-  # ==============================================================
-  #def get_contact_details(self):
-  #  contact = sql("select contact_no, email_id from `tabContact` where contact_name = '%s' and customer_name = '%s' and docstatus != 2" %(self.doc.contact_person, self.doc.customer), as_dict = 1)
-  #  ret = {
-  #    'contact_no'       :    contact and contact[0]['contact_no'] or '',
-  #    'email_id'         :    contact and contact[0]['email_id'] or ''
-  #  }
-  #  return str(ret)
-    
     
 #check if maintenance schedule already generated
 #============================================
@@ -66,7 +35,7 @@
     nm = nm and nm[0][0] or ''
     
     if not nm:
-      return cstr('No')    
+      return 'No'
   
   def on_submit(self):
     if session['user'] != 'Guest':
diff --git a/support/doctype/customer_issue/customer_issue.txt b/support/doctype/customer_issue/customer_issue.txt
index 93c274f..122f92d 100644
--- a/support/doctype/customer_issue/customer_issue.txt
+++ b/support/doctype/customer_issue/customer_issue.txt
@@ -167,7 +167,7 @@
 		'options': '\nOpen\nClosed\nWork In Progress\nCancelled',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -340,7 +340,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -371,7 +371,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -389,7 +389,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -563,7 +563,7 @@
 		'oldfieldname': 'allocated_on',
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -578,7 +578,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Sales Person',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -627,7 +627,7 @@
 		'oldfieldname': 'resolution_date',
 		'oldfieldtype': 'Date',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -643,7 +643,7 @@
 		'oldfieldtype': 'Link',
 		'options': 'Sales Person',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/item_maintenance_detail/item_maintenance_detail.txt b/support/doctype/item_maintenance_detail/item_maintenance_detail.txt
index ff5d211..4d4e26a 100644
--- a/support/doctype/item_maintenance_detail/item_maintenance_detail.txt
+++ b/support/doctype/item_maintenance_detail/item_maintenance_detail.txt
@@ -150,7 +150,7 @@
 		'options': 'Sales Person',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/maintenance_schedule/maintenance_schedule.py b/support/doctype/maintenance_schedule/maintenance_schedule.py
index 0d6ef80..d5c90b5 100644
--- a/support/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/support/doctype/maintenance_schedule/maintenance_schedule.py
@@ -38,21 +38,8 @@
       'item_name': item and item[0]['item_name'] or '',
       'description' : item and item[0]['description'] or ''
     }
-    return str(ret)
-  
-  #pull customer details
-  #-------------------------
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name,t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = %s and t1.name=t2.customer and t2.is_primary_contact = 'Yes'", self.doc.customer, as_dict=1)
-  #  
-  #  ret = {
-  #    'customer_name':  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-  #  return str(ret)
-  
+    return ret
+    
   # generate maintenance schedule
   #-------------------------------------
   def generate_schedule(self):
@@ -132,7 +119,7 @@
       count = period/365
     
     ret = {'no_of_visits':count}
-    return str(ret)
+    return ret
   
   def validate_maintenance_detail(self):
     if not getlist(self.doclist, 'item_maintenance_detail'):
diff --git a/support/doctype/maintenance_schedule/maintenance_schedule.txt b/support/doctype/maintenance_schedule/maintenance_schedule.txt
index 3881aa3..a053cf9 100644
--- a/support/doctype/maintenance_schedule/maintenance_schedule.txt
+++ b/support/doctype/maintenance_schedule/maintenance_schedule.txt
@@ -167,7 +167,7 @@
 		'oldfieldtype': 'Data',
 		'permlevel': 1,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -252,7 +252,7 @@
 		'options': '\nDraft\nSubmitted\nCancelled',
 		'permlevel': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -297,7 +297,7 @@
 		'options': 'Company',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -313,7 +313,7 @@
 		'options': 'Territory',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/maintenance_schedule_detail/maintenance_schedule_detail.txt b/support/doctype/maintenance_schedule_detail/maintenance_schedule_detail.txt
index 01cf7f0..edd8091 100644
--- a/support/doctype/maintenance_schedule_detail/maintenance_schedule_detail.txt
+++ b/support/doctype/maintenance_schedule_detail/maintenance_schedule_detail.txt
@@ -112,7 +112,7 @@
 		'options': 'Sales Person',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/maintenance_visit/maintenance_visit.py b/support/doctype/maintenance_visit/maintenance_visit.py
index 203793c..e4efe1c 100644
--- a/support/doctype/maintenance_visit/maintenance_visit.py
+++ b/support/doctype/maintenance_visit/maintenance_visit.py
@@ -31,20 +31,7 @@
       'item_name' : item and item[0]['item_name'] or '',
       'description' : item and item[0]['description'] or ''
     }
-    return str(ret)
-  
-  #get customer details
-  #-----------------------
-  #def get_customer_details(self):
-  #  det = sql("select t1.customer_name,t1.address,t1.territory,t2.contact_name from `tabCustomer` t1, `tabContact` t2 where t1.name = %s and t1.name=t2.customer and t2.is_primary_contact = 'Yes'", self.doc.customer, as_dict=1)
-  #  
-  #  ret = {
-  #    'customer_name' :  det and det[0]['customer_name'] or '',
-  #    'address'  :  det and det[0]['address'] or '',
-  #    'territory':  det and det[0]['territory'] or '',
-  #    'contact_person' : det and det[0]['contact_name'] or ''
-  #  }
-  #  return str(ret)
+    return ret
   
   # fetch details of resp Sales order or customer issue
   #-----------------------------------------------------------
diff --git a/support/doctype/maintenance_visit/maintenance_visit.txt b/support/doctype/maintenance_visit/maintenance_visit.txt
index 2485f57..76cf56f 100644
--- a/support/doctype/maintenance_visit/maintenance_visit.txt
+++ b/support/doctype/maintenance_visit/maintenance_visit.txt
@@ -241,7 +241,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -258,7 +258,7 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -410,7 +410,7 @@
 		'options': '\nScheduled\nUnscheduled\nBreakdown',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/support/doctype/support_ticket/__init__.py b/support/doctype/support_ticket/__init__.py
index 0ca33ec..9379280 100644
--- a/support/doctype/support_ticket/__init__.py
+++ b/support/doctype/support_ticket/__init__.py
@@ -6,14 +6,26 @@
 	def __init__(self):
 		"""
 			settings_doc must contain
-			is_ssl, host, username, password
+			use_ssl, host, username, password
 		"""
-		POP3Mailbox.__init__(self, 'Support Email Settings')
+		from webnotes.model.doc import Document
+
+		# extract email settings
+		self.email_settings = Document('Email Settings','Email Settings')
+		
+		s = Document('Support Email Settings')
+		s.use_ssl = self.email_settings.support_use_ssl
+		s.host = self.email_settings.support_host
+		s.username = self.email_settings.support_username
+		s.password = self.email_settings.support_password
+		
+		POP3Mailbox.__init__(self, s)
 	
 	def check_mails(self):
 		"""
 			returns true if there are active sessions
 		"""
+		self.auto_close_tickets()
 		return webnotes.conn.sql("select user from tabSessions where time_to_sec(timediff(now(), lastupdate)) < 1800")
 	
 	def process_message(self, mail):
@@ -56,6 +68,39 @@
 		# update feed
 		update_feed(d)
 		
+		# send auto reply
+		self.send_auto_reply(d)
+		
+	def send_auto_reply(self, d):
+		"""
+			Send auto reply to emails
+		"""
+		signature = self.email_settings.support_signature
+
+		response = self.email_settings.support_autoreply or ("""
+A new Ticket has been raised for your query. If you have any additional information, please
+reply back to this mail.
+		
+We will get back to you as soon as possible
+
+[This is an automatic response]
+
+		""" + (signature or ''))
+
+		from webnotes.utils.email_lib import sendmail
+		
+		sendmail(\
+			recipients = [d.raised_by], \
+			sender = self.email_settings.support_email, \
+			subject = '['+d.name+'] ' + str(d.subject or ''), \
+			msg = response)
+		
+	def auto_close_tickets(self):
+		"""
+			Auto Closes Waiting for Customer Support Ticket after 15 days
+		"""
+		webnotes.conn.sql("update `tabSupport Ticket` set status = 'Closed' where status = 'Waiting for Customer' and date_sub(curdate(),interval 15 Day) > modified")
+
 
 def get_support_mails():
 	"""
@@ -63,8 +108,3 @@
 	"""
 	SupportMailbox().get_messages()
 
-def auto_close_tickets():
-	"""
-		Auto Closes Waiting for Customer Support Ticket after 15 days
-	"""
-	webnotes.conn.sql("update `tabSupport Ticket` set status = 'Closed' where status = 'Waiting for Customer' and date_sub(curdate(),interval 15 Day) > modified")
diff --git a/support/doctype/support_ticket/support_ticket.js b/support/doctype/support_ticket/support_ticket.js
index 2c1e77f..914227b 100644
--- a/support/doctype/support_ticket/support_ticket.js
+++ b/support/doctype/support_ticket/support_ticket.js
@@ -20,9 +20,9 @@
 				items: [
 					{
 						column: 0,
-						label:'Support Email Settings',
+						label:'Email Settings',
 						description:'Integrate your incoming support emails to support ticket',
-						onclick: function() { loaddoc('Support Email Settings','Support Email Settings'); }
+						onclick: function() { loaddoc('Email Settings','Email Settings'); }
 					}, 					
 				]
 			})			
diff --git a/support/doctype/support_ticket/support_ticket.py b/support/doctype/support_ticket/support_ticket.py
index 75defbe..c71304a 100644
--- a/support/doctype/support_ticket/support_ticket.py
+++ b/support/doctype/support_ticket/support_ticket.py
@@ -19,7 +19,7 @@
 		
 		response = self.doc.new_response + '\n\n[Please do not change the subject while responding.]'
 
-		signature = webnotes.conn.get_value('Support Email Settings',None,'signature')
+		signature = webnotes.conn.get_value('Email Settings',None,'support_signature')
 		if signature:
 			response += '\n\n' + signature
 
@@ -27,7 +27,7 @@
 		
 		sendmail(\
 			recipients = [self.doc.raised_by], \
-			sender=webnotes.conn.get_value('Support Email Settings',None,'email'), \
+			sender=webnotes.conn.get_value('Email Settings',None,'support_email'), \
 			subject=subject, \
 			msg=response)
 
diff --git a/support/doctype/support_ticket/support_ticket.txt b/support/doctype/support_ticket/support_ticket.txt
index caeb801..8164764 100644
--- a/support/doctype/support_ticket/support_ticket.txt
+++ b/support/doctype/support_ticket/support_ticket.txt
@@ -3,16 +3,16 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2011-05-23 14:50:46',
+		'creation': '2011-05-23 09:01:10',
 		'docstatus': 0,
-		'modified': '2011-07-06 09:25:53',
+		'modified': '2011-07-25 14:45:28',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1309771514',
+		'_last_update': '1311584009',
 		'allow_trash': 1,
 		'autoname': 'SUP.######',
 		'colour': 'White:FFF',
@@ -25,7 +25,7 @@
 		'show_in_menu': 0,
 		'subject': '%(subject)s',
 		'tag_fields': 'status,allocated_to',
-		'version': 150
+		'version': 144
 	},
 
 	# These values are common for all DocField
@@ -131,7 +131,7 @@
 	{
 		'doctype': 'DocField',
 		'fieldname': 'subject',
-		'fieldtype': 'Small Text',
+		'fieldtype': 'Text',
 		'idx': 2,
 		'in_filter': 1,
 		'label': 'Subject',
@@ -170,22 +170,10 @@
 
 	# DocField
 	{
-		'doctype': 'DocField',
-		'fieldname': 'problem_description',
-		'fieldtype': 'Text',
-		'idx': 5,
-		'label': 'Problem Description',
-		'oldfieldname': 'problem_description',
-		'oldfieldtype': 'Text',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'HTML',
-		'idx': 6,
+		'idx': 5,
 		'label': 'Thread HTML',
 		'permlevel': 1
 	},
@@ -196,7 +184,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'new_response',
 		'fieldtype': 'Text',
-		'idx': 7,
+		'idx': 6,
 		'label': 'New Response',
 		'permlevel': 0
 	},
@@ -206,9 +194,8 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 8,
+		'idx': 7,
 		'label': 'Send',
-		'options': 'send_response',
 		'permlevel': 0
 	},
 
@@ -217,7 +204,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Section Break',
-		'idx': 9,
+		'idx': 8,
 		'label': 'Additional Info',
 		'permlevel': 1
 	},
@@ -227,7 +214,7 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 10,
+		'idx': 9,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 1,
 		'width': '50%'
@@ -239,7 +226,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'customer',
 		'fieldtype': 'Link',
-		'idx': 11,
+		'idx': 10,
 		'in_filter': 1,
 		'label': 'Customer',
 		'oldfieldname': 'customer',
@@ -257,14 +244,14 @@
 		'doctype': 'DocField',
 		'fieldname': 'customer_name',
 		'fieldtype': 'Data',
-		'idx': 12,
+		'idx': 11,
 		'in_filter': 1,
 		'label': 'Customer Name',
 		'oldfieldname': 'customer_name',
 		'oldfieldtype': 'Data',
 		'permlevel': 2,
 		'reqd': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -272,7 +259,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'address_display',
 		'fieldtype': 'Small Text',
-		'idx': 13,
+		'idx': 12,
 		'label': 'Address',
 		'permlevel': 2
 	},
@@ -282,7 +269,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'contact_display',
 		'fieldtype': 'Data',
-		'idx': 14,
+		'idx': 13,
 		'label': 'Contact Name',
 		'permlevel': 2
 	},
@@ -292,7 +279,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'contact_mobile',
 		'fieldtype': 'Data',
-		'idx': 15,
+		'idx': 14,
 		'label': 'Mobile No',
 		'permlevel': 2
 	},
@@ -302,7 +289,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'contact_email',
 		'fieldtype': 'Data',
-		'idx': 16,
+		'idx': 15,
 		'label': 'Contact Email',
 		'oldfieldname': 'contact_no',
 		'oldfieldtype': 'Data',
@@ -315,7 +302,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'opening_date',
 		'fieldtype': 'Date',
-		'idx': 17,
+		'idx': 16,
 		'label': 'Opening Date',
 		'no_copy': 1,
 		'oldfieldname': 'opening_date',
@@ -328,7 +315,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'opening_time',
 		'fieldtype': 'Time',
-		'idx': 18,
+		'idx': 17,
 		'label': 'Opening Time',
 		'no_copy': 1,
 		'oldfieldname': 'opening_time',
@@ -341,19 +328,18 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldtype': 'Column Break',
-		'idx': 19,
+		'idx': 18,
 		'oldfieldtype': 'Column Break',
 		'permlevel': 1
 	},
 
 	# DocField
 	{
-		'colour': 'White:FFF',
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldname': 'allocated_to',
 		'fieldtype': 'Link',
-		'idx': 20,
+		'idx': 19,
 		'in_filter': 1,
 		'label': 'Allocated To',
 		'oldfieldname': 'allocated_to',
@@ -368,8 +354,8 @@
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldname': 'resolution_details',
-		'fieldtype': 'Small Text',
-		'idx': 21,
+		'fieldtype': 'Text',
+		'idx': 20,
 		'label': 'Resolution Details',
 		'no_copy': 1,
 		'oldfieldname': 'resolution_details',
@@ -379,19 +365,18 @@
 
 	# DocField
 	{
-		'colour': 'White:FFF',
 		'depends_on': 'eval:!doc.__islocal',
 		'doctype': 'DocField',
 		'fieldname': 'resolution_date',
 		'fieldtype': 'Date',
-		'idx': 22,
+		'idx': 21,
 		'in_filter': 0,
 		'label': 'Resolution Date',
 		'no_copy': 1,
 		'oldfieldname': 'resolution_date',
 		'oldfieldtype': 'Date',
 		'permlevel': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -400,7 +385,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'resolution_time',
 		'fieldtype': 'Time',
-		'idx': 23,
+		'idx': 22,
 		'label': 'Resolution Time',
 		'oldfieldname': 'resolution_time',
 		'oldfieldtype': 'Time',
@@ -414,7 +399,7 @@
 		'fieldname': 'content_type',
 		'fieldtype': 'Data',
 		'hidden': 1,
-		'idx': 24,
+		'idx': 23,
 		'label': 'Content Type',
 		'permlevel': 0
 	}
diff --git a/utilities/doctype/address/address.txt b/utilities/doctype/address/address.txt
index e7ff8cc..4f44806 100644
--- a/utilities/doctype/address/address.txt
+++ b/utilities/doctype/address/address.txt
@@ -117,7 +117,7 @@
 		'label': 'City/Town',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -129,7 +129,7 @@
 		'in_filter': 1,
 		'label': 'Pincode',
 		'permlevel': 0,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -144,7 +144,7 @@
 		'options': 'link:Country',
 		'permlevel': 0,
 		'reqd': 1,
-		'search_index': 1,
+		'search_index': 0,
 		'trigger': 'Client'
 	},
 
@@ -214,6 +214,7 @@
 		'label': 'Customer',
 		'options': 'Customer',
 		'permlevel': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
@@ -240,6 +241,7 @@
 		'label': 'Supplier',
 		'options': 'Supplier',
 		'permlevel': 0,
+		'search_index': 1,
 		'trigger': 'Client'
 	},
 
diff --git a/utilities/doctype/bulk_rename_tool/bulk_rename_tool.txt b/utilities/doctype/bulk_rename_tool/bulk_rename_tool.txt
index f15d3a9..16058e7 100644
--- a/utilities/doctype/bulk_rename_tool/bulk_rename_tool.txt
+++ b/utilities/doctype/bulk_rename_tool/bulk_rename_tool.txt
@@ -3,16 +3,16 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2011-07-08 13:30:05',
+		'creation': '2011-07-08 11:14:15',
 		'docstatus': 0,
-		'modified': '2011-07-08 13:30:05',
+		'modified': '2011-07-26 00:59:27',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1310035501',
+		'_last_update': '1311622167',
 		'allow_attach': 1,
 		'autoname': 'field:rename_doctype',
 		'colour': 'White:FFF',
@@ -21,7 +21,7 @@
 		'name': '__common__',
 		'section_style': 'Simple',
 		'show_in_menu': 0,
-		'version': 6
+		'version': 7
 	},
 
 	# These values are common for all DocField
@@ -96,4 +96,4 @@
 		'label': 'Rename',
 		'options': 'do_rename'
 	}
-]
\ No newline at end of file
+]
diff --git a/utilities/doctype/gl_mapper_detail/gl_mapper_detail.txt b/utilities/doctype/gl_mapper_detail/gl_mapper_detail.txt
index 404e8fc..bf77e7c 100644
--- a/utilities/doctype/gl_mapper_detail/gl_mapper_detail.txt
+++ b/utilities/doctype/gl_mapper_detail/gl_mapper_detail.txt
@@ -173,7 +173,7 @@
 		'label': 'Fiscal Year',
 		'oldfieldname': 'fiscal_year',
 		'reqd': 1,
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
@@ -202,7 +202,7 @@
 		'in_filter': 1,
 		'label': 'Company',
 		'oldfieldname': 'company',
-		'search_index': 1
+		'search_index': 0
 	},
 
 	# DocField
diff --git a/utilities/doctype/patch_util/patch_util.py b/utilities/doctype/patch_util/patch_util.py
index f26d110..828c805 100644
--- a/utilities/doctype/patch_util/patch_util.py
+++ b/utilities/doctype/patch_util/patch_util.py
@@ -85,7 +85,8 @@
 			d.parent = doctype
 			d.parenttype = 'DocType'
 			d.parentfield = 'permissions'
-		
+			
+		d.permlevel = level
 		d.role = role
 		d.read = read
 		d.write = write
diff --git a/utilities/doctype/rename_tool/rename_tool.txt b/utilities/doctype/rename_tool/rename_tool.txt
index 9269185..3b8a5dd 100755
--- a/utilities/doctype/rename_tool/rename_tool.txt
+++ b/utilities/doctype/rename_tool/rename_tool.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2011-06-23 11:03:25',
+		'creation': '2011-06-27 10:52:02',
 		'docstatus': 0,
-		'modified': '2011-07-01 17:46:42',
+		'modified': '2011-07-26 00:59:27',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
@@ -70,7 +70,7 @@
 		'fieldtype': 'Select',
 		'idx': 1,
 		'label': 'Select DocType',
-		'options': 'link:DocType'
+		'options': '\nAccount\nCompany\nCustomer\nSupplier\nEmployee\nWarehouse\nItem'
 	},
 
 	# DocField
diff --git a/utilities/doctype/sms_control/sms_control.py b/utilities/doctype/sms_control/sms_control.py
index de11e90..a1edf83 100644
--- a/utilities/doctype/sms_control/sms_control.py
+++ b/utilities/doctype/sms_control/sms_control.py
@@ -58,7 +58,7 @@
 	def connect_gateway(self):
 		"login to gateway"
 		from webnotes.utils.webservice import FrameworkServer
-		fw = FrameworkServer('www.erpnext.com','/','__system@webnotestech.com','password',https=1)
+		fw = FrameworkServer('www.erpnext.com', '/', '__system@webnotestech.com', 'password', https=1)
 		return fw
 
 	def get_sender_name(self):