Merge branch 'master' of github.com:webnotes/erpnext into cms2
diff --git a/.gitignore b/.gitignore
index 62cc577..ba0a9a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,4 +14,4 @@
 public/files
 public/backups
 public/css/wn-web.css
-public/js/wn-web.js
\ No newline at end of file
+public/js/wn-web.js
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index ec1e17e..83ad9d2 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -49,6 +49,13 @@
 		}
 		return ret
 		
+	def validate_mandatory(self):
+		if not self.doc.group_or_ledger:
+			msgprint("Please select Group or Ledger value", raise_exception=1)
+			
+		if self.doc.cost_center_name != 'Root' and not self.doc.parent_cost_center:
+			msgprint("Please enter parent cost center", raise_exception=1)
+		
 	#-------------------------------------------------------------------------
 	def convert_group_to_ledger(self):
 		if self.check_if_child_exists():
@@ -78,6 +85,16 @@
 	def check_if_child_exists(self):
 		return sql("select name from `tabCost Center` where parent_cost_center = %s and docstatus != 2", self.doc.name)
 
+
+	def validate_budget_details(self):
+		check_acc_list = []
+		for d in getlist(self.doclist, 'budget_details'):
+			if [d.account, d.fiscal_year] in check_acc_list:
+				msgprint("Account " + cstr(d.account) + "has been entered more than once for fiscal year " + cstr(d.fiscal_year), raise_exception=1)
+			else: 
+				check_acc_list.append([d.account, d.fiscal_year])
+		
+
 	#-------------------------------------------------------------------------
 	def validate(self):
 		"""
@@ -86,12 +103,8 @@
 		if (self.doc.__islocal or not self.doc.name) and sql("select name from `tabCost Center` where cost_center_name = %s and company_name=%s", (self.doc.cost_center_name, self.doc.company_name)):
 			msgprint("Cost Center Name already exists, please rename", raise_exception=1)
 			
-		check_acc_list = []
-		for d in getlist(self.doclist, 'budget_details'):
-			if [d.account, d.fiscal_year] in check_acc_list:
-				msgprint("Account " + cstr(d.account) + "has been entered more than once for fiscal year " + cstr(d.fiscal_year), raise_exception=1)
-			else: 
-				check_acc_list.append([d.account, d.fiscal_year])
+		self.validate_mandatory()
+		self.validate_budget_details()
 			
 	#-------------------------------------------------------------------------
 	def update_nsm_model(self):
diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.js b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.js
index c4288a4..830092b 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.js
+++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.js
@@ -20,19 +20,8 @@
 	if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
 }
 
-cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-	hide_field('repost_account_balances');
-	hide_field('next_fiscal_year');
-	hide_field('repost');
-
-	if (doc.docstatus == 1) { 
-		unhide_field('repost_account_balances');
-		unhide_field('next_fiscal_year');
-		unhide_field('repost');
-	}
-}
 
 // ***************** Get Account Head *****************
 cur_frm.fields_dict['closing_account_head'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.is_pl_account = "No" AND `tabAccount`.debit_or_credit = "Credit" AND `tabAccount`.company = "'+ cstr(doc.company) +'" AND `tabAccount`.freeze_account = "No" AND `tabAccount`.group_or_ledger = "Ledger" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name ASC LIMIT 50';
+	return 'SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.is_pl_account = "No" AND `tabAccount`.debit_or_credit = "Credit" AND `tabAccount`.company = "'+ cstr(doc.company) +'" AND ifnull(`tabAccount`.freeze_account, "No") = "No" AND `tabAccount`.group_or_ledger = "Ledger" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name ASC LIMIT 50';
 }
diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index 1b59bc6..f4cf47d 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -8,11 +8,11 @@
 # 
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
 # GNU General Public License for more details.
 # 
 # You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+# along with this program.	If not, see <http://www.gnu.org/licenses/>.
 
 # Please edit this list and import only required elements
 import webnotes
@@ -34,179 +34,165 @@
 
 
 class DocType:
-  def __init__(self,d,dl):
-    self.doc, self.doclist = d, dl
-    self.td, self.tc = 0, 0
-    self.year_start_date = ''
-    self.year_end_date = ''
+	def __init__(self,d,dl):
+		self.doc, self.doclist = d, dl
+		self.td, self.tc = 0, 0
+		self.year_start_date = ''
+		self.year_end_date = ''
 
 
-  # Validate Account Head
-  #============================================================
-  def validate_account_head(self):
-    acc_det = sql("select debit_or_credit, is_pl_account, group_or_ledger, company from `tabAccount` where name = '%s'" % (self.doc.closing_account_head))
+	def validate_account_head(self):
+		acc_det = sql("select debit_or_credit, is_pl_account, group_or_ledger, company \
+			from `tabAccount` where name = '%s'" % (self.doc.closing_account_head))
 
-    # Account should be under liability 
-    if cstr(acc_det[0][0]) != 'Credit' or cstr(acc_det[0][1]) != 'No':
-      msgprint("Account: %s must be created under 'Source of Funds'" % self.doc.closing_account_head)
-      raise Exception
-   
-    # Account must be a ledger
-    if cstr(acc_det[0][2]) != 'Ledger':
-      msgprint("Account %s must be a ledger" % self.doc.closing_account_head)
-      raise Exception 
-    
-    # Account should belong to company selected 
-    if cstr(acc_det[0][3]) != self.doc.company:
-      msgprint("Account %s does not belong to Company %s ." % (self.doc.closing_account_head, self.doc.company))
-      raise Exception 
+		# Account should be under liability 
+		if cstr(acc_det[0][0]) != 'Credit' or cstr(acc_det[0][1]) != 'No':
+			msgprint("Account: %s must be created under 'Source of Funds'" % self.doc.closing_account_head)
+			raise Exception
+	 
+		# Account must be a ledger
+		if cstr(acc_det[0][2]) != 'Ledger':
+			msgprint("Account %s must be a ledger" % self.doc.closing_account_head)
+			raise Exception 
+		
+		# Account should belong to company selected 
+		if cstr(acc_det[0][3]) != self.doc.company:
+			msgprint("Account %s does not belong to Company %s ." % (self.doc.closing_account_head, self.doc.company))
+			raise Exception 
 
-  # validate posting date
-  #=============================================================
-  def validate_posting_date(self):
-    yr = sql("select start_date, end_date from `tabPeriod` where period_name = '%s'" % (self.doc.fiscal_year))
-    self.year_start_date = yr and yr[0][0] or ''
-    self.year_end_date = yr and yr[0][1] or ''
-    
-    # Posting Date should be within closing year
-    if getdate(self.doc.posting_date) < self.year_start_date or getdate(self.doc.posting_date) > self.year_end_date:
-      msgprint("Posting Date should be within Closing Fiscal Year")
-      raise Exception
 
-    # Period Closing Entry
-    pce = sql("select name from `tabPeriod Closing Voucher` where posting_date > '%s' and fiscal_year = '%s' and docstatus = 1" % (self.doc.posting_date, self.doc.fiscal_year))
-    if pce and pce[0][0]:
-      msgprint("Another Period Closing Entry: %s has been made after posting date: %s" % (cstr(pce[0][0]), self.doc.posting_date))
-      raise Exception
-     
-  # Validate closing entry requirement
-  #==========================================================
-  def validate_pl_balances(self):
-    income_bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1, tabAccount t2 where t1.account = t2.name and t1.posting_date between '%s' and '%s' and t2.debit_or_credit = 'Credit' and t2.group_or_ledger = 'Ledger' and ifnull(t2.freeze_account, 'No') = 'No' and t2.is_pl_account = 'Yes' and t2.docstatus < 2 and t2.company = '%s'" % (self.year_start_date, self.doc.posting_date, self.doc.company))
-    expense_bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1, tabAccount t2 where t1.account = t2.name and t1.posting_date between '%s' and '%s' and t2.debit_or_credit = 'Debit' and t2.group_or_ledger = 'Ledger' and ifnull(t2.freeze_account, 'No') = 'No' and t2.is_pl_account = 'Yes' and t2.docstatus < 2 and t2.company = '%s'" % (self.year_start_date, self.doc.posting_date, self.doc.company))
-    
-    income_bal = income_bal and income_bal[0][0] or 0
-    expense_bal = expense_bal and expense_bal[0][0] or 0
-    
-    if not income_bal and not expense_bal:
-      msgprint("Both Income and Expense balances are zero. No Need to make Period Closing Entry.")
-      raise Exception
-    
-  # Get account (pl) specific balance
-  #===========================================================
-  def get_pl_balances(self, d_or_c):
-	acc_bal = sql("select  t1.account, sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1, `tabAccount` t2 where t1.account = t2.name and t2.group_or_ledger = 'Ledger' and ifnull(t2.freeze_account, 'No') = 'No' and ifnull(t2.is_pl_account, 'No') = 'Yes' and ifnull(is_cancelled, 'No') = 'No' and t2.debit_or_credit = '%s' and t2.docstatus < 2 and t2.company = '%s' and t1.posting_date between '%s' and '%s' group by t1.account " % (d_or_c, self.doc.company, self.year_start_date, self.doc.posting_date))
-	return acc_bal
+	def validate_posting_date(self):
+		yr = sql("select start_date, end_date from `tabPeriod` where period_name = '%s'" % (self.doc.fiscal_year))
+		self.year_start_date = yr and yr[0][0] or ''
+		self.year_end_date = yr and yr[0][1] or ''
+		
+		# Posting Date should be within closing year
+		if getdate(self.doc.posting_date) < self.year_start_date or getdate(self.doc.posting_date) > self.year_end_date:
+			msgprint("Posting Date should be within Closing Fiscal Year")
+			raise Exception
 
-   
-  # Makes GL Entries
-  # ==========================================================
-  def make_gl_entries(self, acc_det):
-    for a in acc_det:
-      if flt(a[1]):
-        fdict = {
-	        'account': a[0], 
-	        'cost_center': '', 
-	        'against': '', 
-	        'debit': flt(a[1]) < 0 and -1*flt(a[1]) or 0,
-	        'credit': flt(a[1]) > 0 and flt(a[1]) or 0,
-	        'remarks': self.doc.remarks, 
-	        'voucher_type': self.doc.doctype, 
-	        'voucher_no': self.doc.name, 
-	        'transaction_date': self.doc.transaction_date, 
-	        'posting_date': self.doc.posting_date, 
-	        'fiscal_year': self.doc.fiscal_year, 
-	        'against_voucher': '', 
-	        'against_voucher_type': '', 
-	        'company': self.doc.company, 
-	        'is_opening': 'No', 
-	        'aging_date': self.doc.posting_date
-        }
-      
-        self.save_entry(fdict)
-   
+		# Period Closing Entry
+		pce = sql("select name from `tabPeriod Closing Voucher` \
+			where posting_date > '%s' and fiscal_year = '%s' and docstatus = 1" \
+			% (self.doc.posting_date, self.doc.fiscal_year))
+		if pce and pce[0][0]:
+			msgprint("Another Period Closing Entry: %s has been made after posting date: %s"\
+			 % (cstr(pce[0][0]), self.doc.posting_date))
+			raise Exception
+		 
+		
+	def validate_pl_balances(self):
+		income_bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) \
+			from `tabGL Entry` t1, tabAccount t2 where t1.account = t2.name \
+			and t1.posting_date between '%s' and '%s' and t2.debit_or_credit = 'Credit' \
+			and t2.group_or_ledger = 'Ledger' and t2.is_pl_account = 'Yes' and t2.docstatus < 2 \
+			and t2.company = '%s'" % (self.year_start_date, self.doc.posting_date, self.doc.company))
+			
+		expense_bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) \
+			from `tabGL Entry` t1, tabAccount t2 where t1.account = t2.name \
+			and t1.posting_date between '%s' and '%s' and t2.debit_or_credit = 'Debit' \
+			and t2.group_or_ledger = 'Ledger' and t2.is_pl_account = 'Yes' and t2.docstatus < 2 \
+			and t2.company = '%s'" % (self.year_start_date, self.doc.posting_date, self.doc.company))
+		
+		income_bal = income_bal and income_bal[0][0] or 0
+		expense_bal = expense_bal and expense_bal[0][0] or 0
+		
+		if not income_bal and not expense_bal:
+			msgprint("Both Income and Expense balances are zero. No Need to make Period Closing Entry.")
+			raise Exception
+		
+		
+	def get_pl_balances(self, d_or_c):
+		"""Get account (pl) specific balance"""
+		acc_bal = sql("select	t1.account, sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) \
+			from `tabGL Entry` t1, `tabAccount` t2 where t1.account = t2.name and t2.group_or_ledger = 'Ledger' \
+ 			and ifnull(t2.is_pl_account, 'No') = 'Yes' and ifnull(is_cancelled, 'No') = 'No' \
+			and t2.debit_or_credit = '%s' and t2.docstatus < 2 and t2.company = '%s' \
+			and t1.posting_date between '%s' and '%s' group by t1.account " \
+			% (d_or_c, self.doc.company, self.year_start_date, self.doc.posting_date))
+		return acc_bal
+
+	 
+	def make_gl_entries(self, acc_det):
+		for a in acc_det:
+			if flt(a[1]):
+				fdict = {
+					'account': a[0], 
+					'cost_center': '', 
+					'against': '', 
+					'debit': flt(a[1]) < 0 and -1*flt(a[1]) or 0,
+					'credit': flt(a[1]) > 0 and flt(a[1]) or 0,
+					'remarks': self.doc.remarks, 
+					'voucher_type': self.doc.doctype, 
+					'voucher_no': self.doc.name, 
+					'transaction_date': self.doc.transaction_date, 
+					'posting_date': self.doc.posting_date, 
+					'fiscal_year': self.doc.fiscal_year, 
+					'against_voucher': '', 
+					'against_voucher_type': '', 
+					'company': self.doc.company, 
+					'is_opening': 'No', 
+					'aging_date': self.doc.posting_date
+				}
+			
+				self.save_entry(fdict)
+	 
+
+	def save_entry(self, fdict, is_cancel = 'No'):
+		# Create new GL entry object and map values
+		le = Document('GL Entry')
+		for k in fdict:
+			le.fields[k] = fdict[k]
+		
+		le_obj = get_obj(doc=le)
+		# validate except on_cancel
+		if is_cancel == 'No':
+			le_obj.validate()
+			
+			# update total debit / credit except on_cancel
+			self.td += flt(le.credit)
+			self.tc += flt(le.debit)
+
+		# save
+		le.save(1)
+		le_obj.on_update(adv_adj = '', cancel = '')
  
-  # Save GL Entry
-  # ==========================================================
-  def save_entry(self, fdict, is_cancel = 'No'):
-    # Create new GL entry object and map values
-    le = Document('GL Entry')
-    for k in fdict:
-      le.fields[k] = fdict[k]
-    
-    le_obj = get_obj(doc=le)
-    # validate except on_cancel
-    if is_cancel == 'No':
-      le_obj.validate()
-      
-      # update total debit / credit except on_cancel
-      self.td += flt(le.credit)
-      self.tc += flt(le.debit)
+		 	
+	def validate(self):
+		# validate account head
+		self.validate_account_head()
 
-    # save
-    le.save(1)
-    le_obj.on_update(adv_adj = '', cancel = '')
-    
+		# validate posting date
+		self.validate_posting_date()
 
-  # Reposting Balances
-  # ==========================================================
-  def repost_account_balances(self):
-    # Get Next Fiscal Year
-    fy = sql("select name, is_fiscal_year_closed from `tabFiscal Year` where name = '%s' and past_year = '%s'" % (self.doc.next_fiscal_year, self.doc.fiscal_year))
-    if not fy:
-      msgprint("There is no Fiscal Year with Name " + cstr(self.doc.next_fiscal_year) + " and Past Year " + cstr(self.doc.fiscal_year))
-      raise Exception
-   
-    if fy and fy[0][1] == 'Yes':
-      msgprint("Fiscal Year %s has been closed." % cstr(fy[1]))
-      raise Exception
-    
-    # Repost Balances
-    get_obj('Fiscal Year', fy[0][0]).repost()
- 
-     
-  # Validation
-  # ===========================================================
-  def validate(self):
-  
-    # validate account head
-    self.validate_account_head()
-
-    # validate posting date
-    self.validate_posting_date()
-
-    # check if pl balance:
-    self.validate_pl_balances()
+		# check if pl balance:
+		self.validate_pl_balances()
 
 
-  # On Submit
-  # ===========================================================
-  def on_submit(self):
-    
-    # Makes closing entries for Expense Account
-    in_acc_det = self.get_pl_balances('Credit')
-    self.make_gl_entries(in_acc_det)
+	def on_submit(self):
+		
+		# Makes closing entries for Expense Account
+		in_acc_det = self.get_pl_balances('Credit')
+		self.make_gl_entries(in_acc_det)
 
-    # Makes closing entries for Expense Account
-    ex_acc_det = self.get_pl_balances('Debit')
-    self.make_gl_entries(ex_acc_det)
+		# Makes closing entries for Expense Account
+		ex_acc_det = self.get_pl_balances('Debit')
+		self.make_gl_entries(ex_acc_det)
 
 
-    # Makes Closing entry for Closing Account Head
-    bal = self.tc - self.td
-    self.make_gl_entries([[self.doc.closing_account_head, flt(bal)]])
+		# Makes Closing entry for Closing Account Head
+		bal = self.tc - self.td
+		self.make_gl_entries([[self.doc.closing_account_head, flt(bal)]])
 
 
-  # On Cancel
-  # =============================================================
-  def on_cancel(self):
-    # get all submit entries of current closing entry voucher
-    gl_entries = sql("select account, debit, credit from `tabGL Entry` where voucher_type = 'Period Closing Voucher' and voucher_no = '%s' and ifnull(is_cancelled, 'No') = 'No'" % (self.doc.name))
+	def on_cancel(self):
+		# get all submit entries of current closing entry voucher
+		gl_entries = sql("select account, debit, credit from `tabGL Entry` where voucher_type = 'Period Closing Voucher' and voucher_no = '%s' and ifnull(is_cancelled, 'No') = 'No'" % (self.doc.name))
 
-    # Swap Debit & Credit Column and make gl entry
-    for gl in gl_entries:
-      fdict = {'account': gl[0], 'cost_center': '', 'against': '', 'debit': flt(gl[2]), 'credit' : flt(gl[1]), 'remarks': self.doc.cancel_reason, 'voucher_type': self.doc.doctype, 'voucher_no': self.doc.name, 'transaction_date': self.doc.transaction_date, 'posting_date': self.doc.posting_date, 'fiscal_year': self.doc.fiscal_year, 'against_voucher': '', 'against_voucher_type': '', 'company': self.doc.company, 'is_opening': 'No', 'aging_date': 'self.doc.posting_date'}
-      self.save_entry(fdict, is_cancel = 'Yes')
+		# Swap Debit & Credit Column and make gl entry
+		for gl in gl_entries:
+			fdict = {'account': gl[0], 'cost_center': '', 'against': '', 'debit': flt(gl[2]), 'credit' : flt(gl[1]), 'remarks': self.doc.cancel_reason, 'voucher_type': self.doc.doctype, 'voucher_no': self.doc.name, 'transaction_date': self.doc.transaction_date, 'posting_date': self.doc.posting_date, 'fiscal_year': self.doc.fiscal_year, 'against_voucher': '', 'against_voucher_type': '', 'company': self.doc.company, 'is_opening': 'No', 'aging_date': 'self.doc.posting_date'}
+			self.save_entry(fdict, is_cancel = 'Yes')
 
-    # Update is_cancelled = 'Yes' to all gl entries for current voucher
-    sql("update `tabGL Entry` set is_cancelled = 'Yes' where voucher_type = '%s' and voucher_no = '%s'" % (self.doc.doctype, self.doc.name))
+		# Update is_cancelled = 'Yes' to all gl entries for current voucher
+		sql("update `tabGL Entry` set is_cancelled = 'Yes' where voucher_type = '%s' and voucher_no = '%s'" % (self.doc.doctype, self.doc.name))
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.txt b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
index c70745e..f56c1b0 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
+++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-04-13 11:56:17',
+		'creation': '2012-06-11 12:09:52',
 		'docstatus': 0,
-		'modified': '2012-05-31 11:38:17',
+		'modified': '2012-07-10 14:21:21',
 		'modified_by': u'Administrator',
 		'owner': u'jai@webnotestech.com'
 	},
@@ -273,42 +273,5 @@
 		'permlevel': 0,
 		'print_hide': 1,
 		'search_index': 0
-	},
-
-	# DocField
-	{
-		'doctype': u'DocField',
-		'fieldname': u'repost_account_balances',
-		'fieldtype': u'Section Break',
-		'label': u'Repost Account Balances',
-		'oldfieldtype': u'Section Break',
-		'options': u'Simple',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'allow_on_submit': 1,
-		'doctype': u'DocField',
-		'fieldname': u'next_fiscal_year',
-		'fieldtype': u'Select',
-		'label': u'Fiscal Year (For Reposting)',
-		'oldfieldname': u'next_fiscal_year',
-		'oldfieldtype': u'Select',
-		'options': u'link:Fiscal Year',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'allow_on_submit': 1,
-		'colour': u'White:FFF',
-		'doctype': u'DocField',
-		'fieldname': u'repost',
-		'fieldtype': u'Button',
-		'label': u'Repost',
-		'oldfieldtype': u'Button',
-		'options': u'repost_account_balances',
-		'permlevel': 0
 	}
 ]
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
index 88af72b..0dddb8a 100644
--- a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
+++ b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-04-13 11:56:18',
+		'creation': '2012-06-08 16:07:55',
 		'docstatus': 0,
-		'modified': '2012-06-07 19:05:06',
+		'modified': '2012-07-09 11:00:18',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -70,6 +70,17 @@
 	# DocField
 	{
 		'doctype': u'DocField',
+		'fieldname': u'customer_item_code',
+		'fieldtype': u'Data',
+		'hidden': 1,
+		'label': u"Customer's Item Code",
+		'permlevel': 1,
+		'print_hide': 1
+	},
+
+	# DocField
+	{
+		'doctype': u'DocField',
 		'fieldname': u'item_name',
 		'fieldtype': u'Data',
 		'in_filter': 0,
diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.txt b/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.txt
index b8c8a5e..2a25a6a 100644
--- a/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.txt
+++ b/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-03-27 14:35:48',
+		'creation': '2012-05-15 12:14:34',
 		'docstatus': 0,
-		'modified': '2012-03-27 14:35:48',
+		'modified': '2012-07-04 13:27:05',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -23,7 +23,7 @@
 		'section_style': u'Tray',
 		'server_code_error': u' ',
 		'show_in_menu': 0,
-		'version': 20
+		'version': 1
 	},
 
 	# These values are common for all DocField
@@ -213,11 +213,12 @@
 		'doctype': u'DocField',
 		'fieldname': u'included_in_print_rate',
 		'fieldtype': u'Check',
-		'label': u'Included in Print Rate',
+		'label': u'Is this Tax included in Basic Rate?',
 		'no_column': 0,
 		'no_copy': 1,
 		'permlevel': 0,
 		'print_hide': 1,
-		'report_hide': 1
+		'report_hide': 1,
+		'width': u'150px'
 	}
 ]
\ No newline at end of file
diff --git a/erpnext/patches/july_2012/deprecate_import_data_control.py b/erpnext/patches/july_2012/deprecate_import_data_control.py
new file mode 100644
index 0000000..d0cd7de
--- /dev/null
+++ b/erpnext/patches/july_2012/deprecate_import_data_control.py
@@ -0,0 +1,10 @@
+def execute():
+	"""
+		deprecate:
+		* doctype - import data control
+		* page - import data (old)
+	"""
+	import webnotes
+	from webnotes.model import delete_doc
+	delete_doc('DocType', 'Import Data Control')
+	delete_doc('Page', 'Import Data')
\ No newline at end of file
diff --git a/erpnext/patches/patch_list.py b/erpnext/patches/patch_list.py
index 0307a0f..ab95e95 100644
--- a/erpnext/patches/patch_list.py
+++ b/erpnext/patches/patch_list.py
@@ -481,5 +481,10 @@
 		'patch_module': 'patches.july_2012',
 		'patch_file': 'packing_list_cleanup_and_serial_no',
 		'description': "packing list cleanup and serial no status update"
-	},	
+	},
+	{
+		'patch_module': 'patches.july_2012',
+		'patch_file': 'deprecate_import_data_control',
+		'description': "deprecate doctype - Import Data Control and page - Import Data"
+	},
 ]
\ No newline at end of file
diff --git a/erpnext/selling/doctype/opportunity/opportunity.js b/erpnext/selling/doctype/opportunity/opportunity.js
index c672aa1..4487c89 100644
--- a/erpnext/selling/doctype/opportunity/opportunity.js
+++ b/erpnext/selling/doctype/opportunity/opportunity.js
@@ -140,79 +140,8 @@
 	else 
 		return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
 }
-	
- //Fetch Item Details
-//====================================================================================================================
-cur_frm.cscript.item_code = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	if (d.item_code) {
-		get_server_fields('get_item_details',d.item_code,'enquiry_details',doc,cdt,cdn,1);
-	}
-}
 
-/*
- //Fetch Customer Details
-//======================================================================================================================
-cur_frm.cscript.customer = function(doc, cdt, cdn){
-	if (doc.customer) {
-		get_server_fields('get_cust_address',doc.customer,'',doc,cdt,cdn,1);
-	}
-}
-*/
-
-/*
-//=======================================================================================================================
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE `tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'" AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
-}
-*/
-
-/*
-//=======================================================================================================================
-cur_frm.cscript.contact_person = function(doc, cdt, cdn){
-	if (doc.contact_person) {
-		arg = {};
-		arg.contact_person = doc.contact_person;
-		arg.customer = doc.customer;
-		get_server_fields('get_contact_details',docstring(arg),'',doc,cdt,cdn,1);
-	}
-}
-*/
-
-/*
-// hide - unhide fields based on lead or customer..
-//=======================================================================================================================
-cur_frm.cscript.clear_values = function(doc,cdt,cdn) {
-	if(doc.enquiry_from == 'Lead') {
-		doc.customer = doc.customer_name = doc.contact_person = doc.customer_group = "";
-	}
-	else if(doc.enquiry_from == 'Customer') {
-		doc.lead =	doc.lead_name = "";
-	}
-	refresh_many(['lead','lead_name','customer','customer_name','contact_person','customer_group']);
-}
-*/
-
-/*
-//================ hide - unhide fields on basis of enquiry from either lead or customer =============================== 
-cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){
-	cur_frm.cscript.clear_values(doc,cdt,cdn);
-	 doc.address = doc.territory = doc.contact_no = doc.email_id = "";
-	 refresh_many(['territory','address','contact_no','email_id']);
-}
-*/
-
-/*
-//================ create new contact ============================================================================
-cur_frm.cscript.new_contact = function(){
-	tn = createLocal('Contact');
-	locals['Contact'][tn].is_customer = 1;
-	if(doc.customer) locals['Contact'][tn].customer = doc.customer;
-	loaddoc('Contact', tn);
-}
-*/
- // Create New Quotation
-// =======================================================================================================================
+// Create New Quotation
 cur_frm.cscript['Create Quotation'] = function(){
 	n = createLocal("Quotation");
 	$c('dt_map', args={
@@ -284,39 +213,5 @@
 }
 
 //get query select Territory
-//=======================================================================================================================
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
 	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';}
-
-/*
-//===================== Opportunity From validation - either customer or lead is mandatory =====================================
-cur_frm.cscript.enq_frm_validate = function(doc,cdt,cdn){
-	
-	if(doc.enquiry_from == 'Lead'){
-		if(!doc.lead){
-			alert("Lead is mandatory.");	
-			validated = false; 
-		}
-	}
-	else if(doc.enquiry_from == 'Customer'){
-			if(!doc.customer){
-			alert("Customer is mandatory.");
-			validated = false;
-		}
-		else if(!doc.contact_person){
-			alert("Contact Person is mandatory.");
-			validated = false;
-		}
-		else if(!doc.customer_group){
-			alert("Customer Group is mandatory.");
-			validated = false;
-		}
-	} 
-}
-*/
-
-//===================validation function ==============================================================================
-
-cur_frm.cscript.validate = function(doc,cdt,cdn){
-	//cur_frm.cscript.enq_frm_validate(doc,cdt,cdn);
-}
diff --git a/erpnext/selling/doctype/quotation_item/quotation_item.txt b/erpnext/selling/doctype/quotation_item/quotation_item.txt
index d5ece1f..6ae657c 100644
--- a/erpnext/selling/doctype/quotation_item/quotation_item.txt
+++ b/erpnext/selling/doctype/quotation_item/quotation_item.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-06-04 15:40:56',
+		'creation': '2012-06-08 16:07:57',
 		'docstatus': 0,
-		'modified': '2012-06-07 17:58:39',
+		'modified': '2012-07-09 11:04:47',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -63,6 +63,17 @@
 	# DocField
 	{
 		'doctype': u'DocField',
+		'fieldname': u'customer_item_code',
+		'fieldtype': u'Data',
+		'hidden': 1,
+		'label': u"Customer's Item Code",
+		'permlevel': 1,
+		'print_hide': 1
+	},
+
+	# DocField
+	{
+		'doctype': u'DocField',
 		'fieldname': u'item_name',
 		'fieldtype': u'Data',
 		'in_filter': 1,
diff --git a/erpnext/selling/doctype/sales_common/sales_common.py b/erpnext/selling/doctype/sales_common/sales_common.py
index 718bc86..74963fb 100644
--- a/erpnext/selling/doctype/sales_common/sales_common.py
+++ b/erpnext/selling/doctype/sales_common/sales_common.py
@@ -163,6 +163,15 @@
 		if ret['warehouse'] or ret['reserved_warehouse']:
 			av_qty = self.get_available_qty({'item_code': args['item_code'], 'warehouse': ret['warehouse'] or ret['reserved_warehouse']})
 			ret.update(av_qty)
+			
+		# get customer code for given item from Item Customer Detail
+		customer_item_code_row = webnotes.conn.sql("""\
+			select ref_code from `tabItem Customer Detail`
+			where parent = %s and customer_name = %s""",
+			(args['item_code'], obj.doc.customer))
+		if customer_item_code_row and customer_item_code_row[0][0]:
+			ret['customer_item_code'] = customer_item_code_row[0][0]
+		
 		return ret
 
 
@@ -411,7 +420,8 @@
 							'reserved_qty': (flt(p.qty)/qty)*(reserved_qty),
 							'uom': p.uom,
 							'batch_no': p.batch_no,
-							'serial_no': p.serial_no
+							'serial_no': p.serial_no,
+							'name': d.name
 						})
 			else:
 				il.append({
@@ -422,7 +432,8 @@
 					'reserved_qty': reserved_qty,
 					'uom': d.stock_uom,
 					'batch_no': d.batch_no,
-					'serial_no': d.serial_no
+					'serial_no': d.serial_no,
+					'name': d.name
 				})
 		return il
 
@@ -532,7 +543,9 @@
 		# delete from db
 		webnotes.conn.sql("""\
 			delete from `tabDelivery Note Packing Item`
