Merge branch 'master' of github.com:webnotes/erpnext into edge
diff --git a/accounts/doctype/fiscal_year/fiscal_year.js b/accounts/doctype/fiscal_year/fiscal_year.js
index 936037c..6e0ed38 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.js
+++ b/accounts/doctype/fiscal_year/fiscal_year.js
@@ -1,3 +1,31 @@
+// 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/>.
+
 cur_frm.cscript.refresh = function(doc, dt, dn) {
 	cur_frm.toggle_enable('year_start_date', doc.__islocal)
+	
+	if (!doc.__islocal && (doc.name != sys_defaults.fiscal_year)) {
+		cur_frm.add_custom_button("Set as Default", cur_frm.cscript.set_as_default);
+		cur_frm.set_intro("To set this Fiscal Year as Deafult, click on 'Set as Default'");
+	} else cur_frm.set_intro("");
 }
+
+cur_frm.cscript.set_as_default = function() {
+	wn.call({
+		doc: cur_frm.doc,
+		method: "set_as_default"
+	});
+}
\ No newline at end of file
diff --git a/accounts/doctype/fiscal_year/fiscal_year.py b/accounts/doctype/fiscal_year/fiscal_year.py
index 7f48feb..e23351c 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.py
+++ b/accounts/doctype/fiscal_year/fiscal_year.py
@@ -16,7 +16,18 @@
 
 from __future__ import unicode_literals
 import webnotes
+from webnotes import msgprint, _
 
 class DocType:
 	def __init__(self, d, dl):
