Merge branch 'master' of github.com:webnotes/erpnext
diff --git a/hr/doctype/leave_application/leave_application.js b/hr/doctype/leave_application/leave_application.js
index 7f8948a..2715a6c 100755
--- a/hr/doctype/leave_application/leave_application.js
+++ b/hr/doctype/leave_application/leave_application.js
@@ -16,7 +16,6 @@
 
 cur_frm.add_fetch('employee','employee_name','employee_name');
 
-
 cur_frm.cscript.onload = function(doc, dt, dn) {
 	if(!doc.posting_date) 
 		set_multiple(dt,dn,{posting_date:get_today()});
@@ -127,4 +126,8 @@
 	}
 }
 
-cur_frm.fields_dict.employee.get_query = erpnext.utils.employee_query;
\ No newline at end of file
+cur_frm.fields_dict.employee.get_query = function() {
+	return {
+		query: "hr.doctype.leave_application.leave_application.query_for_permitted_employees"
+	};
+}
\ No newline at end of file
diff --git a/hr/doctype/leave_application/leave_application.py b/hr/doctype/leave_application/leave_application.py
index b9f9e5b..839c730 100755
--- a/hr/doctype/leave_application/leave_application.py
+++ b/hr/doctype/leave_application/leave_application.py
@@ -330,3 +330,20 @@
 				"title": _("Holiday") + ": " + cstr(holiday.description),
 				"name": holiday.name
 			})
+
+@webnotes.whitelist()
+def query_for_permitted_employees(doctype, txt, searchfield, start, page_len, filters):
+	txt = cstr(txt) + "%"
+	
+	return webnotes.conn.sql("""select name, employee_name from `tabEmployee` emp
+		where status = 'Active' and docstatus < 2 and
+		(`%s` like %s or employee_name like %s) and
+		(exists(select ela.name from `tabEmployee Leave Approver` ela
+				where ela.parent=emp.name and ela.leave_approver=%s) or 
+			not exists(select ela.name from `tabEmployee Leave Approver` ela where ela.parent=emp.name)
+			or user_id = %s)
+		order by
+		case when name like %s then 0 else 1 end,
+		case when employee_name like %s then 0 else 1 end,
+		name limit %s, %s""" % tuple([searchfield] + ["%s"]*8), 
+		(txt, txt, webnotes.session.user, webnotes.session.user, txt, txt, start, page_len), debug=1)