-			where name in ("%s")""" % '", "'.join(delete_list))
+			where name in (%s)"""
+			% (", ".join(["%s"] * len(delete_list))),
+			tuple(delete_list))
 
 	# Get total in words
 	# ==================================================================	
diff --git a/erpnext/selling/doctype/sales_order_item/sales_order_item.txt b/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
index 1d2f358..1c80698 100644
--- a/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
+++ b/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-04-13 11:56:28',
+		'creation': '2012-06-08 16:07:58',
 		'docstatus': 0,
-		'modified': '2012-06-07 18:04:52',
+		'modified': '2012-07-09 11:05:16',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -60,6 +60,17 @@
 	# DocField
 	{
 		'doctype': u'DocField',
+		'fieldname': u'customer_item_code',
+		'fieldtype': u'Data',
+		'hidden': 1,
+		'label': u"Customer's Item Code",
+		'permlevel': 1,
+		'print_hide': 1
+	},
+
+	# DocField
+	{
+		'doctype': u'DocField',
 		'fieldname': u'item_name',
 		'fieldtype': u'Data',
 		'label': u'Item Name',
diff --git a/erpnext/setup/doctype/email_digest/email_digest.py b/erpnext/setup/doctype/email_digest/email_digest.py
index b0f0e9f..1e382d1 100644
--- a/erpnext/setup/doctype/email_digest/email_digest.py
+++ b/erpnext/setup/doctype/email_digest/email_digest.py
@@ -255,7 +255,10 @@
 				args['sum_if_reqd'] = "IFNULL(SUM(IFNULL(%(sum_col)s, 0)), 0) AS '%(sum_col)s'," % args
 			
 			if args['type'] == 'new_transactions':
-				args['company_condition'] = ''
+				# tabFeed doesn't have company column
+				# using this arg to set condition of feed_type as null
+				# so that comments, logins and assignments are not counted
+				args['company_condition'] = "feed_type IS NULL AND"
 			else:
 				args['company_condition'] = "company = '%(company)s' AND" % args
 				
@@ -418,8 +421,7 @@
 				sender='notifications+email_digest@erpnext.com',
 				reply_to='support@erpnext.com',
 				subject=self.doc.frequency + ' Digest',
-				msg=email_body,
-				from_defs=1
+				msg=email_body
 			)
 		except Exception, e:
 			webnotes.msgprint('There was a problem in sending your email. Please contact support@erpnext.com')