-		self.doc, self.doclist = d, dl
\ No newline at end of file
+		self.doc, self.doclist = d, dl
+		
+	def set_as_default(self):
+		webnotes.conn.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
+		webnotes.get_obj("Global Defaults").on_update()
+		
+		# clear cache
+		webnotes.clear_cache()
+		
+		msgprint(self.doc.name + _(""" is now the default Fiscal Year. \
+			Please refresh your browser for the change to take effect."""))
\ No newline at end of file
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.js b/accounts/doctype/purchase_invoice/purchase_invoice.js
index bb56bd1..4188b9f 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -193,7 +193,7 @@
 }
 
 cur_frm.fields_dict['entries'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-	return return erpnext.queries.item({
+	return erpnext.queries.item({
 		'ifnull(tabItem.is_purchase_item, "No")': 'Yes'
 	})
 }
diff --git a/accounts/doctype/sales_invoice/sales_invoice.js b/accounts/doctype/sales_invoice/sales_invoice.js
index 86dc3a5..eab1d47 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/accounts/doctype/sales_invoice/sales_invoice.js
@@ -94,8 +94,7 @@
 		for(f in item_flds_pos) cur_frm.fields_dict['entries'].grid.set_column_disp(item_flds_pos[f], false);
 	}
 
-	if(doc.customer) unhide_field('contact_section');
-	else hide_field('contact_section');
+	cur_frm.toggle_display("contact_section", doc.customer);
 
 	// India related fields
 	var cp = wn.control_panel;
@@ -173,6 +172,8 @@
 
 //Customer
 cur_frm.cscript.customer = function(doc,dt,dn,onload) {
+	cur_frm.toggle_display("contact_section", doc.customer);
+	
 	var pl = doc.price_list_name;
 	var callback = function(r,rt) {
 			var callback2 = function(doc, dt, dn) {
@@ -191,8 +192,6 @@
 	}
 	var args = onload ? 'onload':''
 	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', args, callback);
-
-	if(doc.customer) unhide_field('contact_section');
 	
 }
 
@@ -202,25 +201,6 @@
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict.customer_address.on_new = function(dn) {
-	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict.contact_person.on_new = function(dn) {
-	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
-
 // Set Due Date = posting date + credit days
 cur_frm.cscript.debit_to = function(doc,dt,dn) {
 
@@ -232,7 +212,8 @@
 	var callback = function(r,rt) {
 			var doc = locals[cur_frm.doctype][cur_frm.docname];
 			if(doc.customer) $c_obj(make_doclist(dt,dn), 'get_default_customer_address', '', callback2);
-			if(doc.customer) unhide_field('contact_section');
+			cur_frm.toggle_display("contact_section", doc.customer);
+			
 			cur_frm.refresh();
 	}
 
diff --git a/accounts/utils/__init__.py b/accounts/utils/__init__.py
index c4a0042..8ad1899 100644
--- a/accounts/utils/__init__.py
+++ b/accounts/utils/__init__.py
@@ -28,8 +28,8 @@
 		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
 			as year_end_date
 		from `tabFiscal Year`
-		where %s >= year_start_date and %s < adddate(year_start_date, interval 1 year)""",
-		(date, date))
+		where %s >= year_start_date and %s < adddate(year_start_date, interval 1 year)
+		order by year_start_date desc""", (date, date))
 	
 	if not fy:
 		error_msg = """%s not in any Fiscal Year""" % formatdate(date)
diff --git a/home/page/latest_updates/latest_updates.js b/home/page/latest_updates/latest_updates.js
index 97ee561..e8b30cf 100644
--- a/home/page/latest_updates/latest_updates.js
+++ b/home/page/latest_updates/latest_updates.js
@@ -1,6 +1,6 @@
 erpnext.updates = [
 	["7th January 2013", [
-		"Language (backend): Integrated language libraries."
+		"Language (backend): Integrated language libraries."]],
 	["4th January 2013", [
 		"Support Analytics: Simple Tool to Plot Number Tickets and time to Closing",
 		"Workflow: Added Workflow Help",
diff --git a/hr/doctype/employee/employee.txt b/hr/doctype/employee/employee.txt
index 0c48287..6e3e828 100644
--- a/hr/doctype/employee/employee.txt
+++ b/hr/doctype/employee/employee.txt
@@ -2,9 +2,9 @@
  {
   "owner": "Administrator", 
   "docstatus": 0, 
-  "creation": "2012-12-03 10:13:46", 
+  "creation": "2013-01-02 16:17:01", 
   "modified_by": "Administrator", 
-  "modified": "2012-12-27 14:45:31"
+  "modified": "2013-01-09 14:46:42"
  }, 
  {
   "autoname": "naming_series:", 
@@ -150,6 +150,7 @@
   "permlevel": 0
  }, 
  {
+  "description": "You can enter any date manually", 
   "oldfieldtype": "Date", 
   "doctype": "DocField", 
   "label": "Date of Birth", 
diff --git a/hr/doctype/holiday_list/holiday_list.py b/hr/doctype/holiday_list/holiday_list.py
index 43f9916..e5504fa 100644
--- a/hr/doctype/holiday_list/holiday_list.py
+++ b/hr/doctype/holiday_list/holiday_list.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/>.
 
 from __future__ import unicode_literals
 import webnotes
@@ -26,101 +26,64 @@
 sql = webnotes.conn.sql
 
 import datetime
-	
-
 
 class DocType:
-  def __init__(self,doc,doclist=[]):
-    self.doc = doc
-    self.doclist = doclist
+	def __init__(self,doc,doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
 
-  # ---------
-  # autoname
-  # ---------
-  def autoname(self):
-    self.doc.name = make_autoname(self.doc.fiscal_year +"/"+ self.doc.holiday_list_name+"/.###")
+	def autoname(self):
+		self.doc.name = make_autoname(self.doc.fiscal_year +"/"+ self.doc.holiday_list_name+"/.###")
+		
+	def validate(self):
+		self.update_default_holiday_list()
+	
+	def get_weekly_off_dates(self):
+		self.validate_values()
+		yr_start_date, yr_end_date = self.get_fy_start_end_dates()
+		date_list = self.get_weekly_off_date_list(yr_start_date, yr_end_date)
+		for d in date_list:
+			ch = addchild(self.doc, 'holiday_list_details', 'Holiday', self.doclist)
+			ch.description = self.doc.weekly_off
+			ch.holiday_date = d
 
+	def validate_values(self):
+		if not self.doc.fiscal_year:
+			msgprint("Please select Fiscal Year")
+			raise Exception
+		if not self.doc.weekly_off:
+			msgprint("Please select weekly off day")
+			raise Exception
 
-# *************************************************** utilities ***********************************************
-  # ----------------
-  # validate values
-  # ----------------
-  def validate_values(self):
-    if not self.doc.fiscal_year:
-      msgprint("Please select Fiscal Year")
-      raise Exception
-    if not self.doc.weekly_off:
-      msgprint("Please select weekly off day")
-      raise Exception
+	def get_fy_start_end_dates(self):
+		return webnotes.conn.sql("""select year_start_date, 
+			subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
+				as year_end_date
+			from `tabFiscal Year`
+			where name=%s""", (self.doc.fiscal_year,))[0]
 
+	def get_weekly_off_date_list(self, year_start_date, year_end_date):
+		from webnotes.utils import getdate
+		year_start_date, year_end_date = getdate(year_start_date), getdate(year_end_date)
+		
+		from dateutil import relativedelta
+		from datetime import timedelta
+		import calendar
+		
+		date_list = []
+		weekday = getattr(calendar, (self.doc.weekly_off).upper())
+		reference_date = year_start_date + relativedelta.relativedelta(weekday=weekday)
+			
+		while reference_date <= year_end_date:
+			date_list.append(reference_date)
+			reference_date += timedelta(days=7)
+		
+		return date_list
+	
+	def clear_table(self):
+		self.doclist = self.doc.clear_table(self.doclist, 'holiday_list_details')
 
-  # ------------------------------------
-  # get fiscal year start and end dates
-  # ------------------------------------
-  def get_fy_start_end_dates(self):
-    st_date = sql("select year_start_date from `tabFiscal Year` where name = '%s'" %(self.doc.fiscal_year))
-    st_date = st_date and st_date[0][0].strftime('%Y-%m-%d') or ''
-    ed_date = add_days(add_years(st_date,1), -1)
-    return st_date, ed_date
+	def update_default_holiday_list(self):
+		webnotes.conn.sql("""update `tabHoliday List` set is_default = 0 
+			where ifnull(is_default, 0) = 1 and fiscal_year = %s""", (self.doc.fiscal_year,))
 
-  # -------------------------
-  # get weekly off date list
-  # -------------------------
-  def get_weekly_off_date_list(self, yr_start_date, yr_end_date):
-    days_dict, dt_list, lst_st = {'Monday':0,'Tuesday':1,'Wednesday':2,'Thursday':3,'Friday':4,'Saturday':5,'Sunday':6}, [], ''
-
-    w = cint(days_dict[self.doc.weekly_off])    # Weekly Off Day No.
-
-    st_dt_weekday = getdate(yr_start_date).weekday()    # Year Start Date weekday()
-
-    if w == st_dt_weekday:     # Get Start Date
-      lst_st = yr_start_date
-      dt_list.append(lst_st)
-    elif w > st_dt_weekday:
-      lst_st = add_days(yr_start_date,w - st_dt_weekday)
-      dt_list.append(lst_st)
-    else:
-      lst_st = add_days(yr_start_date,6 - st_dt_weekday + 1)
-      dt_list.append(lst_st)
-
-    while getdate(lst_st) < getdate(yr_end_date):    # Get list of dates
-      lst_st = add_days(lst_st,7)
-      if getdate(lst_st) > getdate(yr_end_date):
-        break
-      dt_list.append(lst_st)
-
-    return dt_list
-
-  # ---------------------
-  # get weekly off dates
-  # ---------------------
-  def get_weekly_off_dates(self):
-    self.validate_values()
-    yr_start_date, yr_end_date = self.get_fy_start_end_dates()
-    date_list = self.get_weekly_off_date_list(yr_start_date, yr_end_date)
-    for d in date_list:
-      ch = addchild(self.doc, 'holiday_list_details', 'Holiday', self.doclist)
-      ch.description = self.doc.weekly_off
-      ch.holiday_date = d
-
-  # ------------
-  # clear table
-  # ------------
-  def clear_table(self):
-    self.doclist = self.doc.clear_table(self.doclist,'holiday_list_details')
-
-
-# ***************************************** validate *************************************************
-
-  # ---------------------------
-  # check default holiday list
-  # ---------------------------
-  def update_default_holiday_list(self):
-    sql("update `tabHoliday List` set is_default = 0 where ifnull(is_default, 0) = 1 and fiscal_year = '%s'" % (self.doc.fiscal_year))
-
-
-  # ---------
-  # validate
-  # ---------
-  def validate(self):
-    self.update_default_holiday_list()
diff --git a/hr/doctype/leave_application/leave_application.py b/hr/doctype/leave_application/leave_application.py
index ad3f864..310c155 100755
--- a/hr/doctype/leave_application/leave_application.py
+++ b/hr/doctype/leave_application/leave_application.py
@@ -46,9 +46,14 @@
 		"""
 			get total holidays
 		"""
-		tot_hol = sql("select count(*) from `tabHoliday` h1, `tabHoliday List` h2, `tabEmployee` e1 where e1.name = '%s' and h1.parent = h2.name and e1.holiday_list = h2.name and h1.holiday_date between '%s' and '%s'"% (self.doc.employee, self.doc.from_date, self.doc.to_date))
+		tot_hol = sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2, `tabEmployee` e1 
+			where e1.name = %s and h1.parent = h2.name and e1.holiday_list = h2.name 
+			and h1.holiday_date between %s and %s""", (self.doc.employee, self.doc.from_date, self.doc.to_date))
 		if not tot_hol:
-			tot_hol = sql("select count(*) from `tabHoliday` h1, `tabHoliday List` h2 where h1.parent = h2.name and h1.holiday_date between '%s' and '%s' and ifnull(h2.is_default,0) = 1 and h2.fiscal_year = %s"% (self.doc.from_date, self.doc.to_date, self.doc.fiscal_year))
+			tot_hol = sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2 
+				where h1.parent = h2.name and h1.holiday_date between %s and %s
+				and ifnull(h2.is_default,0) = 1 and h2.fiscal_year = %s""",
+				(self.doc.from_date, self.doc.to_date, self.doc.fiscal_year))
 		return tot_hol and flt(tot_hol[0][0]) or 0
 
 	def get_total_leave_days(self):
diff --git a/manufacturing/doctype/bom/bom.js b/manufacturing/doctype/bom/bom.js
index f2746de..cdb863d 100644
--- a/manufacturing/doctype/bom/bom.js
+++ b/manufacturing/doctype/bom/bom.js
@@ -174,7 +174,7 @@
 
 
 cur_frm.fields_dict['item'].get_query = function(doc) {
-	return return erpnext.queries.item({
+	return erpnext.queries.item({
 		'ifnull(tabItem.is_manufactured_item, "No")': 'Yes'
 	})
 }
diff --git a/patches/january_2013/holiday_list_patch.py b/patches/january_2013/holiday_list_patch.py
new file mode 100644
index 0000000..e8e8f8c
--- /dev/null
+++ b/patches/january_2013/holiday_list_patch.py
@@ -0,0 +1,41 @@
+import webnotes
+def execute():
+	for name in webnotes.conn.sql("""select name from `tabHoliday List`"""):
+		holiday_list_wrapper = webnotes.model_wrapper("Holiday List", name[0])
+		
+		desc_count = _count([d.description for d in 
+			holiday_list_wrapper.doclist.get({"doctype": "Holiday"})])
+			
+		holiday_list_obj = webnotes.get_obj(doc=holiday_list_wrapper.doc,
+			doclist=holiday_list_wrapper.doclist)
+			
+		save = False
+		
+		for desc in desc_count.keys():
+			if desc in ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
+					"Friday", "Saturday"] and desc_count[desc] > 50:
+				holiday_list_obj.doclist = holiday_list_obj.doclist.get(
+					{"description": ["!=", desc]})
+				
+				webnotes.conn.sql("""delete from `tabHoliday`
+					where parent=%s and parenttype='Holiday List' 
+					and `description`=%s""", (holiday_list_obj.doc.name, desc))
+				holiday_list_obj.doc.weekly_off = desc
+				holiday_list_obj.get_weekly_off_dates()
+				save = True
+		
+		if save:
+			holiday_list_wrapper.set_doclist(holiday_list_obj.doclist)
+			holiday_list_wrapper.save()
+				
+def _count(lst):
+	out = {}	
+	for l in lst:
+		out[l] = out.setdefault(l, 0) + 1
+		
+	return out
+		
+		
+		
+		
+		
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index 2dd37ec..f9bb97c 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -578,4 +578,8 @@
 		'patch_module': 'patches.january_2013',
 		'patch_file': 'remove_support_search_criteria',
 	},
+	{
+		'patch_module': 'patches.january_2013',
+		'patch_file': 'holiday_list_patch',
+	},
 ]
\ No newline at end of file
diff --git a/selling/doctype/opportunity/opportunity.js b/selling/doctype/opportunity/opportunity.js
index d5c665a..664b88d 100644
--- a/selling/doctype/opportunity/opportunity.js
+++ b/selling/doctype/opportunity/opportunity.js
@@ -25,6 +25,9 @@
 		cur_frm.add_custom_button('Opportunity Lost', cur_frm.cscript['Declare Opportunity Lost']);
 		cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
 	}
+	
+	cur_frm.toggle_display("contact_info", doc.customer || doc.lead);
+	
 }
 
 // ONLOAD
@@ -79,7 +82,7 @@
 }
 
 // hide - unhide fields based on lead or customer
-cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
+cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){	
 	if(doc.enquiry_from == 'Lead'){
 		unhide_field(['lead']);
 		hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
@@ -87,13 +90,15 @@
 	}
 	else if(doc.enquiry_from == 'Customer'){		
 		unhide_field(['customer']);
-		hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);		
+		hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory', 'customer_group']);		
 		doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
 	}
 }
 
 // customer
 cur_frm.cscript.customer = function(doc,dt,dn) {
+	cur_frm.toggle_display("contact_info", doc.customer || doc.lead);
+	
 	if(doc.customer) {
 		cur_frm.call({
 			doc: cur_frm.doc,
@@ -127,11 +132,18 @@
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return 'SELECT name, address_line1, city FROM tabAddress \
+		WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND \
+		%(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	if (!doc.customer) msgprint("Please select customer first");
+	else {
+		return 'SELECT name, CONCAT(first_name," ",ifnull(last_name,"")) As FullName, \
+		department, designation FROM tabContact WHERE customer = "'+ doc.customer + 
+		'" AND docstatus != 2 AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+	}
 }
 
 // lead
@@ -140,6 +152,8 @@
 }
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
+	cur_frm.toggle_display("contact_info", doc.customer || doc.lead);
+	
 	if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
 	if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);	
 }
diff --git a/selling/doctype/quotation/quotation.js b/selling/doctype/quotation/quotation.js
index 3673b07..330e4e7 100644
--- a/selling/doctype/quotation/quotation.js
+++ b/selling/doctype/quotation/quotation.js
@@ -93,9 +93,7 @@
 	}
 
 	erpnext.hide_naming_series();
-	
-	if(doc.customer || doc.lead) $(cur_frm.fields_dict.contact_section.row.wrapper).toggle(true);
-	else $(cur_frm.fields_dict.contact_section.row.wrapper).toggle(false);
+	cur_frm.toggle_display("contact_section", doc.customer || doc.lead);
 	
 	if (!doc.__islocal) {
 		cur_frm.communication_view = new wn.views.CommunicationList({
@@ -120,6 +118,8 @@
 	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 
 		'get_default_customer_address', '', callback);
 	if(doc.customer) unhide_field(['customer_address','contact_person','territory', 'customer_group']);
+	cur_frm.toggle_display("contact_section", doc.customer || doc.lead);
+	
 }
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
@@ -130,27 +130,11 @@
 	}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict.customer_address.on_new = function(dn) {
-	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict.contact_person.on_new = function(dn) {
-	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
 cur_frm.fields_dict.lead.get_query = erpnext.utils.lead_query;
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
+	cur_frm.toggle_display("contact_section", doc.customer || doc.lead);
+	
 	if(doc.lead) {
 		get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
 		unhide_field('territory');
diff --git a/selling/doctype/sales_common/sales_common.js b/selling/doctype/sales_common/sales_common.js
index c1435bd..4ceac9e 100644
--- a/selling/doctype/sales_common/sales_common.js
+++ b/selling/doctype/sales_common/sales_common.js
@@ -320,7 +320,27 @@
 		}
 	}
 
+cur_frm.fields_dict.customer_address.on_new = function(dn) {
+	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+}
 
+cur_frm.fields_dict.contact_person.on_new = function(dn) {
+	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
+	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
+}
+
+cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
+	return 'SELECT name, address_line1, city FROM tabAddress \
+		WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND \
+		%(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+}
+
+cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
+	return 'SELECT name, CONCAT(first_name," ",ifnull(last_name,"")) As FullName, \
+		department, designation FROM tabContact WHERE customer = "'+ doc.customer + 
+		'" AND docstatus != 2 AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+}
 
 // *********************** QUANTITY ***************************
 cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); }
diff --git a/selling/doctype/sales_order/sales_order.js b/selling/doctype/sales_order/sales_order.js
index a3b71b4..607b132 100644
--- a/selling/doctype/sales_order/sales_order.js
+++ b/selling/doctype/sales_order/sales_order.js
@@ -36,7 +36,9 @@
 	// load default charges
 	
 	if(doc.__islocal && !doc.customer){
-		hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+		hide_field(['customer_address','contact_person', 'customer_name', 
+			'address_display', 'contact_display', 'contact_mobile', 
+			'contact_email', 'territory',  'customer_group']);
 	}
 }
 