diff --git a/erpnext/setup/doctype/email_settings/email_settings.py b/erpnext/setup/doctype/email_settings/email_settings.py
index 755b91d..118dba2 100644
--- a/erpnext/setup/doctype/email_settings/email_settings.py
+++ b/erpnext/setup/doctype/email_settings/email_settings.py
@@ -54,24 +54,13 @@
 				webnotes.msgprint(err_msg)
 				raise e
 			
+			# exceptions are handled in smtp_connect
+			sess = out_email.smtp_connect()
+			
 			try:
-				sess = out_email.smtp_connect()
-				
-				try:
-					sess.quit()
-				except:
-					pass
-			except _socket.error, e:
-				# Invalid mail server -- due to refusing connection
-				webnotes.msgprint('Invalid Outgoing Mail Server or Port. Please rectify and try again.')
-				raise e
-			except smtplib.SMTPAuthenticationError, e:
-				webnotes.msgprint('Invalid Login Id or Mail Password. Please rectify and try again.')
-				raise e
-			except smtplib.SMTPException, e:
-				webnotes.msgprint('There is something wrong with your Outgoing Mail Settings. \
-				Please contact us at support@erpnext.com')
-				raise e
+				sess.quit()
+			except:
+				pass
 		
 
 	def validate_incoming(self):
diff --git a/erpnext/setup/doctype/import_data_control/__init__.py b/erpnext/setup/doctype/import_data_control/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/setup/doctype/import_data_control/__init__.py
+++ /dev/null
diff --git a/erpnext/setup/doctype/import_data_control/import_data_control.py b/erpnext/setup/doctype/import_data_control/import_data_control.py
deleted file mode 100644
index 9e7461e..0000000
--- a/erpnext/setup/doctype/import_data_control/import_data_control.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ERPNext - web based ERP (http://erpnext.com)
-# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
-# 
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-# 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, getchildren, make_autoname
-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
-
-  def get_master_lst(self):
-    
-    return [r[0] for r in sql("select name from `tabDocType` where document_type = 'Master'")]
-
-  def get_child_lst(self,nm):
-    res = [nm]
-    
-    ret=sql("select options from `tabDocField` where parent='%s' and fieldtype = 'Table'"%nm)
-    for r in ret:
-      res.append(r[0])
-    return res
\ No newline at end of file
diff --git a/erpnext/setup/doctype/import_data_control/import_data_control.txt b/erpnext/setup/doctype/import_data_control/import_data_control.txt
deleted file mode 100644
index fa19e10..0000000
--- a/erpnext/setup/doctype/import_data_control/import_data_control.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-# DocType, Import Data Control
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2012-03-27 14:36:21',
-		'docstatus': 0,
-		'modified': '2012-03-27 14:36:21',
-		'modified_by': u'Administrator',
-		'owner': u'harshada@webnotestech.com'
-	},
-
-	# These values are common for all DocType
-	{
-		'colour': u'White:FFF',
-		'doctype': 'DocType',
-		'issingle': 1,
-		'module': u'Setup',
-		'name': '__common__',
-		'section_style': u'Simple',
-		'server_code_error': u' ',
-		'version': 12
-	},
-
-	# DocType, Import Data Control
-	{
-		'doctype': 'DocType',
-		'name': u'Import Data Control'
-	}
-]
\ No newline at end of file
diff --git a/erpnext/setup/page/import_data/__init__.py b/erpnext/setup/page/import_data/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/setup/page/import_data/__init__.py
+++ /dev/null
diff --git a/erpnext/setup/page/import_data/import_data.html b/erpnext/setup/page/import_data/import_data.html
deleted file mode 100644
index b655442..0000000
--- a/erpnext/setup/page/import_data/import_data.html
+++ /dev/null
@@ -1,88 +0,0 @@
-<div class="layout_wrapper">
-<div id="di_header"></div>
-<div style="margin: 8px">
-<table style="border-collapse: collapse;" border="0">
-<tbody>
-<tr>
-<td style="border: 1px solid #aaaaaa; padding: 4px; width: 60%;">
-	
-<form action="index.cgi" enctype="multipart/form-data" method="POST" target="ImportIFrame"> <input name="cmd" type="hidden" value="import_csv" /> 
-<h3 style="background-color: #EEF; padding: 2px;">Step 1. Download Template</h3>
-<select id="import_template" style="margin: 10px;"> <option>Select Master...</option> </select>
-
-<div style="margin: 10px; margin-top: 0px;"><input name="overwrite" type="checkbox"/> Do you want to over-write records? <br><span style='color:orange'>Warning: Over-writing the data of child tables, will delete all old entries from child tables. For more info see below</span></div>
-<div id="child_tab_lst"></div>
-<h3 style="background-color: #EEF; padding: 2px;">Step 2. Upload and Import</h3>
-<table style="width: 480px;" border="0" cellspacing="10px">
-<tbody>
-<tr>
-<td width="200px">Select CSV File to be imported</td>
-<td><input name="csv_file" type="file" /></td>
-</tr>
-<tr>
-<td width="200px">Date format in source CSV</td>
-<td><select name="dateformat"> <option value="yyyy-mm-dd">yyyy-mm-dd</option> <option value="mm/dd/yyyy">mm/dd/yyyy</option> <option value="mm/dd/yy">mm/dd/yy</option> <option value="dd-mm-yyyy">dd-mm-yyyy</option> <option value="dd/mm/yyyy">dd/mm/yyyy</option> </select></td>
-</tr>
-<tr>
-<td>&nbsp;</td>
-<td>
-<div id="import_btn"><input type="submit" value="Import" /></div>
-</td>
-</tr>
-</tbody>
-</table>
-</form>
-<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>
-		<li>Fill in the data in the template. You can remove columns that are not relevant</li>
-		<li>Save the template in CSV format</li>
-		<li>Select the saved CSV file, identify the date format if any</li>
-		<li>Click on "Import"</li>
-	</ol>
-	<br />
-	<h4>Over-writing Guide</h4>
-	<ol>
-		<li>To over-write data, click on "Do you want to over-write records?" and then download template</li>
-		<li>To over-write parent table data, mention existing ID in "Name" column</li>
-		<li>Over-writing of child table data will delete all previous data from child table of those parents which you are importing. So before over-writing child tables, take a backup of the child table data by exporting from report builder. Re-import all rows of the child table for a particular parent.<br>For example: If you want to overwrite tax rate for tax account "VAT" ifor item: ITEM001 and suppose there are 3 rows in "Item Tax" table for item : ITEM001. While overwriting the system will delete all 3 rows. So, you have to re-import all 3 rows for that item.</li>
-		<li>Over-write checkbox will be checked while importing</li>
-	</ol>
-	<br />
-	<h4>Do you have Non-English data?</h4>
-	You may need to save the file with UTF-8 encoding for data to be imported correctly.
-	<br /><br />
-	Microsoft Excel Users:<br />
-	There is no obvious way of saving a CSV file with UTF-8 encoding.<br />
-	You will need to follow these steps:
-	<ol>
-		<li>In Excel, save the file in CSV (Comma Delimited) format</li>
-		<li>Open this saved file in Notepad</li>
-		<li>Click on File -&gt; Save As</li>
-		<li>File Name: &lt;your filename&gt;.csv<br />
-			Save as type: Text Documents (*.txt)<br />
-			Encoding: UTF-8
-		</li>
-		<li>Click on Save</li>
-	</ol>
-	<br />
-	OpenOffice or LibreOffice Users:<br />
-	<ol>
-		<li>While saving as CSV, check "Edit Filter Settings".</li>
-		<li>You will be prompted for Encoding.</li>
-		<li>Make sure it is "UTF-8" and click on OK.</li>
-	</ol>
-</div>
-</td>
-<td style="border: 1px solid #AAA; padding: 4px;">
-<h3>Import Log:</h3>
-<div id="import_result_area">
-<iframe name="ImportIFrame" style="border: 0px; height: 620px; width: 100%"></iframe>
-</div>
-</td>
-</tr>
-</tbody>
-</table>
-</div>
-</div>
diff --git a/erpnext/setup/page/import_data/import_data.js b/erpnext/setup/page/import_data/import_data.js
deleted file mode 100644
index 734c16d..0000000
--- a/erpnext/setup/page/import_data/import_data.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// ERPNext - web based ERP (http://erpnext.com)
-// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
-// 
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-// 
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-// 
-// You should have received a copy of the GNU General Public License
-// along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-pscript['onload_Import Data'] = function() {
-	
-	//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);
-
-			// 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:'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 = wn.request.url + '?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/erpnext/setup/page/import_data/import_data.txt b/erpnext/setup/page/import_data/import_data.txt
deleted file mode 100644
index 40baa6b..0000000
--- a/erpnext/setup/page/import_data/import_data.txt
+++ /dev/null
@@ -1,72 +0,0 @@
-# Page, Import Data
-[
-
-	# These values are common in all dictionaries
-	{
-		'creation': '2010-12-14 10:23:18',
-		'docstatus': 0,
-		'modified': '2010-12-24 11:43:02',
-		'modified_by': 'Administrator',
-		'owner': 'Administrator'
-	},
-
-	# These values are common for all Page
-	{
-		'doctype': 'Page',
-		'module': 'Setup',
-		'name': '__common__',
-		'page_name': 'Import Data',
-		'show_in_menu': 0,
-		'standard': 'Yes'
-	},
-
-	# These values are common for all Page Role
-	{
-		'doctype': 'Page Role',
-		'name': '__common__',
-		'parent': 'Import Data',
-		'parentfield': 'roles',
-		'parenttype': 'Page'
-	},
-
-	# Page, Import Data
-	{
-		'doctype': 'Page',
-		'name': 'Import Data'
-	},
-
-	# Page Role
-	{
-		'doctype': 'Page Role',
-		'idx': 1,
-		'role': 'Administrator'
-	},
-
-	# Page Role
-	{
-		'doctype': 'Page Role',
-		'idx': 2,
-		'role': 'System Manager'
-	},
-
-	# Page Role
-	{
-		'doctype': 'Page Role',
-		'idx': 3,
-		'role': 'Sales Master Manager'
-	},
-
-	# Page Role
-	{
-		'doctype': 'Page Role',
-		'idx': 4,
-		'role': 'Purchase Master Manager'
-	},
-
-	# Page Role
-	{
-		'doctype': 'Page Role',
-		'idx': 5,
-		'role': 'Material Master Manager'
-	}
-]
\ No newline at end of file
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index 45ceb24..ad95cf1 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -41,28 +41,24 @@
 		self.tname = 'Delivery Note Item'
 		self.fname = 'delivery_note_details'
 
-	# Autoname
-	# ---------
+
 	def autoname(self):
 		self.doc.name = make_autoname(self.doc.naming_series+'.#####')
 
 
-# DOCTYPE TRIGGERS FUNCTIONS
-# ==============================================================================
-#************Fiscal Year Validation*****************************
 	def validate_fiscal_year(self):
 		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
 
 
-	# ****** Get contact person details based on customer selected ****
 	def get_contact_details(self):
 		return get_obj('Sales Common').get_contact_details(self,0)
 
-	# *********** Get Commission rate of Sales Partner ****************
+
 	def get_comm_rate(self, sales_partner):
+		"""Get Commission rate of Sales Partner"""
 		return get_obj('Sales Common').get_comm_rate(sales_partner, self)
 
-	# *************** Pull Sales Order Items ************************
+
 	def pull_sales_order_details(self):
 		self.validate_prev_docname()
 		self.doclist = self.doc.clear_table(self.doclist,'other_charges')
@@ -74,15 +70,15 @@
 
 		return cstr(self.doc.sales_order_no)
 
-	# ::::: Validates that Sales Order is not pulled twice :::::::
+
 	def validate_prev_docname(self):
+		"""Validates that Sales Order is not pulled twice"""
 		for d in getlist(self.doclist, 'delivery_note_details'):
 			if self.doc.sales_order_no == d.prevdoc_docname:
 				msgprint(cstr(self.doc.sales_order_no) + " sales order details have already been pulled. ")
 				raise Exception, "Validation Error. "
 
-	#Set Actual Qty based on item code and warehouse
-	#------------------------------------------------------
+
 	def set_actual_qty(self):
 		for d in getlist(self.doclist, 'delivery_note_details'):
 			if d.item_code and d.warehouse:
@@ -90,22 +86,16 @@
 				d.actual_qty = actual_qty and flt(actual_qty[0][0]) or 0
 
 
-	# GET TERMS & CONDITIONS
-	# -------------------------------------
 	def get_tc_details(self):
 		return get_obj('Sales Common').get_tc_details(self)
 
-	#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-Delivery Note').dt_map('Project', 'Delivery Note', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Delivery Note']]")
 
-# DELIVERY NOTE DETAILS TRIGGER FUNCTIONS
-# ================================================================================
 
-	# ***************** Get Item Details ******************************
 	def get_item_details(self, args=None):
 		import json
 		args = args and json.loads(args) or {}
@@ -126,37 +116,31 @@
 		return get_obj('Sales Common').get_barcode_details(barcode)
 
 
-	# *** Re-calculates Basic Rate & amount based on Price List Selected ***
 	def get_adj_percent(self, arg=''):
+		"""Re-calculates Basic Rate & amount based on Price List Selected"""
 		get_obj('Sales Common').get_adj_percent(self)
 
 
-	# ********** Get Actual Qty of item in warehouse selected *************
 	def get_actual_qty(self,args):
+		"""Get Actual Qty of item in warehouse selected"""
 		return get_obj('Sales Common').get_available_qty(eval(args))
 
 
-# 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)
 
-	# Load Default Charges
-	# ----------------------------------------------------------
+
 	def load_default_taxes(self):
 		self.doclist = get_obj('Sales Common').load_default_taxes(self)
 
 
-	# **** Pull details from other charges master (Get Sales Taxes and Charges Master) ****
 	def get_other_charges(self):
+		"""Pull details from Sales Taxes and Charges Master"""
 		self.doclist = get_obj('Sales Common').get_other_charges(self)
 
 
-	#check in manage account if sales order required or not.
-	# ====================================================================================
 	def so_required(self):
+		"""check in manage account if sales order required or not"""
 		res = sql("select value from `tabSingles` where doctype = 'Global Defaults' and field = 'so_required'")
 		if res and res[0][0] == 'Yes':
 			 for d in getlist(self.doclist,'delivery_note_details'):
@@ -165,9 +149,6 @@
 					 raise Exception
 
 
-
-# VALIDATE
-# ====================================================================================
 	def validate(self):
 		self.so_required()
 		self.validate_fiscal_year()
@@ -177,61 +158,57 @@
 		sales_com_obj.check_active_sales_items(self)
 		sales_com_obj.get_prevdoc_date(self)
 		self.validate_mandatory()