@@ -59,9 +61,8 @@
 
 	if (!cur_frm.cscript.is_onload) cur_frm.cscript.hide_price_list_currency(doc, cdt, cdn); 
 	
-	if(doc.customer) $(cur_frm.fields_dict.contact_info.row.wrapper).toggle(true);
-	else $(cur_frm.fields_dict.contact_info.row.wrapper).toggle(false);
-
+	cur_frm.toggle_display("contact_info", doc.customer);
+	
 	if(doc.docstatus==1) {
 		if(doc.status != 'Stopped') {
 			cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
@@ -105,11 +106,13 @@
 
 //customer
 cur_frm.cscript.customer = function(doc,dt,dn) {
+	cur_frm.toggle_display("contact_info", doc.customer);
+	
 	var pl = doc.price_list_name;
 	var callback = function(r,rt) {
 		var callback2  = function(r, rt) {
-
-			if(doc.customer) unhide_field(['customer_address', 'contact_person', 'territory','customer_group']);
+			if(doc.customer) 
+				unhide_field(['customer_address', 'contact_person', 'territory','customer_group']);
 			cur_frm.refresh();
 			
 			if(!onload && (pl != doc.price_list_name)) cur_frm.cscript.price_list_name(doc, dt, dn);
@@ -119,38 +122,22 @@
 		get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0, callback2);
 			
 	}	 
-	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
+	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 
+		'get_default_customer_address', '', callback);
 }
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict.customer_address.on_new = function(dn) {
-	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict.contact_person.on_new = function(dn) {
-	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
 cur_frm.cscript.pull_quotation_details = function(doc,dt,dn) {
 	var callback = function(r,rt){
 		var doc = locals[cur_frm.doctype][cur_frm.docname];					
 		if(!r.exc){							
 			doc.quotation_no = r.message;			
 			if(doc.quotation_no) {					
-				unhide_field(['quotation_date', 'customer_address', 'contact_person', 'territory', 'customer_group']);
+				unhide_field(['quotation_date', 'customer_address', 
+					'contact_person', 'territory', 'customer_group']);
 				if(doc.customer) get_server_fields('get_shipping_address', doc.customer, '', doc, dt, dn, 0);
 			}			
 			cur_frm.refresh();
diff --git a/setup/doctype/global_defaults/global_defaults.py b/setup/doctype/global_defaults/global_defaults.py
index 48c2365..1d93e24 100644
--- a/setup/doctype/global_defaults/global_defaults.py
+++ b/setup/doctype/global_defaults/global_defaults.py
@@ -64,6 +64,9 @@
 			webnotes.conn.set_default('year_start_date', ysd.strftime('%Y-%m-%d'))
 			webnotes.conn.set_default('year_end_date', \
 				get_last_day(get_first_day(ysd,0,11)).strftime('%Y-%m-%d'))
+				
+		# clear cache
+		webnotes.clear_cache()
 	
 	def validate_session_expiry(self):
 		if self.doc.session_expiry:
diff --git a/stock/doctype/delivery_note/delivery_note.js b/stock/doctype/delivery_note/delivery_note.js
index a80966a..223b064 100644
--- a/stock/doctype/delivery_note/delivery_note.js
+++ b/stock/doctype/delivery_note/delivery_note.js
@@ -37,7 +37,9 @@
 	if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time()
 		
 	if(doc.__islocal){
-		hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+		hide_field(['customer_address', 'contact_person', 'customer_name', 
+			'address_display', 'contact_display', 'contact_mobile', 
+			'contact_email', 'territory', 'customer_group']);
 	}	
 }
 
@@ -69,8 +71,7 @@
 		cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
 	}
 	
-	if(doc.customer) $(cur_frm.fields_dict.contact_info.row.wrapper).toggle(true);
-	else $(cur_frm.fields_dict.contact_info.row.wrapper).toggle(false);
+	cur_frm.toggle_display("contact_info", doc.customer);
 	
 	set_print_hide(doc, cdt, cdn);
 }
@@ -78,38 +79,25 @@
 
 //customer
 cur_frm.cscript.customer = function(doc,dt,dn,onload) {	
+	cur_frm.toggle_display("contact_info", doc.customer);
+	
 	var pl = doc.price_list_name;
 	var callback = function(r,rt) {
 			var doc = locals[cur_frm.doctype][cur_frm.docname];
-			if(doc.customer) unhide_field(['customer_address','contact_person','territory','customer_group']);
+			if(doc.customer)
+			 	unhide_field(['customer_address','contact_person','territory','customer_group']);
 			cur_frm.refresh();
 			if(!onload && (pl != doc.price_list_name)) cur_frm.cscript.price_list_name(doc, dt, dn); 
 	} 
 	var args = onload ? 'onload':''
-	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', args, callback);
+	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name),
+	 	'get_default_customer_shipping_address', args, callback);
 }
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict.customer_address.on_new = function(dn) {
-	locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict.contact_person.on_new = function(dn) {
-	locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
-	locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
-}
-
-cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
-
-cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
 
 cur_frm.cscript.get_items = function(doc,dt,dn) {
 	var callback = function(r,rt){
@@ -117,9 +105,12 @@
 		if(r.message){							
 			doc.sales_order_no = r.message;			
 			if(doc.sales_order_no) {					
-					unhide_field(['customer_address','contact_person','territory','customer_group']);														
+				unhide_field(['customer_address','contact_person','territory','customer_group']);														
 			}			
-			refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
+			
+			refresh_many(['delivery_note_details', 'customer', 'customer_address',
+			 	'contact_person', 'customer_name', 'address_display', 'contact_display',
+			 	'contact_mobile', 'contact_email', 'territory', 'customer_group']);
 		}
 	} 
  $c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback); 
diff --git a/stock/doctype/delivery_note/delivery_note.txt b/stock/doctype/delivery_note/delivery_note.txt
index d3e1642..215dd41 100644
--- a/stock/doctype/delivery_note/delivery_note.txt
+++ b/stock/doctype/delivery_note/delivery_note.txt
@@ -2,9 +2,9 @@
  {
   "owner": "Administrator", 
   "docstatus": 0, 
-  "creation": "2012-11-28 11:26:21", 
+  "creation": "2012-12-03 17:26:43", 
   "modified_by": "Administrator", 
-  "modified": "2012-12-03 17:10:41"
+  "modified": "2013-01-09 12:52:30"
  }, 
  {
   "is_submittable": 1, 
@@ -19,6 +19,7 @@
   "doctype": "DocType"
  }, 
  {
+  "read_only": 0, 
   "name": "__common__", 
   "parent": "Delivery Note", 
   "doctype": "DocField", 
@@ -38,10 +39,10 @@
   "doctype": "DocType"
  }, 
  {
+  "print_width": "50%", 
   "oldfieldtype": "Column Break", 
   "doctype": "DocField", 
   "width": "50%", 
-  "trigger": "Client", 
   "fieldname": "column_break0", 
   "fieldtype": "Column Break", 
   "permlevel": 0
@@ -51,7 +52,6 @@
   "description": "To manage multiple series please go to Setup > Manage Series", 
   "no_copy": 1, 
   "oldfieldtype": "Select", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Series", 
   "oldfieldname": "naming_series", 
@@ -68,7 +68,6 @@
   "label": "Customer", 
   "oldfieldname": "customer", 
   "permlevel": 0, 
-  "trigger": "Client", 
   "fieldname": "customer", 
   "fieldtype": "Link", 
   "search_index": 1, 
@@ -86,6 +85,7 @@
  }, 
  {
   "print_hide": 1, 
+  "depends_on": "customer", 
   "doctype": "DocField", 
   "label": "Select Shipping Address", 
   "options": "Address", 
@@ -136,11 +136,11 @@
  }, 
  {
   "print_hide": 0, 
+  "permlevel": 0, 
   "description": "The date at which current entry will get or has actually executed.", 
-  "width": "100px", 
+  "print_width": "100px", 
   "default": "Today", 
   "oldfieldtype": "Date", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Posting Date", 
   "oldfieldname": "posting_date", 
@@ -150,7 +150,7 @@
   "search_index": 1, 
   "reqd": 1, 
   "in_filter": 1, 
-  "permlevel": 0
+  "width": "100px"
  }, 
  {
   "print_hide": 1, 
@@ -176,6 +176,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "100px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
   "doctype": "DocField", 
@@ -189,9 +190,9 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "100px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "P.O. Date", 
   "oldfieldname": "po_date", 
@@ -204,7 +205,6 @@
  }, 
  {
   "oldfieldtype": "Section Break", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Items", 
   "fieldname": "items", 
@@ -215,7 +215,6 @@
   "print_hide": 0, 
   "no_copy": 0, 
   "oldfieldtype": "Table", 
-  "colour": "White:FFF", 
   "allow_on_submit": 1, 
   "doctype": "DocField", 
   "label": "Delivery Note Items", 
@@ -248,6 +247,7 @@
  }, 
  {
   "print_hide": 0, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
@@ -263,7 +263,6 @@
   "oldfieldtype": "Button", 
   "doctype": "DocField", 
   "label": "Re-Calculate Values", 
-  "trigger": "Client", 
   "fieldname": "recalculate_values", 
   "fieldtype": "Button", 
   "permlevel": 0
@@ -279,7 +278,6 @@
   "description": "You can make a delivery note from multiple sales orders. Select sales orders one by one and click on the button below.", 
   "no_copy": 0, 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Sales Order No", 
   "oldfieldname": "sales_order_no", 
@@ -316,12 +314,10 @@
   "print_hide": 1, 
   "description": "Select the price list as entered in \"Price List\" master. This will pull the reference rates of items against this price list as specified in \"Item\" master.", 
   "oldfieldtype": "Select", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Price List", 
   "oldfieldname": "price_list_name", 
   "permlevel": 0, 
-  "trigger": "Client", 
   "fieldname": "price_list_name", 
   "fieldtype": "Select", 
   "reqd": 1, 
@@ -330,7 +326,6 @@
  {
   "print_hide": 1, 
   "description": "Select the currency in which price list is maintained", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Price List Currency", 
   "options": "link:Currency", 
@@ -342,7 +337,6 @@
  {
   "print_hide": 1, 
   "description": "Rate at which Price list currency is converted to company's base currency", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Price List Currency Conversion Rate", 
   "fieldname": "plc_conversion_rate", 
@@ -351,6 +345,7 @@
   "permlevel": 0
  }, 
  {
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "column_break2", 
@@ -361,7 +356,6 @@
   "print_hide": 1, 
   "description": "Customer's Currency", 
   "oldfieldtype": "Select", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Currency", 
   "oldfieldname": "currency", 
@@ -376,7 +370,6 @@
   "description": "Rate at which customer's currency is converted to company's base currency", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Conversion Rate", 
   "oldfieldname": "conversion_rate", 
@@ -388,7 +381,6 @@
  }, 
  {
   "oldfieldtype": "Section Break", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Taxes", 
   "fieldname": "taxes", 
@@ -399,7 +391,6 @@
   "print_hide": 1, 
   "description": "If you have created a standard template in Sales Taxes and Charges Master, select one and click on the button below.", 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Taxes and Charges", 
   "oldfieldname": "charge", 
@@ -413,7 +404,6 @@
   "oldfieldtype": "Button", 
   "doctype": "DocField", 
   "label": "Get Taxes and Charges", 
-  "trigger": "Client", 
   "fieldname": "get_charges", 
   "fieldtype": "Button", 
   "permlevel": 0
@@ -431,6 +421,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "150px", 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
   "label": "Taxes and Charges Total", 
@@ -445,7 +436,6 @@
   "oldfieldtype": "Button", 
   "doctype": "DocField", 
   "label": "Calculate Charges", 
-  "trigger": "Client", 
   "fieldname": "calculate_charges", 
   "fieldtype": "Button", 
   "permlevel": 0
@@ -461,7 +451,6 @@
  {
   "print_hide": 0, 
   "oldfieldtype": "Section Break", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Totals", 
   "fieldname": "totals", 
@@ -470,6 +459,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
@@ -483,6 +473,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
@@ -496,9 +487,9 @@
  {
   "print_hide": 1, 
   "description": "In Words will be visible once you save the Delivery Note.", 
+  "print_width": "200px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "In Words", 
   "oldfieldname": "in_words", 
@@ -516,6 +507,7 @@
  }, 
  {
   "print_hide": 0, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
@@ -529,6 +521,7 @@
  }, 
  {
   "print_hide": 0, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
@@ -542,9 +535,9 @@
  {
   "print_hide": 0, 
   "description": "In Words (Export) will be visible once you save the Delivery Note.", 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "In Words (Export)", 
   "oldfieldname": "in_words_export", 
@@ -575,19 +568,16 @@
  {
   "print_hide": 1, 
   "oldfieldtype": "Button", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Get Terms and Conditions", 
-  "trigger": "Server", 
+  "options": "get_tc_details", 
   "fieldname": "get_terms", 
   "fieldtype": "Button", 
-  "options": "get_tc_details", 
   "permlevel": 0
  }, 
  {
   "print_hide": 1, 
   "oldfieldtype": "HTML", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Terms and Conditions HTML", 
   "options": "You can add Terms and Notes that will be printed in the Transaction", 
@@ -597,7 +587,6 @@
  }, 
  {
   "oldfieldtype": "Text Editor", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Terms and Conditions Details", 
   "oldfieldname": "terms", 
@@ -615,6 +604,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "column_break4", 
@@ -623,20 +613,20 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Transporter Name", 
   "oldfieldname": "transporter_name", 
   "width": "150px", 
-  "trigger": "Client", 
   "fieldname": "transporter_name", 
   "fieldtype": "Data", 
   "reqd": 0, 
   "permlevel": 0
  }, 
  {
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "col_break34", 
@@ -646,9 +636,9 @@
  {
   "print_hide": 1, 
   "description": "Transporter lorry number", 
+  "print_width": "100px", 
   "no_copy": 0, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "LR No", 
   "oldfieldname": "lr_no", 
@@ -660,18 +650,18 @@
  }, 
  {
   "print_hide": 1, 
+  "permlevel": 0, 
   "description": "Date on which lorry started from your warehouse", 
-  "width": "100px", 
+  "print_width": "100px", 
   "default": "Today", 
   "oldfieldtype": "Date", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "LR Date", 
   "oldfieldname": "lr_date", 
   "no_copy": 0, 
   "fieldname": "lr_date", 
   "fieldtype": "Date", 
-  "permlevel": 0
+  "width": "100px"
  }, 
  {
   "doctype": "DocField", 
@@ -681,6 +671,7 @@
   "permlevel": 0
  }, 
  {
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "col_break20", 
@@ -698,6 +689,7 @@
   "in_filter": 1
  }, 
  {
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "col_break21", 
@@ -709,12 +701,12 @@
   "search_index": 1, 
   "doctype": "DocField", 
   "label": "Territory", 
-  "options": "Territory", 
+  "permlevel": 0, 
   "fieldname": "territory", 
   "fieldtype": "Link", 
   "reqd": 1, 
   "hidden": 0, 
-  "permlevel": 0, 
+  "options": "Territory", 
   "in_filter": 1
  }, 
  {
@@ -732,7 +724,6 @@
   "print_hide": 1, 
   "description": "Filling in Additional Information about the Delivery Note will help you analyze your data better.", 
   "oldfieldtype": "Section Break", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "More Info", 
   "fieldname": "more_info", 
@@ -742,8 +733,8 @@
  {
   "print_hide": 1, 
   "description": "Time at which items were delivered from warehouse", 
+  "print_width": "100px", 
   "oldfieldtype": "Time", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Posting Time", 
   "oldfieldname": "posting_time", 
@@ -758,24 +749,25 @@
  {
   "print_hide": 1, 
   "permlevel": 1, 
-  "width": "150px", 
+  "print_width": "150px", 
   "default": "Draft", 
   "oldfieldtype": "Select", 
   "doctype": "DocField", 
   "label": "Status", 
   "oldfieldname": "status", 
   "no_copy": 1, 
+  "options": "\nDraft\nSubmitted\nCancelled", 
   "fieldname": "status", 
   "fieldtype": "Select", 
   "search_index": 1, 
   "reqd": 1, 
-  "options": "\nDraft\nSubmitted\nCancelled", 
+  "width": "150px", 
   "in_filter": 1
  }, 
  {
   "print_hide": 1, 
-  "allow_on_submit": 1, 
   "oldfieldtype": "Link", 
+  "allow_on_submit": 1, 
   "doctype": "DocField", 
   "label": "Letter Head", 
   "oldfieldname": "letter_head", 
@@ -788,13 +780,11 @@
   "print_hide": 1, 
   "no_copy": 1, 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "allow_on_submit": 1, 
   "doctype": "DocField", 
   "label": "Select Print Heading", 
   "oldfieldname": "select_print_heading", 
   "permlevel": 0, 
-  "trigger": "Client", 
   "fieldname": "select_print_heading", 
   "fieldtype": "Link", 
   "options": "Print Heading", 
@@ -803,12 +793,10 @@
  {
   "description": "Track this Delivery Note against any Project", 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Project Name", 
   "oldfieldname": "project_name", 
   "permlevel": 0, 
-  "trigger": "Client", 
   "fieldname": "project_name", 
   "fieldtype": "Link", 
   "search_index": 1, 
@@ -829,7 +817,6 @@
  {
   "print_hide": 1, 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Campaign", 
   "oldfieldname": "campaign", 
@@ -841,18 +828,18 @@
  }, 
  {
   "print_hide": 1, 
-  "allow_on_submit": 1, 
   "oldfieldtype": "Check", 
+  "allow_on_submit": 1, 
   "doctype": "DocField", 
   "label": "Print Without Amount", 
   "oldfieldname": "print_without_amount", 
-  "trigger": "Client", 
   "fieldname": "print_without_amount", 
   "fieldtype": "Check", 
   "permlevel": 0
  }, 
  {
   "print_hide": 1, 
+  "print_width": "50%", 
   "oldfieldtype": "Column Break", 
   "doctype": "DocField", 
   "width": "50%", 
@@ -866,7 +853,6 @@
   "description": "% of materials billed against this Delivery Note", 
   "no_copy": 1, 
   "search_index": 1, 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "% Amount Billed", 
   "oldfieldname": "per_billed", 
@@ -893,7 +879,6 @@
   "description": "% of materials delivered against this Delivery Note", 
   "no_copy": 1, 
   "search_index": 1, 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "% Installed", 
   "oldfieldname": "per_installed", 
@@ -914,9 +899,10 @@
  }, 
  {
   "print_hide": 1, 
-  "allow_on_submit": 0, 
+  "print_width": "150px", 
   "no_copy": 1, 
   "oldfieldtype": "Data", 
+  "allow_on_submit": 0, 
   "doctype": "DocField", 
   "label": "Amended From", 
   "oldfieldname": "amended_from", 
@@ -928,6 +914,7 @@
  {
   "print_hide": 1, 
   "description": "The date at which current entry is corrected in the system.", 
+  "print_width": "100px", 
   "no_copy": 1, 
   "oldfieldtype": "Date", 
   "doctype": "DocField", 
@@ -943,7 +930,6 @@
   "description": "Required only for sample item.", 
   "no_copy": 1, 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "To Warehouse", 
   "oldfieldname": "to_warehouse", 
@@ -956,7 +942,6 @@
  {
   "print_hide": 1, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Excise Page Number", 
   "oldfieldname": "excise_page", 
@@ -977,9 +962,9 @@
  {
   "print_hide": 1, 
   "description": "Select the relevant company name if you have multiple companies", 
+  "print_width": "150px", 
   "permlevel": 0, 
   "oldfieldtype": "Link", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Company", 
   "oldfieldname": "company", 
@@ -993,6 +978,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "150px", 
   "permlevel": 0, 
   "oldfieldtype": "Select", 
   "doctype": "DocField", 
@@ -1010,7 +996,6 @@
   "print_hide": 1, 
   "no_copy": 1, 
   "oldfieldtype": "Data", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Cancel Reason", 
   "oldfieldname": "cancel_reason", 
@@ -1043,7 +1028,6 @@
  {
   "print_hide": 1, 
   "oldfieldtype": "Section Break", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Sales Team", 
   "fieldname": "sales_team_section_break", 
@@ -1052,6 +1036,7 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "column_break6", 
@@ -1061,19 +1046,20 @@
  {
   "print_hide": 1, 
   "permlevel": 0, 
+  "print_width": "150px", 
   "no_copy": 0, 
   "oldfieldtype": "Link", 
   "doctype": "DocField", 
   "label": "Sales Partner", 
   "oldfieldname": "sales_partner", 
   "width": "150px", 
-  "trigger": "Client", 
   "fieldname": "sales_partner", 
   "fieldtype": "Link", 
   "options": "Sales Partner"
  }, 
  {
   "print_hide": 1, 
+  "print_width": "50%", 
   "doctype": "DocField", 
   "width": "50%", 
   "fieldname": "column_break7", 
@@ -1082,13 +1068,13 @@
  }, 
  {
   "print_hide": 1, 
+  "print_width": "100px", 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
   "doctype": "DocField", 
   "label": "Commission Rate (%)", 
   "oldfieldname": "commission_rate", 
   "width": "100px", 
-  "trigger": "Client", 
   "fieldname": "commission_rate", 
   "fieldtype": "Currency", 
   "permlevel": 0
@@ -1097,11 +1083,9 @@
   "print_hide": 1, 
   "no_copy": 0, 
   "oldfieldtype": "Currency", 
-  "colour": "White:FFF", 
   "doctype": "DocField", 
   "label": "Total Commission", 
   "oldfieldname": "total_commission", 
-  "trigger": "Client", 
   "fieldname": "total_commission", 
   "fieldtype": "Currency", 
   "permlevel": 0
@@ -1145,8 +1129,12 @@
   "permlevel": 0
  }, 
  {
+  "amend": 0, 
+  "create": 0, 
   "doctype": "DocPerm", 
+  "submit": 0, 
   "role": "Accounts User", 
+  "cancel": 0, 
   "permlevel": 1
  }, 
  {
@@ -1157,8 +1145,7 @@
   "write": 1, 
   "role": "Sales User", 
   "cancel": 1, 
-  "permlevel": 0, 
-  "match": ""
+  "permlevel": 0
  }, 
  {
   "amend": 0, 
@@ -1173,13 +1160,17 @@
  {
   "doctype": "DocPerm", 
   "role": "Customer", 
-  "match": "customer_name", 
-  "permlevel": 0
+  "permlevel": 0, 
+  "match": "customer_name"
  }, 
  {
-  "write": 1, 
+  "amend": 0, 
+  "create": 0, 
   "doctype": "DocPerm", 
+  "submit": 0, 
+  "write": 1, 
   "role": "All", 
+  "cancel": 0, 
   "permlevel": 2
  }, 
  {
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index 1844032..fcb939a 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -446,7 +446,7 @@
 					only_pending_fetched.append(item)
 		
 		# delete items with 0 qty
-		for item in item_qty:
+		for item in item_qty.keys():
 			if not item_qty[item][0]:
 				del item_qty[item]