-		#self.validate_prevdoc_details()
 		self.validate_reference_value()
 		self.validate_for_items()
 		sales_com_obj.validate_max_discount(self, 'delivery_note_details')						 #verify whether rate is not greater than max discount
 		sales_com_obj.get_allocated_sum(self)	# this is to verify that the allocated % of sales persons is 100%
 		sales_com_obj.check_conversion_rate(self)
-		# ::::::: Get total in Words ::::::::
+		
+		# 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 actual qty for each item in selected warehouse :::::::
+		# Set actual qty for each item in selected warehouse
 		self.update_current_stock()
-		# :::::: set DN status :::::::
 
 		self.doc.status = 'Draft'
 		if not self.doc.billing_status: self.doc.billing_status = 'Not Billed'
 		if not self.doc.installation_status: self.doc.installation_status = 'Not Installed'
 
-	# ************** Validate Mandatory *************************
+
 	def validate_mandatory(self):
-		# :::::::::: Amendment Date ::::::::::::::
 		if self.doc.amended_from and not self.doc.amendment_date:
 			msgprint("Please Enter Amendment Date")
 			raise Exception, "Validation Error. "
 
-	#check for does customer belong to same project as entered..
-	#-------------------------------------------------------------------------------------------------
+
 	def validate_proj_cust(self):
+		"""check for does customer belong to same project as entered.."""
 		if self.doc.project_name and self.doc.customer:
 			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 values with reference document
-	#----------------------------------------
+
 	def validate_reference_value(self):
+		"""Validate values with reference document with previous document"""
 		get_obj('DocType Mapper', 'Sales Order-Delivery Note', with_children = 1).validate_reference_value(self, self.doc.name)
 
 
-	# ******* Validate Previous Document Details ************
 	def validate_prevdoc_details(self):
 		for d in getlist(self.doclist,'delivery_note_details'):
-
 			prevdoc = d.prevdoc_doctype
 			prevdoc_docname = d.prevdoc_docname
 
 			if prevdoc_docname and prevdoc:
-				# ::::::::::: Validates Transaction Date of DN and previous doc (i.e. SO , PO, PR) *********
+				# Validates Transaction Date of DN and previous doc (i.e. SO , PO, PR)
 				trans_date = sql("select posting_date from `tab%s` where name = '%s'" %(prevdoc,prevdoc_docname))[0][0]
 				if trans_date and getdate(self.doc.posting_date) < (trans_date):
 					msgprint("Your Posting Date cannot be before "+cstr(prevdoc)+" Date.")
 					raise Exception
-				# ::::::::: Validates DN and previous doc details ::::::::::::::::::
+				# Validates DN and previous doc details
 				get_name = sql("select name from `tab%s` where name = '%s'" % (prevdoc, prevdoc_docname))
 				name = get_name and get_name[0][0] or ''
 				if name:	#check for incorrect docname
@@ -265,7 +242,6 @@
 					raise Exception, "Validation Error."
 
 
-	# ******************** Validate Items **************************
 	def validate_for_items(self):
 		check_list, chk_dupl_itm = [], []
 		for d in getlist(self.doclist,'delivery_note_details'):
@@ -289,9 +265,8 @@
 					chk_dupl_itm.append(f)
 
 
-	# check if same item, warehouse present in prevdoc
-	# ------------------------------------------------------------------
 	def validate_items_with_prevdoc(self, d):
+		"""check if same item, warehouse present in prevdoc"""
 		prev_item_dt = (d.prevdoc_doctype == 'Sales Order') and 'Sales Order Item' or 'Purchase Receipt Item'
 		data = sql("select item_code from `tab%s` where parent = '%s' and name = '%s'"\
 		 	% (prev_item_dt, d.prevdoc_docname, d.prevdoc_detail_docname))
@@ -301,7 +276,6 @@
 				% (d.item_code, d.prevdoc_docname), raise_exception=1)
 
 
-	# ********* UPDATE CURRENT STOCK *****************************
 	def update_current_stock(self):
 		for d in getlist(self.doclist, 'delivery_note_details'):
 			bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
@@ -313,8 +287,6 @@
 			d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
 
 
-# ON SUBMIT
-# =================================================================================================
 	def on_submit(self):
 		self.validate_packed_qty()
 		set(self.doc, 'message', 'Items against your Order #%s have been delivered. Delivery #%s: ' % (self.doc.po_no, self.doc.name))
@@ -327,7 +299,6 @@
 		get_obj("Sales Common").update_prevdoc_detail(1,self)
 		self.update_stock_ledger(update_stock = 1)
 
-		#------------Check Credit Limit---------------------
 		self.credit_limit()
 
 		# set DN status
@@ -357,10 +328,6 @@
 			webnotes.msgprint("Packing Error:\n" + err_msg, raise_exception=1)
 
 
-
-
-# ON CANCEL
-# =================================================================================================
 	def on_cancel(self):
 		sales_com_obj = get_obj(dt = 'Sales Common')
 		sales_com_obj.check_stop_sales_order(self)
@@ -373,7 +340,6 @@
 		self.cancel_packing_slips()
 
 
-	# ******************** Check Next DocStatus **************************
 	def check_next_docstatus(self):
 		submit_rv = sql("select t1.name from `tabSales Invoice` t1,`tabSales Invoice Item` t2 where t1.name = t2.parent and t2.delivery_note = '%s' and t1.docstatus = 1" % (self.doc.name))
 		if submit_rv:
@@ -403,8 +369,6 @@
 			webnotes.msgprint("%s Packing Slip(s) Cancelled" % res[0][1])
 
 
-# UPDATE STOCK LEDGER
-# =================================================================================================
 	def update_stock_ledger(self, update_stock, is_stopped = 0):
 		self.values = []
 		for d in self.get_item_list(is_stopped):
@@ -424,12 +388,10 @@
 		get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
 
 
-	# ***************** Gets Items from packing list *****************
 	def get_item_list(self, is_stopped):
 	 return get_obj('Sales Common').get_item_list(self, is_stopped)
 
 
-	# ********************** Make Stock Entry ************************************
 	def make_sl_entry(self, d, wh, qty, in_value, update_stock):
 		self.values.append({
 			'item_code'					: d['item_code'],
@@ -439,7 +401,7 @@
 			'posting_time'				: self.doc.posting_time,
 			'voucher_type'				: 'Delivery Note',
 			'voucher_no'				: self.doc.name,
-			'voucher_detail_no'	 		: '',
+			'voucher_detail_no'	 		: d['name'],
 			'actual_qty'				: qty,
 			'stock_uom'					: d['uom'],
 			'incoming_rate'			 	: in_value,
@@ -451,8 +413,6 @@
 		})
 
 
-	# SEND SMS
-	# ============================================================================================
 	def send_sms(self):
 		if not self.doc.customer_mobile_no:
 			msgprint("Please enter customer mobile no")
@@ -462,8 +422,8 @@
 			msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.customer_mobile_no,], self.doc.message))
 
 
-#------------ check credit limit of items in DN Detail which are not fetched from sales order----------
 	def credit_limit(self):
+		"""check credit limit of items in DN Detail which are not fetched from sales order"""
 		amount, total = 0, 0
 		for d in getlist(self.doclist, 'delivery_note_details'):
 			if not d.prevdoc_docname:
@@ -472,7 +432,7 @@
 			total = (amount/self.doc.net_total)*self.doc.grand_total
 			get_obj('Sales Common').check_credit(self, total)
 
-	# on update
+
 	def on_update(self):
 		get_obj('Sales Common').make_packing_list(self,'delivery_note_details')
 		self.set_actual_qty()
diff --git a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
index 5abb70d..8d0d387 100644
--- a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
+++ b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-04-13 11:56:35',
+		'creation': '2012-06-08 16:08:01',
 		'docstatus': 0,
-		'modified': '2012-06-07 17:57:14',
+		'modified': '2012-07-09 11:06:26',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -70,6 +70,17 @@
 
 	# DocField
 	{
+		'doctype': u'DocField',
+		'fieldname': u'customer_item_code',
+		'fieldtype': u'Data',
+		'hidden': 1,
+		'label': u"Customer's Item Code",
+		'permlevel': 1,
+		'print_hide': 1
+	},
+
+	# DocField
+	{
 		'colour': u'White:FFF',
 		'doctype': u'DocField',
 		'fieldname': u'item_name',
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index b2c9235..c8d6392 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -61,8 +61,7 @@
 			if cstr(d.uom) in check_list:
 				msgprint("UOM %s has been entered more than once in Conversion Factor Details." % cstr(d.uom))
 				raise Exception
-
-			if not cstr(d.uom) in check_list:
+			else:
 				check_list.append(cstr(d.uom))
 
 			if cstr(d.uom) == cstr(self.doc.stock_uom):
diff --git a/erpnext/utilities/cleanup_data.py b/erpnext/utilities/cleanup_data.py
new file mode 100644
index 0000000..60b54ec
--- /dev/null
+++ b/erpnext/utilities/cleanup_data.py
@@ -0,0 +1,201 @@
+#!/usr/bin/python
+
+# This script is for cleaning up of all data from system including 
+# all transactions and masters (excludes default masters). 
+# Basically after running this file, system will reset to it's 
+# initial state.
+# This script can be executed from lib/wnf.py using 
+# lib/wnf.py --cleanup-data
+
+import sys
+sys.path.append("lib/py")
+sys.path.append(".")
+sys.path.append("erpnext")
+
+import webnotes
+
+#--------------------------------
+
+def delete_transactions():
+	print "Deleting transactions..."
+
+	trans = ['Timesheet','Task','Support Ticket','Stock Reconciliation', 'Stock Ledger Entry', \
+		'Stock Entry','Sales Order','Salary Slip','Sales Invoice','Quotation', 'Quality Inspection', \
+		'Purchase Receipt','Purchase Order','Production Order', 'POS Setting','Period Closing Voucher', \
+		'Purchase Invoice','Maintenance Visit','Maintenance Schedule','Leave Application', \
+		'Leave Allocation', 'Lead', 'Journal Voucher', 'Installation Note','Purchase Request', \
+		'GL Entry','Expense Claim','Opportunity','Delivery Note','Customer Issue','Bin', \
+		'Authorization Rule','Attendance','Account Balance', 'C-Form', 'Form 16A', 'Lease Agreement', \
+		'Lease Installment', 'TDS Payment', 'TDS Return Acknowledgement', 'Appraisal', \
+		'Installation Note', 'Communication'
+	]
+	for d in trans:
+		for t in webnotes.conn.sql("select options from tabDocField where parent='%s' and fieldtype='Table'" % d):
+			webnotes.conn.sql("delete from `tab%s`" % (t))
+		webnotes.conn.sql("delete from `tab%s`" % (d))
+		webnotes.conn.sql("COMMIT")
+		webnotes.conn.sql("START TRANSACTION")
+		print "Deleted " + d
+	
+	
+	
+def delete_masters():
+	print "Deleting masters...."
+	masters = {
+		'Workstation':['Default Workstation'],
+		'Warehouse Type':['Default Warehouse Type', 'Fixed Asset', 'Rejected', 'Reserved', 
+			'Sample', 'Stores', 'WIP Warehouse'],
+		'Warehouse':['Default Warehouse'],
+		'UOM':['Kg', 'Mtr', 'Box', 'Ltr', 'Nos', 'Ft', 'Pair', 'Set'],
+		'Territory':['All Territories', 'Default Territory'],
+		'Terms and Conditions':'',
+		'Tag':'',
+		'Supplier Type':['Default Supplier Type'],
+		'Supplier':'',
+		'Serial No':'',
+		'Sales Person':['All Sales Persons'],
+		'Sales Partner':'',
+		'Sales BOM':'',
+		'Salary Structure':'',
+		'Purchase Taxes and Charges Master':'',
+		'Project':'',
+		'Print Heading':'',
+		'Price List':['Default Price List'],
+		'Period':'',
+		'Sales Taxes and Charges Master':'',
+		'Letter Head':'',
+		'Leave Type':['Leave Without Pay', 'Privilege Leave', 'Casual Leave', 'PL', 'CL', 'LWP', 
+			'Compensatory Off', 'Sick Leave'],
+		'Landed Cost Master':'',
+		'Appraisal Template':'',
+		'Item Group':['All Item Groups', 'Default'], 
+		'Item':'',
+		'Holiday List':'',
+		'Grade':'',
+		'Feed':'',
+		'Expense Claim Type':['Travel', 'Medical', 'Calls', 'Food', 'Others'],
+		'Event':'', 
+		'Employment Type':'', 
+		'Employee':'',
+		'Earning Type':['Basic', 'Conveyance', 'House Rent Allowance', 'Dearness Allowance', 
+			'Medical Allowance', 'Telephone'],
+		'Designation':'',
+		'Department':'',
+		'Deduction Type':['Income Tax', 'Professional Tax', 'Provident Fund', 'Leave Deduction'],
+		'Customer Group':['All Customer Groups', 'Default Customer Group'],
+		'Customer':'',
+		'Cost Center':'', 
+		'Contact':'',
+		'Campaign':'', 
+		'Budget Distribution':'', 
+		'Brand':'',
+		'Branch':'',
+		'Batch':'', 
+		'Appraisal':'', 
+		'Account':'', 
+		'BOM': ''
+	}
+	for d in masters.keys():
+		for t in webnotes.conn.sql("select options from tabDocField where parent='%s' \
+			and fieldtype='Table'" % d):
+			webnotes.conn.sql("delete from `tab%s`" % (t))
+		lst = '"'+'","'.join(masters[d])+ '"'
+		webnotes.conn.sql("delete from `tab%s` where name not in (%s)" % (d, lst))
+		webnotes.conn.sql("COMMIT")
+		webnotes.conn.sql("START TRANSACTION")
+		print "Deleted " + d
+
+
+
+def reset_series():
+	# Reset series
+	webnotes.conn.sql("""update tabSeries set current = 0 where name not in \
+		('Ann/', 'BSD', 'DEF', 'DF', 'EV', 'Event Updates/', 'FileData-', \
+		'FL', 'FMD/', 'GLM Detail', 'Login Page/', 'MDI', 'MDR', 'MI', 'MIR', \
+		'PERM', 'PR', 'SRCH/C/', 'TD', 'TIC/', 'TMD/', 'TW', 'UR', '_FEED', \
+		'_SRCH', '_TRIGGER', '__NSO', 'CustomField', 'Letter')
+	""")
+	print "Series updated"
+
+
+def delete_main_masters():
+	main_masters = ['Fiscal Year','Company', 'DefaultValue']
+	for d in main_masters:
+		for t in webnotes.conn.sql("select options from tabDocField where parent='%s' and fieldtype='Table'" % d):
+			webnotes.conn.sql("delete from `tab%s`" % (t))
+		webnotes.conn.sql("delete from `tab%s`" % (d))
+		webnotes.conn.sql("COMMIT")
+		webnotes.conn.sql("START TRANSACTION")
+		print "Deleted " + d
+	
+
+
+def reset_global_defaults():
+	flds = {
+		'default_company': '', 
+		'default_currency': '', 
+		'default_currency_format': 'Lacs', 
+		'default_currency_fraction': '', 
+		'current_fiscal_year': '', 
+		'date_format': 'dd-mm-yyyy', 
+		'sms_sender_name': '', 
+		'default_item_group': 'Default', 
+		'default_stock_uom': 'Nos', 
+		'default_valuation_method': 'FIFO', 
+		'default_warehouse_type': 'Default Warehouse Type', 
+		'tolerance': '', 
+		'acc_frozen_upto': '', 
+		'bde_auth_role': '', 
+		'credit_controller': '', 
+		'default_customer_group': 'Default Customer Group', 
+		'default_territory': 'Default', 
+		'default_price_list': 'Standard', 
+		'default_supplier_type': 'Default Supplier Type'
+	}
+
+	from webnotes.model.code import get_obj
+	gd = get_obj('Global Defaults', 'Global Defaults')
+	for d in flds:
+		gd.doc.fields[d] = flds[d]
+	gd.doc.save()
+	
+	webnotes.clear_cache()
+
+
+def run():
+	webnotes.connect()
+	
+	# Confirmation from user
+	confirm = ''
+	while not confirm:
+		confirm = raw_input("Are you sure you want to delete the data from the system (N/Y)?")
+	if confirm.lower() != 'y':
+		raise Exception
+
+	cleanup_type = ''
+	while cleanup_type not in ['1', '2']:
+		cleanup_type = raw_input("""\nWhat type of cleanup you want ot perform?
+	1. Only Transactions
+	2. Both Masters and Transactions
+
+	Please enter your choice (1/2):
+		""")
+		
+	# delete
+	delete_transactions()
+	
+	if cleanup_type == '1':	
+		print '\n', '*' * 10 + 'NOTE' + '*' * 10, '\n'
+		print "To reset series of the transactions go to Setup --> Numbering Series\n"
+	else:
+		delete_masters()
+		reset_series()
+		delete_main_masters()
+		reset_global_defaults()
+
+	print "System cleaned up succesfully"
+	webnotes.conn.close()
+
+
+if __name__ == '__main__':
+	run()
diff --git a/erpnext/utilities/page/questions/questions.js b/erpnext/utilities/page/questions/questions.js
index 33e0853..048ed54 100644
--- a/erpnext/utilities/page/questions/questions.js
+++ b/erpnext/utilities/page/questions/questions.js
@@ -14,8 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-pscript.onload_questions = function(wrapper) {	
-	console.log(1);
+pscript.onload_questions = function(wrapper) {
 	body = $(wrapper).find('.layout-main-section').get(0);
 	
 	wrapper.appframe = new wn.ui.AppFrame($(wrapper).find('.layout-appframe'));
diff --git a/erpnext/utilities/page/todo/todo.css b/erpnext/utilities/page/todo/todo.css
index ee9b4f1..7c7dcaf 100644
--- a/erpnext/utilities/page/todo/todo.css
+++ b/erpnext/utilities/page/todo/todo.css
@@ -47,4 +47,9 @@
 
 .todo-content {
 	padding-right: 15px;
+}
+
+.layout-main {
+	background-color: #FFFDC9;
+	min-height: 300px;
 }
\ No newline at end of file
diff --git a/erpnext/utilities/page/todo/todo.html b/erpnext/utilities/page/todo/todo.html
index d49fc23..88dcbf3 100644
--- a/erpnext/utilities/page/todo/todo.html
+++ b/erpnext/utilities/page/todo/todo.html
@@ -1,9 +1,6 @@
-<div class="layout-wrapper" style="min-height: 300px; background-color: #FFFDC9">
+<div class="layout-wrapper layout-wrapper-background">
 	<div class="appframe-area"></div>
-	<div>
-		<a class="close" onclick="window.history.back();">&times;</a>
-		<h1>To Do</h1>
-		<br>
+	<div class="layout-main">
 		<div>
 			<div id="todo-list">
 				<h4>My List</h4><br>
@@ -14,8 +11,6 @@
 				<div class="todo-content"></div>
 			</div>
 		</div>
-		<div style="margin-top: 21px; clear: both">
-			<button id="add-todo" class="btn btn-small"><i class="icon-plus"></i> Add</button>
-		</div>
+		<div style="clear: both"></div>
 	</div>
 </div>
\ No newline at end of file
diff --git a/erpnext/utilities/page/todo/todo.js b/erpnext/utilities/page/todo/todo.js
index 206becf..786e757 100644
--- a/erpnext/utilities/page/todo/todo.js
+++ b/erpnext/utilities/page/todo/todo.js
@@ -48,11 +48,6 @@
 			}
 		}
 	});
-	
-	$('#add-todo').click(function() {
-		erpnext.todo.make_dialog({
-			date:get_today(), priority:'Medium', checked:0, description:''});
-	})
 }
 
 erpnext.todo.ToDoItem = Class.extend({
@@ -196,7 +191,15 @@
 	});
 }
 
-wn.pages.todo.onload = function() {
+wn.pages.todo.onload = function(wrapper) {
+	// create app frame
+	wrapper.appframe = new wn.ui.AppFrame($(wrapper).find('.appframe-area'), 'To Do');
+	wrapper.appframe.add_button('Refresh', erpnext.todo.refresh, 'icon-refresh');
+	wrapper.appframe.add_button('Add', function() {
+		erpnext.todo.make_dialog({
+			date:get_today(), priority:'Medium', checked:0, description:''});
+	}, 'icon-plus');
+
 	// load todos
 	erpnext.todo.refresh();
 }
\ No newline at end of file
diff --git a/erpnext/utilities/page/users/users.py b/erpnext/utilities/page/users/users.py
index 347c9b2..07504a8 100644
--- a/erpnext/utilities/page/users/users.py
+++ b/erpnext/utilities/page/users/users.py
@@ -167,7 +167,7 @@
 			'Website Settings', 'subdomain') or ""
 	})
 	if not args.get('last_name'): args['last_name'] = ''
-	sendmail_md(pr.email, subject="Welcome to ERPNext", msg=welcome_txt % args, from_defs=1)
+	sendmail_md(pr.email, subject="Welcome to ERPNext", msg=welcome_txt % args)
 
 #
 # delete user
diff --git a/public/css/all-app.css b/public/css/all-app.css
index 93dfe47..ecdbe65 100644
--- a/public/css/all-app.css
+++ b/public/css/all-app.css
@@ -3219,6 +3219,8 @@
 	height: 18px;
 	border: 1px solid #aaa;
 	border-radius: 9px;
+	-webkit-border-radius: 9px;
+	-moz-border-radius: 9px;
 	overflow: hidden;
 }
 
@@ -3227,6 +3229,10 @@
 	left: 0px;
 	height: 100%;
 	z-index: 0;
+	/* So that this div is also curved like the enclosing one */
+	border-radius: 9px;
+	-webkit-border-radius: 9px;
+	-moz-border-radius: 9px;
 
 	background: #e0ff84; /* Old browsers */
 	background: -moz-linear-gradient(top,  #e0ff84 0%, #a4e567 100%); /* FF3.6+ */
diff --git a/public/css/all-web.css b/public/css/all-web.css
index a2de6b6..332471b 100644
--- a/public/css/all-web.css
+++ b/public/css/all-web.css
@@ -2470,6 +2470,8 @@
 	height: 18px;
 	border: 1px solid #aaa;
 	border-radius: 9px;
+	-webkit-border-radius: 9px;
+	-moz-border-radius: 9px;
 	overflow: hidden;
 }
 
@@ -2478,6 +2480,10 @@
 	left: 0px;
 	height: 100%;
 	z-index: 0;
+	/* So that this div is also curved like the enclosing one */
+	border-radius: 9px;
+	-webkit-border-radius: 9px;
+	-moz-border-radius: 9px;
 
 	background: #e0ff84; /* Old browsers */
 	background: -moz-linear-gradient(top,  #e0ff84 0%, #a4e567 100%); /* FF3.6+ */
diff --git a/public/js/all-app.js b/public/js/all-app.js
index f320cc1..f8ceac2 100644
--- a/public/js/all-app.js
+++ b/public/js/all-app.js
@@ -735,7 +735,7 @@
 me.txt.field_object=this;me.input.set_input=function(val){if(val==undefined)val='';me.txt.value=val;}
 me.get_value=function(){return me.txt.value;}
 $(me.txt).autocomplete({source:function(request,response){wn.call({method:'webnotes.widgets.search.search_link',args:{'txt':request.term,'dt':me.df.options,'query':me.get_custom_query()},callback:function(r){response(r.results);},});},select:function(event,ui){me.set_input_value(ui.item.value);}}).data('autocomplete')._renderItem=function(ul,item){return $('<li></li>').data('item.autocomplete',item).append(repl('<a>%(label)s<br><span style="font-size:10px">%(info)s</span></a>',item)).appendTo(ul);};$(this.txt).change(function(){var val=$(this).val();me.set_input_value_executed=false;if(!val){if(selector&&selector.display)
-return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},100);}})}
+return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},1000);}})}
 LinkField.prototype.get_custom_query=function(){this.set_get_query();if(this.get_query){if(cur_frm)
 var doc=locals[cur_frm.doctype][cur_frm.docname];return this.get_query(doc,this.doctype,this.docname);}}
 LinkField.prototype.setup_buttons=function(){var me=this;me.btn.onclick=function(){selector.set(me,me.df.options,me.df.label);selector.show(me.txt);}
@@ -1333,8 +1333,7 @@
 return perm;}
 LocalDB.create=function(doctype,n){if(!n)n=LocalDB.get_localname(doctype);var doc=LocalDB.add(doctype,n)
 doc.__islocal=1;doc.owner=user;LocalDB.set_default_values(doc);return n;}
-LocalDB.delete_record=function(dt,dn){var d=locals[dt][dn];if(!d.__islocal)
-d.__oldparent=d.parent;d.parent='old_parent:'+d.parent;d.docstatus=2;d.__deleted=1;}
+LocalDB.delete_record=function(dt,dn){delete locals[dt][dn];}
 LocalDB.get_default_value=function(fn,ft,df){if(df=='_Login'||df=='__user')
 return user;else if(df=='_Full Name')
 return user_fullname;else if(ft=='Date'&&(df=='Today'||df=='__today')){return get_today();}
@@ -1345,8 +1344,8 @@
 LocalDB.add_child=function(doc,childtype,parentfield){var n=LocalDB.create(childtype);var d=locals[childtype][n];d.parent=doc.name;d.parentfield=parentfield;d.parenttype=doc.doctype;return d;}
 LocalDB.no_copy_list=['amended_from','amendment_date','cancel_reason'];LocalDB.copy=function(dt,dn,from_amend){var newdoc=LocalDB.create(dt);for(var key in locals[dt][dn]){var df=get_field(dt,key);if(key!=='name'&&key.substr(0,2)!='__'&&!(df&&((!from_amend&&cint(df.no_copy)==1)||in_list(LocalDB.no_copy_list,df.fieldname)))){locals[dt][newdoc][key]=locals[dt][dn][key];}}
 return locals[dt][newdoc];}
-function make_doclist(dt,dn,deleted){if(!locals[dt]){return[];}
-var dl=[];dl[0]=locals[dt][dn];for(var ndt in locals){if(locals[ndt]){for(var ndn in locals[ndt]){var doc=locals[ndt][ndn];if(doc&&doc.parenttype==dt&&(doc.parent==dn||(deleted&&doc.__oldparent==dn))){dl[dl.length]=doc;}}}}
+function make_doclist(dt,dn){if(!locals[dt]){return[];}
+var dl=[];dl[0]=locals[dt][dn];for(var ndt in locals){if(locals[ndt]){for(var ndn in locals[ndt]){var doc=locals[ndt][ndn];if(doc&&doc.parenttype==dt&&doc.parent==dn){dl.push(doc)}}}}
 return dl;}
 var Meta={};var local_dt={};Meta.make_local_dt=function(dt,dn){var dl=make_doclist('DocType',dt);if(!local_dt[dt])local_dt[dt]={};if(!local_dt[dt][dn])local_dt[dt][dn]={};for(var i=0;i<dl.length;i++){var d=dl[i];if(d.doctype=='DocField'){var key=d.fieldname?d.fieldname:d.label;local_dt[dt][dn][key]=copy_dict(d);}}}
 Meta.get_field=function(dt,fn,dn){if(dn&&local_dt[dt]&&local_dt[dt][dn]){return local_dt[dt][dn][fn];}else{if(wn.meta.docfield_map[dt])var d=wn.meta.docfield_map[dt][fn];if(d)return d;}
@@ -1358,7 +1357,7 @@
 /*
  *	lib/js/legacy/model/doclist.js
  */
-function compress_doclist(list){var kl={};var vl=[];var flx={};for(var i=0;i<list.length;i++){var o=list[i];var fl=[];if(!kl[o.doctype]){var tfl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__deleted','__newname','__modified','_user_tags'];var fl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__deleted','__newname','__modified','_user_tags'];for(key in wn.meta.docfield_map[o.doctype]){if(!in_list(fl,key)&&!in_list(no_value_fields,wn.meta.docfield_map[o.doctype][key].fieldtype)&&!wn.meta.docfield_map[o.doctype][key].no_column){fl[fl.length]=key;tfl[tfl.length]=key}}
+function compress_doclist(list){var kl={};var vl=[];var flx={};for(var i=0;i<list.length;i++){var o=list[i];var fl=[];if(!kl[o.doctype]){var tfl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__newname','__modified','_user_tags'];var fl=[].concat(tfl);for(key in wn.meta.docfield_map[o.doctype]){if(!in_list(fl,key)&&!in_list(no_value_fields,wn.meta.docfield_map[o.doctype][key].fieldtype)&&!wn.meta.docfield_map[o.doctype][key].no_column){fl[fl.length]=key;tfl[tfl.length]=key}}
 flx[o.doctype]=fl;kl[o.doctype]=tfl}
 var nl=[];var fl=flx[o.doctype];for(var j=0;j<fl.length;j++){var v=o[fl[j]];nl.push(v);}
 vl.push(nl);}
@@ -1562,7 +1561,7 @@
 me.txt.field_object=this;me.input.set_input=function(val){if(val==undefined)val='';me.txt.value=val;}
 me.get_value=function(){return me.txt.value;}
 $(me.txt).autocomplete({source:function(request,response){wn.call({method:'webnotes.widgets.search.search_link',args:{'txt':request.term,'dt':me.df.options,'query':me.get_custom_query()},callback:function(r){response(r.results);},});},select:function(event,ui){me.set_input_value(ui.item.value);}}).data('autocomplete')._renderItem=function(ul,item){return $('<li></li>').data('item.autocomplete',item).append(repl('<a>%(label)s<br><span style="font-size:10px">%(info)s</span></a>',item)).appendTo(ul);};$(this.txt).change(function(){var val=$(this).val();me.set_input_value_executed=false;if(!val){if(selector&&selector.display)
-return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},100);}})}
+return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},1000);}})}
 LinkField.prototype.get_custom_query=function(){this.set_get_query();if(this.get_query){if(cur_frm)
 var doc=locals[cur_frm.doctype][cur_frm.docname];return this.get_query(doc,this.doctype,this.docname);}}
 LinkField.prototype.setup_buttons=function(){var me=this;me.btn.onclick=function(){selector.set(me,me.df.options,me.df.label);selector.show(me.txt);}
@@ -1747,7 +1746,7 @@
 var sec;for(var i=0;i<fl.length;i++){var f=fl[i];if(f.fieldtype=='Section Break'&&fl[i+1]&&fl[i+1].fieldtype=='Section Break')
 continue;var fn=f.fieldname?f.fieldname:f.label;var fld=make_field(f,this.doctype,this.layout.cur_cell,this);this.fields[this.fields.length]=fld;this.fields_dict[fn]=fld;if(sec&&['Section Break','Column Break'].indexOf(f.fieldtype)==-1){fld.parent_section=sec;sec.fields.push(fld);}
 if(f.fieldtype=='Section Break'){sec=fld;this.sections.push(fld);}
-if((f.fieldtype=='Section Break')&&(fl[i+1])&&(fl[i+1].fieldtype!='Column Break')&&!f.hidden){var c=this.layout.addcell();$y(c.wrapper,{padding:'8px'});}}}
+if((f.fieldtype=='Section Break')&&(fl[i+1])&&(fl[i+1].fieldtype!='Column Break')){var c=this.layout.addcell();$y(c.wrapper,{padding:'8px'});}}}
 _f.Frm.prototype.add_custom_button=function(label,fn,icon){this.frm_head.appframe.add_button(label,fn,icon);}
 _f.Frm.prototype.clear_custom_buttons=function(){this.frm_head.refresh_toolbar()}
 _f.Frm.prototype.add_fetch=function(link_field,src_field,tar_field){if(!this.fetch_dict[link_field]){this.fetch_dict[link_field]={'columns':[],'fields':[]}}
@@ -1823,13 +1822,12 @@
 if(doctype.client_string){this.cstring={};var elist=doctype.client_string.split('---');for(var i=1;i<elist.length;i=i+2){this.cstring[strip(elist[i])]=elist[i+1];}}}
 return ret;}
 _f.Frm.prototype.copy_doc=function(onload,from_amend){if(!this.perm[0][CREATE]){msgprint('You are not allowed to create '+this.meta.name);return;}
-var dn=this.docname;var newdoc=LocalDB.copy(this.doctype,dn,from_amend);if(this.meta.allow_attach&&newdoc.file_list)
+var dn=this.docname;var newdoc=LocalDB.copy(this.doctype,dn,from_amend);if(this.meta.allow_attach&&newdoc.file_list&&!from_amend)
 newdoc.file_list=null;var dl=make_doclist(this.doctype,dn);var tf_dict={};for(var d in dl){d1=dl[d];if(!tf_dict[d1.parentfield]){tf_dict[d1.parentfield]=get_field(d1.parenttype,d1.parentfield);}
 if(d1.parent==dn&&cint(tf_dict[d1.parentfield].no_copy)!=1){var ch=LocalDB.copy(d1.doctype,d1.name,from_amend);ch.parent=newdoc.name;ch.docstatus=0;ch.owner=user;ch.creation='';ch.modified_by=user;ch.modified='';}}
 newdoc.__islocal=1;newdoc.docstatus=0;newdoc.owner=user;newdoc.creation='';newdoc.modified_by=user;newdoc.modified='';if(onload)onload(newdoc);loaddoc(newdoc.doctype,newdoc.name);}
 _f.Frm.prototype.reload_doc=function(){this.check_doctype_conflict(this.docname);var me=this;var ret_fn=function(r,rtxt){me.runclientscript('setup',me.doctype,me.docname);me.refresh();}
-if(me.doc.__islocal){$c('webnotes.widgets.form.load.getdoctype',{'doctype':me.doctype},ret_fn,null,null,'Refreshing '+me.doctype+'...');}else{var gl=me.grids;for(var i=0;i<gl.length;i++){var dt=gl[i].df.options;for(var dn in locals[dt]){if(locals[dt][dn].__islocal&&locals[dt][dn].parent==me.docname){var d=locals[dt][dn];d.parent='';d.docstatus=2;d.__deleted=1;}}}
-$c('webnotes.widgets.form.load.getdoc',{'name':me.docname,'doctype':me.doctype,'getdoctype':1,'user':user},ret_fn,null,null,'Refreshing '+me.docname+'...');}}
+if(me.doc.__islocal){$c('webnotes.widgets.form.load.getdoctype',{'doctype':me.doctype},ret_fn,null,null,'Refreshing '+me.doctype+'...');}else{$c('webnotes.widgets.form.load.getdoc',{'name':me.docname,'doctype':me.doctype,'getdoctype':1,'user':user},ret_fn,null,null,'Refreshing '+me.docname+'...');}}
 _f.Frm.prototype.savedoc=function(save_action,onsave,onerr){this.error_in_section=0;save_doclist(this.doctype,this.docname,save_action,onsave,onerr);}
 _f.Frm.prototype.saveupdate=function(){this.save('Update');}
 _f.Frm.prototype.savesubmit=function(){var answer=confirm("Permanently Submit "+this.docname+"?");var me=this;if(answer){this.save('Submit',function(r){if(!r.exc&&me.cscript.on_submit){me.runclientscript('on_submit',me.doctype,me.docname);}});}}
@@ -1852,14 +1850,13 @@
  *	lib/js/legacy/widgets/form/form_fields.js
  */
 _f.ColumnBreak=function(){this.set_input=function(){};}
-_f.ColumnBreak.prototype.make_body=function(){if((!this.perm[this.df.permlevel])||(!this.perm[this.df.permlevel][READ])||this.df.hidden){return;}
-this.cell=this.frm.layout.addcell(this.df.width);$y(this.cell.wrapper,{padding:'8px'});_f.cur_col_break_width=this.df.width;var fn=this.df.fieldname?this.df.fieldname:this.df.label;if(this.df&&this.df.label){this.label=$a(this.cell.wrapper,'div','','',this.df.label);}}
-_f.ColumnBreak.prototype.refresh=function(layout){if(!this.cell)return;if(this.set_hidden!=this.df.hidden){if(this.df.hidden)
+_f.ColumnBreak.prototype.make_body=function(){this.cell=this.frm.layout.addcell(this.df.width);$y(this.cell.wrapper,{padding:'8px'});_f.cur_col_break_width=this.df.width;var fn=this.df.fieldname?this.df.fieldname:this.df.label;if(this.df&&this.df.label){this.label=$a(this.cell.wrapper,'div','','',this.df.label);}}
+_f.ColumnBreak.prototype.refresh=function(layout){var hidden=0;if((!this.perm[this.df.permlevel])||(!this.perm[this.df.permlevel][READ])||this.df.hidden){hidden=1;}
+if(this.set_hidden!=hidden){if(hidden)
 this.cell.hide();else
-this.cell.show();this.set_hidden=this.df.hidden;}}
+this.cell.show();this.set_hidden=hidden;}}
 _f.SectionBreak=function(){this.fields=[];this.set_input=function(){};this.make_row=function(){this.row=this.df.label?this.frm.layout.addrow():this.frm.layout.addsubrow();}}
-_f.SectionBreak.prototype.make_body=function(){var me=this;if((!this.perm[this.df.permlevel])||(!this.perm[this.df.permlevel][READ])||this.df.hidden){return;}
-this.make_row();if(this.df.label){if(!this.df.description)
+_f.SectionBreak.prototype.make_body=function(){var me=this;this.make_row();if(this.df.label){if(!this.df.description)
 this.df.description='';$(this.row.main_head).html(repl('<div class="form-section-head">\
     <h3 class="head">%(label)s</h3>\
     <div class="help small" \
@@ -1875,7 +1872,8 @@
 if(f.df.reqd&&!v){return true;}
 if(f.df.fieldtype=='Table'){if(f.grid.get_children().length||f.df.reqd){return true;}}}
 return false;}
-_f.SectionBreak.prototype.refresh=function(from_form){if(this.df.hidden){if(this.row)this.row.hide();}else{if(this.collapsible){}}}
+_f.SectionBreak.prototype.refresh=function(from_form){var hidden=0;if((!this.perm[this.df.permlevel])||(!this.perm[this.df.permlevel][READ])||this.df.hidden){hidden=1;}
+if(hidden){if(this.row)this.row.hide();}else{if(this.collapsible){}}}
 _f.ImageField=function(){this.images={};}
 _f.ImageField.prototype=new Field();_f.ImageField.prototype.onmake=function(){this.no_img=$a(this.wrapper,'div','no_img');this.no_img.innerHTML="No Image";$dh(this.no_img);}
 _f.ImageField.prototype.get_image_src=function(doc){if(doc.file_list){file=doc.file_list.split(',');extn=file[0].split('.');extn=extn[extn.length-1].toLowerCase();var img_extn_list=['gif','jpg','bmp','jpeg','jp2','cgm','ief','jpm','jpx','png','tiff','jpe','tif'];if(in_list(img_extn_list,extn)){var src=wn.request.url+"?cmd=downloadfile&file_id="+file[1];}}else{var src="";}
@@ -1931,7 +1929,7 @@
 if(odd){$bg(cell,this.alt_row_bg);cell.is_odd=1;cell.div.style.border='2px solid '+this.alt_row_bg;}else $bg(cell,'#FFF');if(!hc.fieldname)cell.div.style.cursor='default';}
 this.set_ht();return row;}
 _f.Grid.prototype.refresh_cell=function(docname,fieldname){for(var r=0;r<this.tab.rows.length;r++){if(this.tab.rows[r].docname==docname){for(var c=0;c<this.head_row.cells.length;c++){var hc=this.head_row.cells[c];if(hc.fieldname==fieldname){this.set_cell_value(this.tab.rows[r].cells[c]);}}}}}
-_f.cur_grid;_f.cur_grid_ridx;_f.Grid.prototype.set_cell_value=function(cell){if(cell.row.is_newrow)return;var hc=this.head_row.cells[cell.cellIndex];if(hc.fieldname){var v=locals[hc.doctype][cell.row.docname][hc.fieldname];}else{var v=(cell.row.rowIndex+1);}
+_f.cur_grid;_f.cur_grid_ridx;_f.Grid.prototype.set_cell_value=function(cell){if(cell.row.is_newrow)return;var hc=this.head_row.cells[cell.cellIndex];if(hc.fieldname&&locals[hc.doctype][cell.row.docname]){var v=locals[hc.doctype][cell.row.docname][hc.fieldname];}else{var v=(cell.row.rowIndex+1);}
 if(v==null){v='';}
 var me=this;if(cell.cellIndex){var ft=hc.fieldtype;if(ft=='Link'&&cur_frm.doc.docstatus<1)ft='Data';$s(cell.div,v,ft,hc.options);}else{cell.div.style.padding='2px';cell.div.style.textAlign='left';cell.innerHTML='';var t=make_table(cell,1,3,'60px',['20px','20px','20px'],{verticalAlign:'middle',padding:'2px'});$y($td(t,0,0),{paddingLeft:'4px'});$td(t,0,0).innerHTML=cell.row.rowIndex+1;if(cur_frm.editable&&this.can_edit){var ed=$a($td(t,0,1),'i','icon-edit',{cursor:'pointer'});ed.cell=cell;ed.title='Edit Row';ed.onclick=function(){_f.cur_grid=me;_f.cur_grid_ridx=this.cell.row.rowIndex;_f.edit_record(me.doctype,this.cell.row.docname,1);}}else{cell.div.innerHTML=(cell.row.rowIndex+1);cell.div.style.cursor='default';cell.div.onclick=function(){}}}}
 $(document).bind('click',function(e){var me=this;var is_target_toolbar=function(){return $(e.target).parents('.grid_tbarlinks').length;}
diff --git a/public/js/all-web.js b/public/js/all-web.js
index 257984e..0244801 100644
--- a/public/js/all-web.js
+++ b/public/js/all-web.js
@@ -646,8 +646,7 @@
 return perm;}
 LocalDB.create=function(doctype,n){if(!n)n=LocalDB.get_localname(doctype);var doc=LocalDB.add(doctype,n)
 doc.__islocal=1;doc.owner=user;LocalDB.set_default_values(doc);return n;}
-LocalDB.delete_record=function(dt,dn){var d=locals[dt][dn];if(!d.__islocal)
-d.__oldparent=d.parent;d.parent='old_parent:'+d.parent;d.docstatus=2;d.__deleted=1;}
+LocalDB.delete_record=function(dt,dn){delete locals[dt][dn];}
 LocalDB.get_default_value=function(fn,ft,df){if(df=='_Login'||df=='__user')
 return user;else if(df=='_Full Name')
 return user_fullname;else if(ft=='Date'&&(df=='Today'||df=='__today')){return get_today();}
@@ -658,8 +657,8 @@
 LocalDB.add_child=function(doc,childtype,parentfield){var n=LocalDB.create(childtype);var d=locals[childtype][n];d.parent=doc.name;d.parentfield=parentfield;d.parenttype=doc.doctype;return d;}
 LocalDB.no_copy_list=['amended_from','amendment_date','cancel_reason'];LocalDB.copy=function(dt,dn,from_amend){var newdoc=LocalDB.create(dt);for(var key in locals[dt][dn]){var df=get_field(dt,key);if(key!=='name'&&key.substr(0,2)!='__'&&!(df&&((!from_amend&&cint(df.no_copy)==1)||in_list(LocalDB.no_copy_list,df.fieldname)))){locals[dt][newdoc][key]=locals[dt][dn][key];}}
 return locals[dt][newdoc];}
-function make_doclist(dt,dn,deleted){if(!locals[dt]){return[];}
-var dl=[];dl[0]=locals[dt][dn];for(var ndt in locals){if(locals[ndt]){for(var ndn in locals[ndt]){var doc=locals[ndt][ndn];if(doc&&doc.parenttype==dt&&(doc.parent==dn||(deleted&&doc.__oldparent==dn))){dl[dl.length]=doc;}}}}
+function make_doclist(dt,dn){if(!locals[dt]){return[];}
+var dl=[];dl[0]=locals[dt][dn];for(var ndt in locals){if(locals[ndt]){for(var ndn in locals[ndt]){var doc=locals[ndt][ndn];if(doc&&doc.parenttype==dt&&doc.parent==dn){dl.push(doc)}}}}
 return dl;}
 var Meta={};var local_dt={};Meta.make_local_dt=function(dt,dn){var dl=make_doclist('DocType',dt);if(!local_dt[dt])local_dt[dt]={};if(!local_dt[dt][dn])local_dt[dt][dn]={};for(var i=0;i<dl.length;i++){var d=dl[i];if(d.doctype=='DocField'){var key=d.fieldname?d.fieldname:d.label;local_dt[dt][dn][key]=copy_dict(d);}}}
 Meta.get_field=function(dt,fn,dn){if(dn&&local_dt[dt]&&local_dt[dt][dn]){return local_dt[dt][dn][fn];}else{if(wn.meta.docfield_map[dt])var d=wn.meta.docfield_map[dt][fn];if(d)return d;}
@@ -671,7 +670,7 @@
 /*
  *	lib/js/legacy/model/doclist.js
  */
-function compress_doclist(list){var kl={};var vl=[];var flx={};for(var i=0;i<list.length;i++){var o=list[i];var fl=[];if(!kl[o.doctype]){var tfl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__deleted','__newname','__modified','_user_tags'];var fl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__deleted','__newname','__modified','_user_tags'];for(key in wn.meta.docfield_map[o.doctype]){if(!in_list(fl,key)&&!in_list(no_value_fields,wn.meta.docfield_map[o.doctype][key].fieldtype)&&!wn.meta.docfield_map[o.doctype][key].no_column){fl[fl.length]=key;tfl[tfl.length]=key}}
+function compress_doclist(list){var kl={};var vl=[];var flx={};for(var i=0;i<list.length;i++){var o=list[i];var fl=[];if(!kl[o.doctype]){var tfl=['doctype','name','docstatus','owner','parent','parentfield','parenttype','idx','creation','modified','modified_by','__islocal','__newname','__modified','_user_tags'];var fl=[].concat(tfl);for(key in wn.meta.docfield_map[o.doctype]){if(!in_list(fl,key)&&!in_list(no_value_fields,wn.meta.docfield_map[o.doctype][key].fieldtype)&&!wn.meta.docfield_map[o.doctype][key].no_column){fl[fl.length]=key;tfl[tfl.length]=key}}
 flx[o.doctype]=fl;kl[o.doctype]=tfl}
 var nl=[];var fl=flx[o.doctype];for(var j=0;j<fl.length;j++){var v=o[fl[j]];nl.push(v);}
 vl.push(nl);}
diff --git a/public/js/fields.js b/public/js/fields.js
index dbd77c0..b9dca90 100644
--- a/public/js/fields.js
+++ b/public/js/fields.js
@@ -99,7 +99,7 @@
 me.txt.field_object=this;me.input.set_input=function(val){if(val==undefined)val='';me.txt.value=val;}
 me.get_value=function(){return me.txt.value;}
 $(me.txt).autocomplete({source:function(request,response){wn.call({method:'webnotes.widgets.search.search_link',args:{'txt':request.term,'dt':me.df.options,'query':me.get_custom_query()},callback:function(r){response(r.results);},});},select:function(event,ui){me.set_input_value(ui.item.value);}}).data('autocomplete')._renderItem=function(ul,item){return $('<li></li>').data('item.autocomplete',item).append(repl('<a>%(label)s<br><span style="font-size:10px">%(info)s</span></a>',item)).appendTo(ul);};$(this.txt).change(function(){var val=$(this).val();me.set_input_value_executed=false;if(!val){if(selector&&selector.display)
-return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},100);}})}
+return;me.set_input_value('');}else{setTimeout(function(){if(!me.set_input_value_executed){me.set_input_value(val);}},1000);}})}
 LinkField.prototype.get_custom_query=function(){this.set_get_query();if(this.get_query){if(cur_frm)
 var doc=locals[cur_frm.doctype][cur_frm.docname];return this.get_query(doc,this.doctype,this.docname);}}
 LinkField.prototype.setup_buttons=function(){var me=this;me.btn.onclick=function(){selector.set(me,me.df.options,me.df.label);selector.show(me.txt);}