Merge branch 'responsive' of github.com:webnotes/erpnext into responsive
diff --git a/accounts/doctype/account/account.js b/accounts/doctype/account/account.js
index c12c2d6..44f7abd 100644
--- a/accounts/doctype/account/account.js
+++ b/accounts/doctype/account/account.js
@@ -132,7 +132,9 @@
 
 cur_frm.fields_dict['parent_account'].get_query = function(doc) {
 	return {
-		query: "accounts.doctype.account.account.get_parent_account",
-		filters: { "company": doc.company}
+		filters: {
+			"group_or_ledger": "Group", 
+			"company": doc.company
+		}
 	}
-}
+}
\ No newline at end of file
diff --git a/accounts/doctype/c_form/c_form.js b/accounts/doctype/c_form/c_form.js
index d8c7d81..35656e9 100644
--- a/accounts/doctype/c_form/c_form.js
+++ b/accounts/doctype/c_form/c_form.js
@@ -18,10 +18,12 @@
 // -----------------------------
 cur_frm.fields_dict.invoice_details.grid.get_field("invoice_no").get_query = function(doc) {
 	return {
-		query: "accounts.doctype.c_form.c_form.get_invoice_nos",
 		filters: {
-			customer: doc.customer,
-			company: doc.company
+			"docstatus": 1, 
+			"customer": doc.customer,
+			"company": doc.company,
+			"c_form_applicable": 'Yes',
+			"c_form_no": ''
 		}
 	}
 }
diff --git a/accounts/doctype/cost_center/cost_center.js b/accounts/doctype/cost_center/cost_center.js
index 4e2b8de..d273e53 100644
--- a/accounts/doctype/cost_center/cost_center.js
+++ b/accounts/doctype/cost_center/cost_center.js
@@ -36,11 +36,25 @@
 //Account filtering for cost center
 cur_frm.fields_dict['budget_details'].grid.get_field('account').get_query = function(doc) {
 	var mydoc = locals[this.doctype][this.docname];
-	return 'SELECT DISTINCT `tabAccount`.`name`,`tabAccount`.debit_or_credit,`tabAccount`.group_or_ledger FROM `tabAccount` WHERE `tabAccount`.`company` = "' + doc.company + '" AND `tabAccount`.docstatus != 2 AND `tabAccount`.`is_pl_account` = "Yes" AND `tabAccount`.debit_or_credit = "Debit" AND `tabAccount`.`group_or_ledger` != "Group" AND `tabAccount`.`group_or_ledger` is not NULL AND `tabAccount`.`name` LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50';
+	return{
+		filters:[
+			['Account', 'company', '=', doc.company_name],
+			['Account', 'is_pl_account', '=', 'Yes'],
+			['Account', 'debit_or_credit', '=', 'Debit'],
+			['Account', 'group_or_ledger', '!=', 'Group'],
+			['Account', 'group_or_ledger', 'is not', 'NULL']
+		]
 	}
+}
 
 cur_frm.fields_dict['parent_cost_center'].get_query = function(doc){
-	return 'SELECT DISTINCT `tabCost Center`.name FROM `tabCost Center` WHERE `tabCost Center`.group_or_ledger="Group" AND `tabCost Center`.docstatus != 2 AND `tabCost Center`.company="'+ doc.company+'" AND `tabCost Center`.company is not NULL AND `tabCost Center`.name LIKE "%s" ORDER BY `tabCost Center`.name LIMIT 50';
+	return{
+		filters:[			
+			['Cost Center', 'group_or_ledger', '=', 'Group'],
+			['Cost Center', 'company', '=', doc.company_name],
+			['Cost Center', 'company_name', 'is not', 'NULL']
+		]
+	}
 }
 
 //parent cost center
diff --git a/accounts/doctype/journal_voucher/journal_voucher.js b/accounts/doctype/journal_voucher/journal_voucher.js
index 53c8764..ea077981 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.js
+++ b/accounts/doctype/journal_voucher/journal_voucher.js
@@ -196,24 +196,32 @@
 
 cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc) {
 	return {
-		query: "accounts.utils.get_cost_center_list",
-		filters: { company: doc.company}
+		filters: { 
+			'company_name': doc.company,
+			'group_or_ledger': 'Ledger'
+		}
 	}
 }
 
 cur_frm.fields_dict['entries'].grid.get_field('against_voucher').get_query = function(doc) {	
 	var d = locals[this.doctype][this.docname];
 	return {
-		query: "accounts.doctype.journal_voucher.journal_voucher.get_against_purchase_invoice",
-		filters: { account: d.account }
+		filters: [
+			['Purchase Invoice', 'credit_to', '=', d.account],
+			['Purchase Invoice', 'docstatus', '=', 1],
+			['Purchase Invoice', 'outstanding_amount', '>', 0]
+		]
 	}
 }
 
 cur_frm.fields_dict['entries'].grid.get_field('against_invoice').get_query = function(doc) {
 	var d = locals[this.doctype][this.docname];
 	return {
-		query: "accounts.doctype.journal_voucher.journal_voucher.get_against_sales_invoice",
-		filters: { account: d.account }
+		filters: [
+			['Sales Invoice', 'debit_to', '=', d.account],
+			['Sales Invoice', 'docstatus', '=', 1],
+			['Sales Invoice', 'outstanding_amount', '>', 0]
+		]
 	}
 }
 
diff --git a/accounts/doctype/mode_of_payment/mode_of_payment.js b/accounts/doctype/mode_of_payment/mode_of_payment.js
index 85b2ab1..e3625e6 100644
--- a/accounts/doctype/mode_of_payment/mode_of_payment.js
+++ b/accounts/doctype/mode_of_payment/mode_of_payment.js
@@ -15,8 +15,11 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 cur_frm.set_query("default_account", function(doc) {
-	return erpnext.queries.account({
-		account_type: "Bank or Cash",
-		company: doc.company
-	});
+	return{
+		query: "controllers.queries.account_query",
+		filters: {
+			'account_type': "Bank or Cash",
+			'company': doc.company
+		}
+	}
 });
\ No newline at end of file
diff --git a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.js b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.js
index ac7d9d2..ad0c1d0 100644
--- a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.js
+++ b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.js
@@ -36,25 +36,12 @@
 	// TO-do: check for pos, it should not come
 	if (!doc.account) msgprint("Please select Account first");
 	else {
-		return repl("select gle.voucher_no, gle.posting_date, gle.%(account_type)s \
-		    from `tabGL Entry` gle \
-		    where gle.account = '%(acc)s' \
-		    and gle.voucher_type = '%(dt)s' \
-			and gle.voucher_no like '%s' \
-		    and ifnull(gle.is_cancelled, 'No') = 'No' \
-		    and (ifnull(gle.against_voucher, '') = '' \
-		        or ifnull(gle.against_voucher, '') = gle.voucher_no ) \
-			and ifnull(gle.%(account_type)s, 0) > 0 \
-		    and (select ifnull(abs(sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))), 0) \
-				from `tabGL Entry` \
-		        where against_voucher_type = '%(dt)s' \
-		        and against_voucher = gle.voucher_no \
-		        and voucher_no != gle.voucher_no \
-				and account = gle.account \
-		        and ifnull(is_cancelled, 'No') = 'No') != \
-		        abs(ifnull(gle.debit, 0) - ifnull(gle.credit, 0)) \
-		    ORDER BY gle.posting_date DESC, gle.voucher_no DESC LIMIT 50", 
-			{dt:doc.voucher_type, acc:doc.account, account_type: doc.account_type});
+		query: "accounts.doctype.payment_to_invoice_matching_tool.payment_to_invoice_matching_tool.gl_entry_details",
+		filters: {
+			"dt": doc.voucher_type,
+			"acc": doc.account,
+			"account_type": doc.account_type 
+		}		
 	}
 }
 
diff --git a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
index ba4dec3..07a97d8 100644
--- a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
+++ b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
@@ -139,3 +139,30 @@
 			msgprint("Successfully allocated.")
 		else:
 			msgprint("No amount allocated.", raise_exception=1)
+
+def gl_entry_details(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+	
+	return webnotes.conn.sql("""select gle.voucher_no, gle.posting_date, 
+				gle.%(account_type)s from `tabGL Entry` gle
+			    where gle.account = '%(acc)s' 
+			    	and gle.voucher_type = '%(dt)s'
+					and gle.voucher_no like '%(txt)s'  
+					and ifnull(gle.is_cancelled, 'No') = 'No'
+			    	and (ifnull(gle.against_voucher, '') = '' 
+			    		or ifnull(gle.against_voucher, '') = gle.voucher_no ) 
+					and ifnull(gle.%(account_type)s, 0) > 0 
+			   		and (select ifnull(abs(sum(ifnull(debit, 0)) 
+			   				- sum(ifnull(credit, 0))), 0) 
+						from `tabGL Entry` 
+			        	where against_voucher_type = '%(dt)s' 
+			        		and against_voucher = gle.voucher_no 
+			        	and voucher_no != gle.voucher_no 
+			        	and ifnull(is_cancelled, 'No') = 'No') 
+							!= abs(ifnull(gle.debit, 0) - ifnull(gle.credit, 0)
+						) 
+					%(mcond)s
+			    ORDER BY gle.posting_date desc, gle.voucher_no desc 
+			    limit %(start)s, %(page_len)s""" %  {dt:filters["dt"], acc:filters["acc"], 
+			    account_type: filters['account_type'], 'mcond':get_match_cond(doctype, searchfield)
+			    'txt': "%%%s%%" % txt,"start": start, "page_len": page_len})
\ No newline at end of file
diff --git a/accounts/doctype/period_closing_voucher/period_closing_voucher.js b/accounts/doctype/period_closing_voucher/period_closing_voucher.js
index 830092b..fd45841 100644
--- a/accounts/doctype/period_closing_voucher/period_closing_voucher.js
+++ b/accounts/doctype/period_closing_voucher/period_closing_voucher.js
@@ -23,5 +23,13 @@
 
 // ***************** 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 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';
+	return{
+		filters:{
+			'is_pl_account': "No",
+			"debit_or_credit": "Credit",
+			"company": doc.company,
+			"freeze_account": "No",
+			"group_or_ledger": "Ledger"
+		}
+	}	
 }
diff --git a/accounts/doctype/pos_setting/pos_setting.js b/accounts/doctype/pos_setting/pos_setting.js
index 1648bad..991c8da 100755
--- a/accounts/doctype/pos_setting/pos_setting.js
+++ b/accounts/doctype/pos_setting/pos_setting.js
@@ -25,43 +25,72 @@
 //cash bank account
 //------------------------------------
 cur_frm.fields_dict['cash_bank_account'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.is_pl_account = "No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters:{
+			'debit_or_credit': "Debit",
+			'is_pl_account': "No",
+			'group_or_ledger': "Ledger",
+			'company': doc.company
+		}
+	}	
 }
 
 // Income Account 
 // --------------------------------
 cur_frm.fields_dict['income_account'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.account_type ="Income Account" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters:{
+			'debit_or_credit': "Credit",
+			'group_or_ledger': "Ledger",
+			'company': doc.company,
+			'account_type': "Income Account"
+		}
+	}	
 }
 
 
 // Cost Center 
 // -----------------------------
 cur_frm.fields_dict['cost_center'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY	`tabCost Center`.`name` ASC LIMIT 50';
+	return{
+		filters:{
+			'company_name': doc.company,
+			'group_or_ledger': "Ledger"
+		}
+	}	
 }
 
 //get query select Territory
 //=================================================================
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters:{
+			'is_group': "No"
+		}
+	}	
 }
 
 
 // ------------------ Get Print Heading ------------------------------------
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['Print Heading', 'docstatus', '!=', 2]
+		]	
+	}	
 }
 
 cur_frm.fields_dict["expense_account"].get_query = function(doc) {
 	return {
-		"query": "accounts.utils.get_account_list", 
-		"filters": {
+		filters: {
 			"is_pl_account": "Yes",
 			"debit_or_credit": "Debit",
-			"company": doc.company
+			"company": doc.company,
+			"group_or_ledger": "Ledger"
 		}
 	}
 }
 
-cur_frm.fields_dict.user.get_query = erpnext.utils.profile_query;
\ No newline at end of file
+cur_frm.fields_dict.user.get_query = function(doc,cdt,cdn) {
+	return{	query:"controllers.queries.profile_query"}
+}
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.js b/accounts/doctype/purchase_invoice/purchase_invoice.js
index 512e036..efe0c2a 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -152,30 +152,55 @@
 
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+		filters:{'supplier':  doc.supplier}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+		filters:{'supplier':  doc.supplier}
+	}	
 }
 
 cur_frm.fields_dict['entries'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-	return erpnext.queries.item({
-		'ifnull(tabItem.is_purchase_item, "No")': 'Yes'
-	})
+	return {
+		query:"controllers.queries.item_query",
+		filters:{
+			'is_purchase_item': 'Yes'	
+		}
+	}	 
 }
 
 cur_frm.fields_dict['credit_to'].get_query = function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.is_pl_account="No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters:{
+			'debit_or_credit': 'Credit',
+			'is_pl_account': 'No',
+			'group_or_ledger': 'Ledger',
+			'company': doc.company
+		}
+	}	
 }
 
 // Get Print Heading
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+return{
+		filters:[
+			['Print Heading', 'docstatus', '!=', 2]
+		]
+	}	
 }
 
 cur_frm.fields_dict['entries'].grid.get_field("expense_head").get_query = function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE (tabAccount.debit_or_credit="Debit" OR tabAccount.account_type = "Expense Account") AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"';
+	return{
+		filters:{
+			'debit_or_credit':'Debit',
+			'account_type': 'Expense Account',
+			'group_or_ledger': 'Ledger',
+			'company': doc.company
+		}
+	}	
 }
 cur_frm.cscript.expense_head = function(doc, cdt, cdn){
 	var d = locals[cdt][cdn];
@@ -190,8 +215,11 @@
 
 cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc) {
 	return {
-		query: "accounts.utils.get_cost_center_list",
-		filters: { company: doc.company}
+		filters: { 
+			'company_name': doc.company,
+			'group_or_ledger': 'Ledger'
+		}
+
 	}
 }
 
@@ -232,9 +260,11 @@
 }
 
 cur_frm.fields_dict['entries'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['Project', 'status', 'not in', 'Completed, Cancelled']
+		]
+	}	
 }
 
 
diff --git a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
index a147ac1..c9f78fb 100644
--- a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
+++ b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js
@@ -127,18 +127,28 @@
   refresh_field('row_id',d.name,'purchase_tax_details');
 }
 
-/*---------------------- Get rate if account_head has account_type as TAX or CHARGEABLE-------------------------------------*/
-
-cur_frm.fields_dict['purchase_tax_details'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
-  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND (tabAccount.account_type in ("Tax", "Chargeable", "Expense Account") or (tabAccount.is_pl_account = "Yes" and tabAccount.debit_or_credit = "Debit")) AND tabAccount.company = "' + doc.company + '" AND  tabAccount.name LIKE "%s"'
-}
-
+cur_frm.set_query("account_head", "purchase_tax_details", function() {
+  return {
+    filters: [
+      ["Account", "group_or_ledger", "=", "Ledger"],
+      ["Account", "docstatus", "!=", 2],
+      ["Account", "account_type", "in", "Tax, Chargeable, Expense Account"],
+      ["Account", "is_pl_account", "=", "Yes"],
+      ["Account", "debit_or_credit", "=", "Debit"],
+      ["Account", "company", "=", doc.company]
+    ]
+  }
+});
 
 cur_frm.fields_dict['purchase_tax_details'].grid.get_field("cost_center").get_query = function(doc) {
-	return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY	`tabCost Center`.`name` ASC LIMIT 50';
+  return {
+    filters: {
+      'company_name': doc.company,
+      'group_or_ledger': "Ledger"
+    }
+  }
 }
 
-
 cur_frm.cscript.account_head = function(doc, cdt, cdn) {
   var d = locals[cdt][cdn];
   if(!d.charge_type && d.account_head){
diff --git a/accounts/doctype/sales_invoice/sales_invoice.js b/accounts/doctype/sales_invoice/sales_invoice.js
index c7d7d25..70bf03b 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/accounts/doctype/sales_invoice/sales_invoice.js
@@ -249,55 +249,84 @@
 }
 
 cur_frm.fields_dict.debit_to.get_query = function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.is_pl_account = "No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters: {
+			'debit_or_credit': 'Debit',
+			'is_pl_account': 'No',
+			'group_or_ledger': 'Ledger',
+			'company': doc.company
+		}
+	}
 }
 
 cur_frm.fields_dict.cash_bank_account.get_query = function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.is_pl_account = "No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters: {
+			'debit_or_credit': 'Debit',
+			'is_pl_account': 'No',
+			'group_or_ledger': 'Ledger',
+			'company': doc.company
+		}
+	}	
 }
 
 cur_frm.fields_dict.write_off_account.get_query = function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.is_pl_account = "Yes" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
+	return{
+		filters:{
+			'debit_or_credit': 'Debit',
+			'is_pl_account': 'Yes',
+			'group_or_ledger': 'Ledger',
+			'company': doc.company
+		}
+	}
 }
 
 // Write off cost center
 //-----------------------
 cur_frm.fields_dict.write_off_cost_center.get_query = function(doc) {
-	return 'SELECT `tabCost Center`.name FROM `tabCost Center` WHERE `tabCost Center`.group_or_ledger="Ledger" AND `tabCost Center`.docstatus!=2 AND `tabCost Center`.company="'+doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s"'
+	return{
+		filters:{
+			'group_or_ledger': 'Ledger',
+			'company_name': doc.company
+		}
+	}	
 }
 
 //project name
 //--------------------------
 cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
-	var cond = '';
-	if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
-	return repl('SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND %(cond)s `tabProject`.name LIKE "%s" \
-		ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
+	return{
+		query: "controllers.queries.get_project_name",
+		filters: {'customer': doc.customer}
+	}	
 }
 
 //Territory
 //-----------------------------
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters: {'is_group': 'NO'}
+	}	
 }
 
 // Income Account in Details Table
 // --------------------------------
 cur_frm.set_query("income_account", "entries", function(doc) {
-	return 'SELECT tabAccount.name FROM tabAccount WHERE (tabAccount.debit_or_credit="Credit" OR tabAccount.account_type = "Income Account") AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus!=2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"';	
-})
+	return{
+		query: "accounts.doctype.sales_invoice.sales_invoice.get_income_account",
+		filters: {'company': doc.company}
+	}
+});
 
 // expense account
 if (sys_defaults.auto_inventory_accounting) {
 	cur_frm.fields_dict['entries'].grid.get_field('expense_account').get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_account_list", 
-			"filters": {
-				"is_pl_account": "Yes",
-				"debit_or_credit": "Debit",
-				"company": doc.company
+			filters: {
+				'is_pl_account': 'Yes',
+				'debit_or_credit': 'Debit',
+				'company': doc.company,
+				'group_or_ledger': 'Ledger'
 			}
 		}
 	}
@@ -307,15 +336,22 @@
 //----------------------------
 cur_frm.fields_dict['entries'].grid.get_field('warehouse').get_query= function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
-	return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50";
+	return{
+		filters:[
+			['Bin', 'item_code', '=', d.item_code],
+			['Bin', 'actual_qty', '>', 0]
+		]
+	}	
 }
 
 // Cost Center in Details Table
 // -----------------------------
 cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc) {
 	return {
-		query: "accounts.utils.get_cost_center_list",
-		filters: { company: doc.company}
+		filters: { 
+			'company': doc.company,
+			'group_or_ledger': 'Ledger'
+		}	
 	}
 }
 
diff --git a/accounts/doctype/sales_invoice/sales_invoice.py b/accounts/doctype/sales_invoice/sales_invoice.py
index e0147b1..e42cb73 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/accounts/doctype/sales_invoice/sales_invoice.py
@@ -984,3 +984,16 @@
 	return {
 		"cash_bank_account": val
 	}
+
+def get_income_account(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+
+	return webnotes.conn.sql("""select tabAccount.name from `tabAccount` 
+			where (tabAccount.debit_or_credit="Credit" 
+					or tabAccount.account_type = "Income Account") 
+				and tabAccount.group_or_ledger="Ledger" 
+				and tabAccount.docstatus!=2 
+				and tabAccount.company = '%(company)s' 
+				and tabAccount.%(key)s LIKE '%(txt)s'
+				%(mcond)s""" % {'company': filters['company'], 'key': searchfield, 
+			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield)})
\ No newline at end of file
diff --git a/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js b/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js
index 9f4cb08..9ec574e 100644
--- a/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js
+++ b/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js
@@ -137,11 +137,20 @@
 /*---------------------- Get rate if account_head has account_type as TAX or CHARGEABLE-------------------------------------*/
 
 cur_frm.fields_dict['other_charges'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
-  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.account_type in ("Tax", "Chargeable", "Income Account") AND tabAccount.company = "'+doc.company+'" AND  tabAccount.name LIKE "%s"'
+  return{
+    filters:[
+      ['Account', 'group_or_ledger', '=', 'Ledger'],
+      ['Account', 'account_type', 'in', 'Tax, Chargeable, Income Account'],
+      ['Account', 'company', '=', doc.company]
+    ]
+  }  
 }
 
 cur_frm.fields_dict['other_charges'].grid.get_field("cost_center").get_query = function(doc) {
-	return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY	`tabCost Center`.`name` ASC LIMIT 50';
+  return{
+    'company_name': doc.company,
+    'group_or_ledger': "Ledger"
+  }	
 }
 
 
diff --git a/buying/doctype/purchase_common/purchase_common.js b/buying/doctype/purchase_common/purchase_common.js
index 8f8893f..ada4beb 100644
--- a/buying/doctype/purchase_common/purchase_common.js
+++ b/buying/doctype/purchase_common/purchase_common.js
@@ -28,27 +28,37 @@
 		
 		if(this.frm.fields_dict.price_list_name) {
 			this.frm.set_query("price_list_name", function() {
-				return repl("select name, currency from `tabPrice List` \
-					where buying_or_selling = 'Buying' and name like \"%s%%\"");
+				return{
+					filters: { 'buying_or_selling': "Buying" }
+				}
 			});
 			
 			this.frm.set_query("price_list_currency", function() {
-				return repl("select distinct ref_currency from `tabItem Price` \
-					where price_list_name=\"%(price_list_name)s\" and buying_or_selling = 'Buying' \
-					and ref_currency like \"%s%%\"", 
-					{price_list_name: me.frm.doc.price_list_name});
+				return{
+					filters: {
+						'price_list_name': me.frm.doc.price_list_name,
+						'buying_or_selling': "Buying"
+					}					
+				}
 			});
 		}
 		
 		if(this.frm.fields_dict.supplier) {
-			this.frm.set_query("supplier", erpnext.utils.supplier_query);
+			this.frm.set_query("supplier", function() {
+				return{	query:"controllers.queries.supplier_query" }});
 		}
 		
 		this.frm.set_query("item_code", this.frm.cscript.fname, function() {
 			if(me.frm.doc.is_subcontracted == "Yes") {
-				return erpnext.queries.item({'ifnull(tabItem.is_sub_contracted_item, "No")': "Yes"});
+				 return{
+					query:"controllers.queries.item_query",
+					filters:{ 'is_sub_contracted_item': 'Yes' }
+				}
 			} else {
-				return erpnext.queries.item({'ifnull(tabItem.is_purchase_item, "No")': "Yes"});
+				return{
+					query: "controllers.queries.item_query",
+					filters: { 'is_purchase_item': 'Yes' }
+				}				
 			}
 		});
 	},
diff --git a/buying/doctype/purchase_order/purchase_order.js b/buying/doctype/purchase_order/purchase_order.js
index b378a40..bccd4a9 100644
--- a/buying/doctype/purchase_order/purchase_order.js
+++ b/buying/doctype/purchase_order/purchase_order.js
@@ -110,17 +110,23 @@
 }
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return {
+		filters: {'supplier': doc.supplier}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return {
+		filters: {'supplier': doc.supplier}
+	}
 }
 
 cur_frm.fields_dict['po_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return {
+		filters:[
+			['Project', 'status', 'not in', 'Completed, Cancelled']
+		]
+	}
 }
 
 cur_frm.cscript.get_last_purchase_rate = function(doc, cdt, cdn){
diff --git a/buying/doctype/quality_inspection/quality_inspection.js b/buying/doctype/quality_inspection/quality_inspection.js
index 2dbb285..d40d81a 100644
--- a/buying/doctype/quality_inspection/quality_inspection.js
+++ b/buying/doctype/quality_inspection/quality_inspection.js
@@ -43,18 +43,26 @@
 
 // item code based on GRN/DN
 cur_frm.fields_dict['item_code'].get_query = function(doc, cdt, cdn) {
-	if (doc.purchase_receipt_no)
-		return 'SELECT item_code, item_name, description FROM `tabPurchase Receipt Item` WHERE parent = "'+ doc.purchase_receipt_no +'" and docstatus != 2 AND item_code LIKE "%s" ORDER BY item_code ASC LIMIT 50';
-	else if (doc.delivery_note_no) 
-		return 'SELECT item_code, item_name, description FROM `tabDelivery Note Item` WHERE parent = "'+ doc.delivery_note_no +'" and docstatus != 2 AND item_code LIKE "%s" ORDER BY item_code ASC LIMIT 50';
-	else
-		return 'SELECT name, item_name, description FROM tabItem WHERE docstatus != 2 AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+	var filter = {};
+	if (doc.purchase_receipt_no) filter['parent'] = doc.purchase_receipt_no;
+		
+	else if (doc.delivery_note_no) filter['parent'] =  doc.delivery_note_no;
+
+	return{
+		filters: filter
+	}
 }
 
 // Serial No based on item_code
 cur_frm.fields_dict['item_serial_no'].get_query = function(doc, cdt, cdn) {
+	var filter = {};
 	if (doc.item_code)
-		return 'SELECT name, item_code, warehouse FROM `tabSerial No` WHERE docstatus != 2 AND item_code = "' + doc.item_code +'" AND status = "In Store" AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+		filter:{
+			'item_code': doc.item_code,
+			'status': "In Store"
+		}
 	else
-		return 'SELECT name, item_code, warehouse FROM `tabSerial No` WHERE docstatus != 2 AND status = "In Store" AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
-}
+		filter: { 'status': "In Store" }
+	
+	return { filters: filter }
+}
\ No newline at end of file
diff --git a/buying/doctype/supplier_quotation/supplier_quotation.js b/buying/doctype/supplier_quotation/supplier_quotation.js
index ef688ec..722ac00 100644
--- a/buying/doctype/supplier_quotation/supplier_quotation.js
+++ b/buying/doctype/supplier_quotation/supplier_quotation.js
@@ -65,10 +65,11 @@
 
 cur_frm.fields_dict['quotation_items'].grid.get_field('project_name').get_query = 
 	function(doc, cdt, cdn) {
-		return "select `tabProject`.name from `tabProject` \
-			where `tabProject`.status not in (\"Completed\", \"Cancelled\") \
-			and `tabProject`.name like \"%s\" \
-			order by `tabProject`.name ASC LIMIT 50";
+		return{
+			filters:[
+				['Project', 'status', 'not in', 'Completed, Cancelled']
+			]
+		}
 	}
 
 cur_frm.cscript.supplier_address = function(doc, dt, dn) {
@@ -80,12 +81,13 @@
 cur_frm.cscript.contact_person = cur_frm.cscript.supplier_address;
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-	return "SELECT name, address_line1, city FROM tabAddress WHERE supplier = \"" + doc.supplier
-		+ "\" AND docstatus != 2 AND name LIKE \"%s\" ORDER BY name ASC LIMIT 50";
+	return {
+		filters:{'supplier': doc.supplier}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return "SELECT name, CONCAT(first_name, \" \", ifnull(last_name,\"\")) As FullName, \
-		department, designation FROM tabContact WHERE supplier = \"" + doc.supplier 
-		+"\" AND docstatus != 2 AND name LIKE \"%s\" ORDER BY name ASC LIMIT 50";
-}
+	return {
+		filters:{'supplier': doc.supplier}
+	}
+}
\ No newline at end of file
diff --git a/controllers/queries.py b/controllers/queries.py
new file mode 100644
index 0000000..e397420
--- /dev/null
+++ b/controllers/queries.py
@@ -0,0 +1,221 @@
+ # 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/>.
+
+from __future__ import unicode_literals
+import webnotes
+from webnotes.utils import cstr
+
+def get_filters_cond(doctype, filters, conditions):
+	if filters:
+		if isinstance(filters, dict):
+			filters = filters.items()
+			flt = []
+			for f in filters:
+				if f[1][0] == '!':
+					flt.append([doctype, f[0], '!=', f[1][1:]])
+				else:
+					flt.append([doctype, f[0], '=', f[1]])
+		
+		from webnotes.widgets.reportview import build_filter_conditions
+		build_filter_conditions(flt, conditions)
+		cond = ' and ' + ' and '.join(conditions)	
+	else:
+		cond = ''
+	return cond
+
+def get_match_cond(doctype, searchfield = 'name'):
+	meta = webnotes.get_doctype(doctype)
+	from webnotes.widgets.search import get_std_fields_list
+	fields = get_std_fields_list(meta, searchfield)
+
+	from webnotes.widgets.reportview import build_match_conditions
+	cond = build_match_conditions(doctype, fields)
+
+	if cond:
+		cond = ' and ' + cond
+	else:
+		cond = ''
+	return cond
+
+ # searches for enabled profiles
+def profile_query(doctype, txt, searchfield, start, page_len, filters):
+	return webnotes.conn.sql("""select name, concat_ws(' ', first_name, middle_name, last_name) 
+		from `tabProfile` 
+		where ifnull(enabled, 0)=1 
+			and docstatus < 2 
+			and name not in ('Administrator', 'Guest') 
+			and (%(key)s like "%(txt)s" 
+				or concat_ws(' ', first_name, middle_name, last_name) like "%(txt)s") 
+			%(mcond)s
+		order by 
+			case when name like "%(txt)s" then 0 else 1 end, 
+			case when concat_ws(' ', first_name, middle_name, last_name) like "%(txt)s" 
+				then 0 else 1 end, 
+			name asc 
+		limit %(start)s, %(page_len)s""" % {'key': searchfield, 'txt': "%%%s%%" % txt,  
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+ # searches for active employees
+def employee_query(doctype, txt, searchfield, start, page_len, filters):
+	return webnotes.conn.sql("""select name, employee_name from `tabEmployee` 
+		where status = 'Active' 
+			and docstatus < 2 
+			and (%(key)s like "%(txt)s" 
+				or employee_name like "%(txt)s") 
+			%(mcond)s
+		order by 
+			case when name like "%(txt)s" then 0 else 1 end, 
+			case when employee_name like "%(txt)s" then 0 else 1 end, 
+			name 
+		limit %(start)s, %(page_len)s""" % {'key': searchfield, 'txt': "%%%s%%" % txt,  
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+ # searches for leads which are not converted
+def lead_query(doctype, txt, searchfield, start, page_len, filters): 
+	return webnotes.conn.sql("""select name, lead_name, company_name from `tabLead`
+		where docstatus < 2 
+			and ifnull(status, '') != 'Converted' 
+			and (%(key)s like "%(txt)s" 
+				or lead_name like "%(txt)s" 
+				or company_name like "%(txt)s") 
+			%(mcond)s
+		order by 
+			case when name like "%(txt)s" then 0 else 1 end, 
+			case when lead_name like "%(txt)s" then 0 else 1 end, 
+			case when company_name like "%(txt)s" then 0 else 1 end, 
+			lead_name asc 
+		limit %(start)s, %(page_len)s""" % {'key': searchfield, 'txt': "%%%s%%" % txt,  
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+ # searches for customer
+def customer_query(doctype, txt, searchfield, start, page_len, filters):
+	cust_master_name = webnotes.defaults.get_user_default("cust_master_name")
+
+	if cust_master_name == "Customer Name":
+		fields = ["name", "customer_group", "territory"]
+	else:
+		fields = ["name", "customer_name", "customer_group", "territory"]
+
+	fields = ", ".join(fields) 
+
+	return webnotes.conn.sql("""select %(field)s from `tabCustomer` 
+		where docstatus < 2 
+			and (%(key)s like "%(txt)s" 
+				or customer_name like "%(txt)s") 
+			%(mcond)s
+		order by 
+			case when name like "%(txt)s" then 0 else 1 end, 
+			case when customer_name like "%(txt)s" then 0 else 1 end, 
+			name, customer_name 
+		limit %(start)s, %(page_len)s""" % {'field': fields,'key': searchfield, 
+		'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 
+		'start': start, 'page_len': page_len})
+
+# searches for supplier
+def supplier_query(doctype, txt, searchfield, start, page_len, filters):
+	supp_master_name = webnotes.defaults.get_user_default("supp_master_name")
+	if supp_master_name == "Supplier Name":  
+		fields = ["name", "supplier_type"]
+	else: 
+		fields = ["name", "supplier_name", "supplier_type"]
+	fields = ", ".join(fields) 
+
+	return webnotes.conn.sql("""select %(field)s from `tabSupplier` 
+		where docstatus < 2 
+			and (%(key)s like "%(txt)s" 
+				or supplier_name like "%(txt)s") 
+			%(mcond)s
+		order by 
+			case when name like "%(txt)s" then 0 else 1 end, 
+			case when supplier_name like "%(txt)s" then 0 else 1 end, 
+			name, supplier_name 
+		limit %(start)s, %(page_len)s """ % {'field': fields,'key': searchfield, 
+		'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 'start': start, 
+		'page_len': page_len})
+
+def item_std(doctype, txt, searchfield, start, page_len, filters):
+	return webnotes.conn.sql("""select tabItem.name, 
+		if(length(tabItem.item_name) > 40, 
+			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name, 
+		if(length(tabItem.description) > 40, 
+			concat(substr(tabItem.description, 1, 40), "..."), description) as decription 
+		FROM tabItem 
+		WHERE tabItem.docstatus!=2 
+			and tabItem.%(key)s LIKE "%(txt)s" 
+			%(mcond)s 
+		limit %(start)s, %(page_len)s """ % {'key': searchfield, 'txt': "%%%s%%" % txt, 
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 
+		'page_len': page_len})
+
+def account_query(doctype, txt, searchfield, start, page_len, filters):
+	conditions = []
+	if not filters:
+		filters = {}
+	if not filters.group_or_ledger:
+		filters.group_or_ledger = "Ledger"
+	
+	return webnotes.conn.sql("""select tabAccount.name, tabAccount.parent_account, 
+		tabAccount.debit_or_credit from tabAccount 
+		where tabAccount.docstatus!=2 
+			and tabAccount.%(key)s LIKE "%(txt)s" 
+		 	%(fcond)s %(mcond)s 
+		limit %(start)s, %(page_len)s""" % {'key': searchfield, 
+		'txt': "%%%s%%" % txt, 'fcond': get_filters_cond(doctype, filters, conditions), 
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+def item_query(doctype, txt, searchfield, start, page_len, filters):
+	conditions = []
+
+	return webnotes.conn.sql("""select tabItem.name, 
+		if(length(tabItem.item_name) > 40, 
+			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name, 
+		if(length(tabItem.description) > 40, \
+			concat(substr(tabItem.description, 1, 40), "..."), description) as decription 
+		from tabItem 
+		where tabItem.docstatus!=2 
+			and (ifnull(`tabItem`.`end_of_life`,"") in ("", "0000-00-00") 
+				or `tabItem`.`end_of_life` > NOW()) 
+			and (tabItem.%(key)s LIKE "%(txt)s" 
+				or tabItem.item_name LIKE "%(txt)s")  
+			%(fcond)s %(mcond)s 
+		limit %(start)s,%(page_len)s """ %  {'key': searchfield, 'txt': "%%%s%%" % txt, 
+		'fcond': get_filters_cond(doctype, filters, conditions), 
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+def bom(doctype, txt, searchfield, start, page_len, filters):
+	conditions = []	
+
+	return webnotes.conn.sql("""select tabBOM.name, tabBOM.item 
+		from tabBOM 
+		where tabBOM.docstatus=1 
+			and tabBOM.is_active=1 
+			and tabBOM.%(key)s like "%s"  
+			%(fcond)s  %(mcond)s  
+		limit %(start)s, %(page_len)s """ %  {'key': searchfield, 'txt': "%%%s%%" % txt, 
+		'fcond': get_filters_cond(doctype, filters, conditions), 
+		'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len})
+
+def get_project_name(doctype, txt, searchfield, start, page_len, filters):
+	cond = ''
+	if filters['customer']:
+		cond = '(`tabProject`.customer = "' + filters['customer'] + '" or ifnull(`tabProject`.customer,"")="") and'
+	
+	return webnotes.conn.sql("""select `tabProject`.name from `tabProject` 
+		where `tabProject`.status not in ("Completed", "Cancelled") 
+			and %(cond)s `tabProject`.name like "%(txt)s" %(mcond)s 
+		order by `tabProject`.name asc 
+		limit %(start)s, %(page_len)s """ % {'cond': cond,'txt': "%%%s%%" % txt, 
+		'mcond':get_match_cond(doctype, searchfield),'start': start, 'page_len': page_len})
\ No newline at end of file
diff --git a/hr/doctype/appraisal/appraisal.js b/hr/doctype/appraisal/appraisal.js
index 601f3fc..2289064 100644
--- a/hr/doctype/appraisal/appraisal.js
+++ b/hr/doctype/appraisal/appraisal.js
@@ -83,4 +83,6 @@
 	refresh_field('total_score');
 }
 
-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(doc,cdt,cdn) {
+	return{	query:"controllers.queries.employee_query" }	
+}
\ No newline at end of file
diff --git a/hr/doctype/attendance/attendance.js b/hr/doctype/attendance/attendance.js
index 1749a6c..d1a66ce 100644
--- a/hr/doctype/attendance/attendance.js
+++ b/hr/doctype/attendance/attendance.js
@@ -21,4 +21,8 @@
 	if(doc.__islocal) cur_frm.set_value("att_date", get_today());
 }
 
-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(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.employee_query"
+	}	
+}
diff --git a/hr/doctype/employee/employee.js b/hr/doctype/employee/employee.js
index 4ef66a0..398d8f8 100644
--- a/hr/doctype/employee/employee.js
+++ b/hr/doctype/employee/employee.js
@@ -18,8 +18,10 @@
 erpnext.hr.EmployeeController = wn.ui.form.Controller.extend({
 	setup: function() {
 		this.setup_leave_approver_select();
-		this.frm.fields_dict.user_id.get_query = erpnext.utils.profile_query;
-		this.frm.fields_dict.reports_to.get_query = erpnext.utils.employee_query;
+		this.frm.fields_dict.user_id.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.profile_query"} }
+		this.frm.fields_dict.reports_to.get_query = function(doc,cdt,cdn) {	
+			return{	query:"controllers.queries.employee_query"}	}
 	},
 	
 	onload: function() {
diff --git a/hr/doctype/expense_claim/expense_claim.js b/hr/doctype/expense_claim/expense_claim.js
index 5b136d0..406b57a 100644
--- a/hr/doctype/expense_claim/expense_claim.js
+++ b/hr/doctype/expense_claim/expense_claim.js
@@ -35,7 +35,11 @@
 		}
 	});
 	
-	cur_frm.fields_dict.employee.get_query = erpnext.utils.employee_query;
+	cur_frm.fields_dict.employee.get_query = function(doc,cdt,cdn) {
+		return{
+			query:"controllers.queries.employee_query"
+		}	
+	}
 }
 
 cur_frm.cscript.clear_sanctioned = function(doc) {
diff --git a/hr/doctype/leave_allocation/leave_allocation.js b/hr/doctype/leave_allocation/leave_allocation.js
index a26d211..80445c1 100755
--- a/hr/doctype/leave_allocation/leave_allocation.js
+++ b/hr/doctype/leave_allocation/leave_allocation.js
@@ -79,4 +79,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(doc,cdt,cdn) {
+  return{
+    query:"controllers.queries.employee_query"
+  } 
+}
\ No newline at end of file
diff --git a/hr/doctype/salary_slip/salary_slip.js b/hr/doctype/salary_slip/salary_slip.js
index cfffc5f..f6853fc 100644
--- a/hr/doctype/salary_slip/salary_slip.js
+++ b/hr/doctype/salary_slip/salary_slip.js
@@ -134,4 +134,8 @@
 	calculate_all(doc, dt, dn);
 }
 
-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(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.employee_query"
+	}		
+}
diff --git a/hr/doctype/salary_structure/salary_structure.js b/hr/doctype/salary_structure/salary_structure.js
index 2979243..60c159d 100644
--- a/hr/doctype/salary_structure/salary_structure.js
+++ b/hr/doctype/salary_structure/salary_structure.js
@@ -72,4 +72,6 @@
   calculate_totals(doc, cdt, cdn);
 }
 
-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(doc,cdt,cdn) {
+  return{ query:"controllers.queries.employee_query" } 
+}
\ No newline at end of file
diff --git a/manufacturing/doctype/bom/bom.js b/manufacturing/doctype/bom/bom.js
index d14590c..acb770d 100644
--- a/manufacturing/doctype/bom/bom.js
+++ b/manufacturing/doctype/bom/bom.js
@@ -169,30 +169,37 @@
 
 
 cur_frm.fields_dict['item'].get_query = function(doc) {
-	return erpnext.queries.item({
-		'ifnull(tabItem.is_manufactured_item, "No")': 'Yes',
-	})
+ 	return{
+		query:"controllers.queries.item_query",
+		filters:{
+			'has_serial_no': 'Yes'	
+		}
+	}
 }
 
 cur_frm.fields_dict['project_name'].get_query = function(doc, dt, dn) {
-	return 'SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['Project', 'status', 'not in', 'Completed, Cancelled']
+		]
+	}
 }
 
 cur_frm.fields_dict['bom_materials'].grid.get_field('item_code').get_query = function(doc) {
-	return 'SELECT DISTINCT `tabItem`.`name`, `tabItem`.description FROM `tabItem` \
-		WHERE (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` = "0000-00-00" \
-			OR `tabItem`.`end_of_life` > NOW()) AND `tabItem`.`%(key)s` like "%s" \
-		ORDER BY `tabItem`.`name` LIMIT 50';
+	return{
+		query:"controllers.queries.item_query"
+	}
 }
 
 cur_frm.fields_dict['bom_materials'].grid.get_field('bom_no').get_query = function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
-	return 'SELECT DISTINCT `tabBOM`.`name`, `tabBOM`.`remarks` FROM `tabBOM` \
-		WHERE `tabBOM`.`item` = "' + d.item_code + '" AND `tabBOM`.`is_active` = 1 AND \
-		 	`tabBOM`.docstatus = 1 AND `tabBOM`.`name` like "%s" \
-		ORDER BY `tabBOM`.`name` LIMIT 50';
+	return{
+		filters:{
+			'item': d.item_code,
+			'is_active': 1,
+			'docstatus': 1
+		}
+	}	
 }
 
 cur_frm.cscript.validate = function(doc, dt, dn) {
diff --git a/manufacturing/doctype/bom/bom.py b/manufacturing/doctype/bom/bom.py
index 5f64148..00523c5 100644
--- a/manufacturing/doctype/bom/bom.py
+++ b/manufacturing/doctype/bom/bom.py
@@ -85,10 +85,10 @@
 			msgprint("Item %s does not exist in system" % item[0]['item_code'], raise_exception = 1)
 			
 	def set_bom_material_details(self):
-		for item in self.doclist.get({"parentfield": "bom_materials"}):			
-			ret = self.get_bom_material_detail({ "item_code": item.item_code, "bom_no": item.bom_no,
-				"qty": item.qty	})
-			
+		for item in self.doclist.get({"parentfield": "bom_materials"}):
+			ret = self.get_bom_material_detail({"item_code": item.item_code, "bom_no": item.bom_no, 
+				"qty": item.qty})
+
 			for r in ret:
 				if not item.fields.get(r):
 					item.fields[r] = ret[r]
@@ -100,7 +100,7 @@
 			args = webnotes.form_dict.get('args')
 			import json
 			args = json.loads(args)
-			
+
 		item = self.get_item_det(args['item_code'])
 		self.validate_rm_item(item)
 		
diff --git a/manufacturing/doctype/bom_replace_tool/bom_replace_tool.js b/manufacturing/doctype/bom_replace_tool/bom_replace_tool.js
index c98603c..bad03ac 100644
--- a/manufacturing/doctype/bom_replace_tool/bom_replace_tool.js
+++ b/manufacturing/doctype/bom_replace_tool/bom_replace_tool.js
@@ -20,10 +20,16 @@
 }
 
 cur_frm.set_query("current_bom", function(doc) {
-	return erpnext.queries.bom({name: "!" + doc.new_bom});
+	return{
+		query:"controllers.queries.bom",
+		filters: {name: "!" + doc.new_bom}
+	}
 });
 
 
 cur_frm.set_query("new_bom", function(doc) {
-	return erpnext.queries.bom({name: "!" + doc.current_bom});
+	return{
+		query:"controllers.queries.bom",
+		filters: {name: "!" + doc.current_bom}
+	}
 });
\ No newline at end of file
diff --git a/manufacturing/doctype/production_order/production_order.js b/manufacturing/doctype/production_order/production_order.js
index 77dce03..12f9490 100644
--- a/manufacturing/doctype/production_order/production_order.js
+++ b/manufacturing/doctype/production_order/production_order.js
@@ -101,18 +101,27 @@
 }
 
 cur_frm.fields_dict['production_item'].get_query = function(doc) {
-	 return 'SELECT DISTINCT `tabItem`.`name`, `tabItem`.`description` FROM `tabItem` WHERE (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` = "0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND `tabItem`.docstatus != 2 AND `tabItem`.is_pro_applicable = "Yes" AND `tabItem`.%(key)s LIKE "%s" ORDER BY `tabItem`.`name` LIMIT 50';
+	return {
+		filters:[
+			['Item', 'is_pro_applicable', '=', 'Yes']
+		]
+	}
 }
 
 cur_frm.fields_dict['project_name'].get_query = function(doc, dt, dn) {
-	return 'SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['Project', 'status', 'not in', 'Completed, Cancelled']
+		]
+	}	
 }
 
 
 cur_frm.set_query("bom_no", function(doc) {
 	if (doc.production_item) {
-		return erpnext.queries.bom({item: cstr(doc.production_item)});
+		return{
+			query:"controllers.queries.bom",
+			filters: {item: cstr(doc.production_item)}
+		}
 	} else msgprint(" Please enter Production Item first");
 });
\ No newline at end of file
diff --git a/manufacturing/doctype/production_planning_tool/production_planning_tool.js b/manufacturing/doctype/production_planning_tool/production_planning_tool.js
index 95b84b2..9158748 100644
--- a/manufacturing/doctype/production_planning_tool/production_planning_tool.js
+++ b/manufacturing/doctype/production_planning_tool/production_planning_tool.js
@@ -53,11 +53,18 @@
 cur_frm.fields_dict['pp_details'].grid.get_field('bom_no').get_query = function(doc) {
 	var d = locals[this.doctype][this.docname];
 	if (d.item_code) {
-		return erpnext.queries.bom({item: cstr(d.item_code)});
+		return {
+			query:"controllers.queries.bom",
+			filters:{'item': cstr(d.item_code)}
+		}
 	} else msgprint(" Please enter Item first");
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.customer_query"
+	}
+}
 
 cur_frm.fields_dict.pp_so_details.grid.get_field("customer").get_query =
-	erpnext.utils.customer_query;
\ No newline at end of file
+	cur_frm.fields_dict.customer.get_query;
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index 48e521d..114c6e0 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -20,6 +20,8 @@
 	"execute:webnotes.reload_doc('core', 'doctype', 'docperm') # 2013-04-07",
 	"execute:webnotes.reload_doc('core', 'doctype', 'report')",
 	"execute:webnotes.reload_doc('core', 'doctype', 'doctype') # 2013-07-08",
+	"execute:webnotes.reload_doc('core', 'doctype', 'page') # 2013-06-24",
+	"patches.mar_2012.so_rv_mapper_fix", 
 	"patches.mar_2012.clean_property_setter", 
 	"patches.april_2012.naming_series_patch", 
 	"patches.mar_2012.cleanup_control_panel", 
diff --git a/projects/doctype/project/project.js b/projects/doctype/project/project.js
index a6f32cb..9d04477 100644
--- a/projects/doctype/project/project.js
+++ b/projects/doctype/project/project.js
@@ -28,4 +28,8 @@
 	}
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.customer_query"
+	}
+}
\ No newline at end of file
diff --git a/projects/doctype/task/task.js b/projects/doctype/task/task.js
index 131b5fd..cb2c539 100644
--- a/projects/doctype/task/task.js
+++ b/projects/doctype/task/task.js
@@ -21,9 +21,9 @@
 erpnext.projects.Task = wn.ui.form.Controller.extend({
 	setup: function() {
 		this.frm.fields_dict.project.get_query = function() {
-			return "select name from `tabProject` \
-				where %(key)s like \"%s\" \
-				order by name asc limit 50";
+			return {
+				query: "projects.doctype.task.task.get_project"
+			}
 		};
 	},
 
diff --git a/projects/doctype/task/task.py b/projects/doctype/task/task.py
index 1df8547..0ea9eea 100644
--- a/projects/doctype/task/task.py
+++ b/projects/doctype/task/task.py
@@ -92,3 +92,13 @@
 		}, as_dict=True, update={"allDay": 0})
 
 	return data
+
+def get_project(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+	return webnotes.conn.sql(""" select name from `tabProject`
+			where %(key)s like "%(txt)s"
+				%(mcond)s
+			order by name 
+			limit %(start)s, %(page_len)s """ % {'key': searchfield, 
+			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield),
+			'start': start, 'page_len': page_len})
\ No newline at end of file
diff --git a/projects/doctype/time_log/time_log.js b/projects/doctype/time_log/time_log.js
index 22f9610..69ec304 100644
--- a/projects/doctype/time_log/time_log.js
+++ b/projects/doctype/time_log/time_log.js
@@ -2,8 +2,8 @@
 
 erpnext.projects.TimeLog = wn.ui.form.Controller.extend({
 	setup: function() {
-		this.frm.set_query("task", erpnext.queries.task);
-	}
-});
+		this.frm.set_query("task", function() {
+			return { query: "projects.utils.query_task" }
+		});
 
 cur_frm.cscript = new erpnext.projects.TimeLog({frm: cur_frm});
\ No newline at end of file
diff --git a/selling/doctype/customer/customer.js b/selling/doctype/customer/customer.js
index 914836c..cd530a2 100644
--- a/selling/doctype/customer/customer.js
+++ b/selling/doctype/customer/customer.js
@@ -122,8 +122,14 @@
 }
 
 cur_frm.fields_dict['customer_group'].get_query = function(doc,dt,dn) {
-	return 'SELECT `tabCustomer Group`.`name`, `tabCustomer Group`.`parent_customer_group` FROM `tabCustomer Group` WHERE `tabCustomer Group`.`is_group` = "No" AND `tabCustomer Group`.`docstatus`!= 2 AND `tabCustomer Group`.%(key)s LIKE "%s" ORDER BY	`tabCustomer Group`.`name` ASC LIMIT 50';
+	return{
+		filters:{'is_group': 'No'}
+	}	
 }
 
 
-cur_frm.fields_dict.lead_name.get_query = erpnext.utils.lead_query;
\ No newline at end of file
+cur_frm.fields_dict.lead_name.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.lead_query"
+	}
+}
\ No newline at end of file
diff --git a/selling/doctype/installation_note/installation_note.js b/selling/doctype/installation_note/installation_note.js
index 4fd8678..4cbd67d 100644
--- a/selling/doctype/installation_note/installation_note.js
+++ b/selling/doctype/installation_note/installation_note.js
@@ -62,16 +62,20 @@
 
 cur_frm.fields_dict['delivery_note_no'].get_query = function(doc) {
 	doc = locals[this.doctype][this.docname];
-	var cond = '';
-	if(doc.customer) {
-		cond = '`tabDelivery Note`.customer = "'+doc.customer+'" AND';
-	}
-	return repl('SELECT DISTINCT `tabDelivery Note`.name, `tabDelivery Note`.customer_name	FROM `tabDelivery Note`, `tabDelivery Note Item` WHERE `tabDelivery Note`.company = "%(company)s" AND `tabDelivery Note`.docstatus = 1 AND ifnull(`tabDelivery Note`.per_installed,0) < 99.99 AND %(cond)s `tabDelivery Note`.name LIKE "%s" ORDER BY `tabDelivery Note`.name DESC LIMIT 50', {company:doc.company, cond:cond});
+
+	var filter = {
+    	'company': doc.company,
+    	'docstatus': 1,
+    	'per_installed': 99.99
+  	};
+	if(doc.customer) filter['customer'] = doc.customer;
+  	return { filters: filter }
 }
 
-
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+  	return{
+ 		filters: { 'is_group': "No" }
+  	}	
 }
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
@@ -79,11 +83,19 @@
 }
 
 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{
+    	filters: { 'customer': doc.customer }
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+    	filters: { 'customer': doc.customer }
+	}
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.customer_query"
+	}
+}
\ No newline at end of file
diff --git a/selling/doctype/lead/lead.js b/selling/doctype/lead/lead.js
index 40cf454..a20b331 100644
--- a/selling/doctype/lead/lead.js
+++ b/selling/doctype/lead/lead.js
@@ -20,16 +20,19 @@
 wn.provide("erpnext");
 erpnext.LeadController = wn.ui.form.Controller.extend({
 	setup: function() {
-		this.frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
+		this.frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.customer_query" } }
 	},
 	
 	onload: function() {
 		if(cur_frm.fields_dict.lead_owner.df.options.match(/^Profile/)) {
-			cur_frm.fields_dict.lead_owner.get_query = erpnext.utils.profile_query;
+			cur_frm.fields_dict.lead_owner.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.profile_query" } }
 		}
 
 		if(cur_frm.fields_dict.contact_by.df.options.match(/^Profile/)) {
-			cur_frm.fields_dict.contact_by.get_query = erpnext.utils.profile_query;
+			cur_frm.fields_dict.contact_by.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.profile_query" } }
 		}
 
 		if(in_list(user_roles,'System Manager')) {
diff --git a/selling/doctype/opportunity/opportunity.js b/selling/doctype/opportunity/opportunity.js
index bc10c9b..b87fee1 100644
--- a/selling/doctype/opportunity/opportunity.js
+++ b/selling/doctype/opportunity/opportunity.js
@@ -109,7 +109,8 @@
 	}
 	
 	if(cur_frm.fields_dict.contact_by.df.options.match(/^Profile/)) {
-		cur_frm.fields_dict.contact_by.get_query = erpnext.utils.profile_query;
+		cur_frm.fields_dict.contact_by.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.profile_query" } }
 	}
 	
 	if(doc.customer && !doc.customer_name) cur_frm.cscript.customer(doc);
@@ -153,23 +154,23 @@
 }
 
 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';
+	return {
+		filters:{'customer':doc.customer}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
 	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';
+		filters:{'customer':doc.customer}
 	}
 }
 
 // lead
 cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
-	return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s"	ORDER BY	`tabLead`.`name` ASC LIMIT 50';
+	return {
+		query: "selling.doctype.opportunity.opportunity.get_lead"
+	}
 }
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
@@ -185,14 +186,17 @@
 }
 
 cur_frm.fields_dict['enquiry_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
-	if (doc.enquiry_type == 'Maintenance')
-	 	return erpnext.queries.item({
-			'ifnull(tabItem.is_service_item, "No")': 'Yes'
-		});
-	else 
- 		return erpnext.queries.item({
-			'ifnull(tabItem.is_sales_item, "No")': 'Yes'
-		});
+	if (doc.enquiry_type == 'Maintenance') {
+		return {
+			query:"controllers.queries.item_query",
+			filters:{ 'is_service_item': 'Yes' }
+		}
+	} else {
+		return {
+			query:"controllers.queries.item_query",
+			filters:{ 'is_sales_item': 'Yes' }
+		}		
+	}
 }
 
 cur_frm.cscript['Declare Opportunity Lost'] = function(){
@@ -229,8 +233,12 @@
 
 //get query select Territory
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';}
+	return{
+		filters:{'is_group': 'No'}
+	}	
 	
-cur_frm.fields_dict.lead.get_query = erpnext.utils.lead_query;
+cur_frm.fields_dict.lead.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.lead_query" } }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+				return { query:"controllers.queries.customer_query" } }
\ No newline at end of file
diff --git a/selling/doctype/opportunity/opportunity.py b/selling/doctype/opportunity/opportunity.py
index cced9ab..92d391b 100644
--- a/selling/doctype/opportunity/opportunity.py
+++ b/selling/doctype/opportunity/opportunity.py
@@ -202,4 +202,14 @@
 		}
 	}, target_doclist)
 		
-	return [d.fields for d in doclist]
\ No newline at end of file
+	return [d.fields for d in doclist]
+
+def get_lead(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+	return webnotes.conn.sql ("""select `tabLead`.name, `tabLead`.lead_name FROM `tabLead` 
+			where `tabLead`.%(key)s like "%(txt)s" 
+				%(mcond)s	
+			order by `tabLead`.`name` asc 
+			limit %(start)s, %(page_len)s """ % {'key': searchfield, 
+			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield),
+			'start': start, 'page_len': page_len})
\ No newline at end of file
diff --git a/selling/doctype/quotation/quotation.js b/selling/doctype/quotation/quotation.js
index 877f65c..0649f54 100644
--- a/selling/doctype/quotation/quotation.js
+++ b/selling/doctype/quotation/quotation.js
@@ -118,7 +118,8 @@
 	}),'', doc, dt, dn, 1);
 }
 
-cur_frm.fields_dict.lead.get_query = erpnext.utils.lead_query;
+cur_frm.fields_dict.lead.get_query = function(doc,cdt,cdn) {
+	return{	query:"controllers.queries.lead_query" } }
 
 cur_frm.cscript.lead = function(doc, cdt, cdn) {
 	if(doc.lead) {
@@ -186,45 +187,21 @@
 	if(doc.customer) {
 		var export_rate_field = wn.meta.get_docfield(cdt, 'export_rate', cdn);
 		var precision = (export_rate_field && export_rate_field.fieldtype) === 'Float' ? 6 : 2;
-		return repl("\
-			select \
-				item.name, \
-				( \
-					select concat('Last Quote @ ', q.currency, ' ', \
-						format(q_item.export_rate, %(precision)s)) \
-					from `tabQuotation` q, `tabQuotation Item` q_item \
-					where \
-						q.name = q_item.parent \
-						and q_item.item_code = item.name \
-						and q.docstatus = 1 \
-						and q.customer = \"%(cust)s\" \
-					order by q.transaction_date desc \
-					limit 1 \
-				) as quote_rate, \
-				( \
-					select concat('Last Sale @ ', si.currency, ' ', \
-						format(si_item.basic_rate, %(precision)s)) \
-					from `tabSales Invoice` si, `tabSales Invoice Item` si_item \
-					where \
-						si.name = si_item.parent \
-						and si_item.item_code = item.name \
-						and si.docstatus = 1 \
-						and si.customer = \"%(cust)s\" \
-					order by si.posting_date desc \
-					limit 1 \
-				) as sales_rate, \
-				item.item_name, item.description \
-			from `tabItem` item \
-			where \
-				item.%(key)s like \"%s\" \
-				%(cond)s \
-				limit 25", {
-					cust: doc.customer,
-					cond: cond,
-					precision: precision
-				});
+		return {
+			query: "selling.doctype.quotation.quotation.quotation_details",
+			filters:{
+				cust: doc.customer,
+				cond: cond,
+				precision: precision
+			}
+		}
 	} else {
-		return repl("SELECT name, item_name, description FROM `tabItem` item WHERE item.%(key)s LIKE '%s' %(cond)s ORDER BY item.item_code DESC LIMIT 50", {cond:cond});
+		return {
+			query: 'selling.doctype.quotation.quotation.quotation_details',
+			filters:{
+				cond: cond
+			}		
+		}	
 	}
 }
 
diff --git a/selling/doctype/quotation/quotation.py b/selling/doctype/quotation/quotation.py
index 3f0974e..5bf8510 100644
--- a/selling/doctype/quotation/quotation.py
+++ b/selling/doctype/quotation/quotation.py
@@ -259,4 +259,42 @@
 		
 	# postprocess: fetch shipping address, set missing values
 		
-	return [d.fields for d in doclist]
\ No newline at end of file
+	return [d.fields for d in doclist]
+
+def quotation_details(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+
+	if filters.has_key('cust') and filters.has_key('precision'):
+		return webnotes.conn.sql("""select 	item.name, 
+					(select concat('Last Quote @ ', q.currency, ' ', 
+								format(q_item.export_rate, %(precision)s))
+						from `tabQuotation` q, `tabQuotation Item` q_item 
+						where q.name = q_item.parent 
+							and q_item.item_code = item.name
+							and q.docstatus = 1	
+							and q.customer = "%(cust)s"
+						order by q.transaction_date desc 
+						limit 1) as quote_rate,
+					(select concat('Last Sale @ ', si.currency, ' ', 
+								format(si_item.basic_rate, %(precision)s)) 
+						from `tabSales Invoice` si, `tabSales Invoice Item` si_item 
+						where si.name = si_item.parent 
+							and si_item.item_code = item.name
+							and si.docstatus = 1 
+							and si.customer ="%(cust)s"
+						order by si.posting_date desc 
+						limit 1) as sales_rate,
+					item.item_name, item.description
+					from `tabItem` item 
+					where %(cond)s %(mcond)s 
+						and item.%(searchfield)s like '%(txt)s' 
+					order by item.name desc limit %(start)s, %(page_len)s """ % {'precision': filters["precision"], 
+					'cust': filters['cust'], 'cond': filters['cond'], 'searchfield': searchfield, 
+					'txt': "%%%s%%" % txt, 'mcond': get_match_cond(doctype, searchfield), 
+					'start': start, 'page_len': page_len})
+
+	else:
+		return webnotes.conn.sql(""" select name, item_name, description from `tabItem` item 
+			where %s %s and %s like %s order by name desc limit %s, %s""" % 
+		("%s", get_match_cond(doctype, searchfield), searchfield, "%s", "%s", "%s"), 
+		(filters["cond"], "%%%s%%" % txt, start, page_len))
\ No newline at end of file
diff --git a/selling/doctype/sales_bom/sales_bom.js b/selling/doctype/sales_bom/sales_bom.js
index b6ba779..7d79340 100644
--- a/selling/doctype/sales_bom/sales_bom.js
+++ b/selling/doctype/sales_bom/sales_bom.js
@@ -24,9 +24,9 @@
 }
 
 cur_frm.fields_dict.new_item_code.get_query = function() {
-	return 'select name, description from tabItem where is_stock_item="No" and is_sales_item="Yes"\
-		and name not in (select name from `tabSales BOM`)\
-		and `%(key)s` like "%s"'
+	return{
+		query: "selling.doctype.sales_bom.sales_bom.get_new_item_code"
+	}
 }
 cur_frm.fields_dict.new_item_code.query_description = 'Select Item where "Is Stock Item" is "No" \
 	and "Is Sales Item" is "Yes" and there is no other Sales BOM';
diff --git a/selling/doctype/sales_bom/sales_bom.py b/selling/doctype/sales_bom/sales_bom.py
index 03479eb..13f68aa 100644
--- a/selling/doctype/sales_bom/sales_bom.py
+++ b/selling/doctype/sales_bom/sales_bom.py
@@ -83,3 +83,13 @@
 			if l not in l2:
 				return 0
 		return 1
+
+def get_new_item_code(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+
+	return webnotes.conn.sql("""select name, description from tabItem 
+		where is_stock_item="No" and is_sales_item="Yes"
+		and name not in (select name from `tabSales BOM`) and %s like "%s" 
+		%s limit %s, %s""" % (searchfield, "%s", 
+		get_match_cond(doctype, searchfield),"%s", "%s"), 
+		("%%%s%%" % txt, start, page_len))
\ No newline at end of file
diff --git a/selling/doctype/sales_common/sales_common.js b/selling/doctype/sales_common/sales_common.js
index cf757a6..8d86950 100644
--- a/selling/doctype/sales_common/sales_common.js
+++ b/selling/doctype/sales_common/sales_common.js
@@ -36,32 +36,34 @@
 		}
 		
 		this.frm.set_query("customer_address", function() {
-			return 'SELECT name, address_line1, city FROM tabAddress \
-				WHERE customer = "'+ me.frm.doc.customer +'" AND docstatus != 2 AND \
-				%(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+			return {
+				filters: {'customer': me.frm.doc.customer }
+			}
 		});
 		
 		this.frm.set_query("contact_person", function() {
-			return 'SELECT name, CONCAT(first_name," ",ifnull(last_name,"")) As FullName, \
-				department, designation FROM tabContact WHERE customer = "'+ me.frm.doc.customer + 
-				'" AND docstatus != 2 AND %(key)s LIKE "%s" ORDER BY name ASC LIMIT 50';
+			return {
+				filters: {'customer': me.frm.doc.customer }
+			}
 		});
 		
 		if(this.frm.fields_dict.charge) {
 			this.frm.set_query("charge", function() {
-				return 'SELECT DISTINCT `tabSales Taxes and Charges Master`.name FROM \
-					`tabSales Taxes and Charges Master` \
-					WHERE `tabSales Taxes and Charges Master`.company = "' + me.frm.doc.company +
-					'" AND `tabSales Taxes and Charges Master`.company is not NULL \
-					AND `tabSales Taxes and Charges Master`.docstatus != 2 \
-					AND `tabSales Taxes and Charges Master`.%(key)s LIKE "%s" \
-					ORDER BY `tabSales Taxes and Charges Master`.name LIMIT 50';
+				return {
+					filters: [
+						['Sales Taxes and Charges Master', 'company', '=', me.frm.doc.company],
+						['Sales Taxes and Charges Master', 'company', 'is not', 'NULL'],
+						['Sales Taxes and Charges Master', 'docstatus', '!=', 2]
+					]
+				}
 			});
 		}
 		
-		this.frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
+		this.frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+			return{	query:"controllers.queries.customer_query" } }
 
-		this.frm.fields_dict.lead && this.frm.set_query("lead", erpnext.utils.lead_query);
+		this.frm.fields_dict.lead && this.frm.set_query("lead", function(doc,cdt,cdn) {
+			return{	query:"controllers.queries.lead_query" } });
 
 		if(!this.fname) {
 			return;
@@ -70,8 +72,10 @@
 		if(this.frm.fields_dict[this.fname].grid.get_field('item_code')) {
 			this.frm.set_query("item_code", this.fname, function() {
 				return me.frm.doc.order_type === "Maintenance" ?
-					erpnext.queries.item({'ifnull(tabItem.is_service_item, "No")': "Yes"}) :
-					erpnext.queries.item({'ifnull(tabItem.is_sales_item, "No")': "Yes"});
+					 	{ query:"controllers.queries.item_query",
+							filters:{'is_service_item': 'Yes'}}	:
+						{ query:"controllers.queries.item_query",
+							filters:{'is_sales_item': 'Yes'	}}	;
 			});
 		}
 		
@@ -82,18 +86,22 @@
 					wn.throw("Please enter Item Code to get batch no");
 				} else {
 					if(item.warehouse) {
-						return "select batch_no from `tabStock Ledger Entry` sle \
-							where item_code = '" + item.item_code + 
-							"' and warehouse = '" + item.warehouse +
-							"' and ifnull(is_cancelled, 'No') = 'No' and batch_no like '%s' \
-							and exists(select * from `tabBatch` where \
-							name = sle.batch_no and expiry_date >= '" + me.frm.doc.posting_date + 
-							"' and docstatus != 2) group by batch_no having sum(actual_qty) > 0 \
-							order by batch_no desc limit 50";
+						return {
+							query : "selling.doctype.sales_common.sales_common.get_batch_no",
+							filters: {
+								'item_code': item.item_code,
+								'warehouse': item.warehouse,
+								'posting_date': me.frm.doc.posting_date
+							}
+						}
 					} else {
-						return "SELECT name FROM tabBatch WHERE docstatus != 2 AND item = '" + 
-							item.item_code + "' and expiry_date >= '" + me.frm.doc.posting_date + 
-							"' AND name like '%s' ORDER BY name DESC LIMIT 50";
+						return{
+							query : "selling.doctype.sales_common.sales_common.get_batch_no",
+							filters: {
+								'item': item.item_code,
+								'posting_date': me.frm.doc.posting_date
+							}
+						}
 					}
 				}
 			});
diff --git a/selling/doctype/sales_common/sales_common.py b/selling/doctype/sales_common/sales_common.py
index f34ebf9..00825bb 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -365,3 +365,35 @@
 					dt = webnotes.conn.sql("select transaction_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname))
 				d.prevdoc_date = (dt and dt[0][0]) and dt[0][0].strftime('%Y-%m-%d') or ''
 
+def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+
+	if filters.has_key('warehouse'):
+		return webnotes.conn.sql("""select batch_no from `tabStock Ledger Entry` sle 
+				where item_code = '%(item_code)s' 
+					and warehouse = '%(warehouse)s' 
+					and ifnull(is_cancelled, 'No') = 'No' 
+					and batch_no like '%(txt)s' 
+					and exists(select * from `tabBatch` 
+							where name = sle.batch_no 
+								and expiry_date >= '%(posting_date)s' 
+								and docstatus != 2) 
+					%(mcond)s
+				group by batch_no having sum(actual_qty) > 0 
+				order by batch_no desc 
+				limit %(start)s, %(page_len)s """ % {'item_code': filters['item_code'], 
+					'warehouse': filters['warehouse'], 'posting_date': filters['posting_date'], 
+					'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 
+					'start': start, 'page_len': page_len})
+	else:
+		return webnotes.conn.sql("""select name from tabBatch 
+				where docstatus != 2 
+					and item = '%(item_code)s' 
+					and expiry_date >= '%(posting_date)s' 
+					and name like '%(txt)s' 
+					%(mcond)s 
+				order by name desc 
+				limit %(start)s, %(page_len)s""" % {'item_code': filters['item_code'], 
+				'posting_date': filters['posting_date'], 'txt': "%%%s%%" % txt, 
+				'mcond':get_match_cond(doctype, searchfield),'start': start, 
+				'page_len': page_len})
\ No newline at end of file
diff --git a/selling/doctype/sales_order/sales_order.js b/selling/doctype/sales_order/sales_order.js
index 27db426..509ecf7 100644
--- a/selling/doctype/sales_order/sales_order.js
+++ b/selling/doctype/sales_order/sales_order.js
@@ -154,12 +154,12 @@
 }
 
 cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
-	var cond = '';
-	if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
-	return repl('SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND %(cond)s `tabProject`.name LIKE "%s" \
-		ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
+	return {
+		query: "controllers.queries.get_project_name",
+		filters: {
+			'customer': doc.customer
+		}
+	}
 }
 
 cur_frm.cscript['Stop Sales Order'] = function() {
@@ -193,7 +193,9 @@
 }
 
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters:{ 'is_group': "No"}
+	}
 }
 
 cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
diff --git a/setup/doctype/authorization_rule/authorization_rule.js b/setup/doctype/authorization_rule/authorization_rule.js
index 184c761..1866cbc 100644
--- a/setup/doctype/authorization_rule/authorization_rule.js
+++ b/setup/doctype/authorization_rule/authorization_rule.js
@@ -81,32 +81,51 @@
 }
 
 
-cur_frm.fields_dict.system_user.get_query = erpnext.utils.profile_query;
+cur_frm.fields_dict.system_user.get_query = function(doc,cdt,cdn) {
+  return{ query:"controllers.queries.profile_query" } }
 
-cur_frm.fields_dict.approving_user.get_query = erpnext.utils.profile_query;
+cur_frm.fields_dict.approving_user.get_query = function(doc,cdt,cdn) {
+  return{ query:"controllers.queries.profile_query" } }
+
+cur_frm.fields_dict['approving_role'].get_query = cur_frm.fields_dict['system_role'].get_query;
 
 // System Role Trigger
 // -----------------------
 cur_frm.fields_dict['system_role'].get_query = function(doc) {
-  return 'SELECT tabRole.name FROM tabRole WHERE tabRole.name not in ("Administrator","Guest","All") AND tabRole.%(key)s LIKE "%s" LIMIT 50'
+  return{
+    filters:[
+      ['Role', 'name', 'not in', 'Administrator, Guest, All']
+    ]
+  }
 }
 
 // Approving Role Trigger
 // -----------------------
-cur_frm.fields_dict['approving_role'].get_query = function(doc) {
-  return 'SELECT tabRole.name FROM tabRole WHERE tabRole.name not in ("Administrator","Guest","All") AND tabRole.%(key)s LIKE "%s" LIMIT 50'
-}
+// cur_frm.fields_dict['approving_role'].get_query = function(doc) {
+//   return 'SELECT tabRole.name FROM tabRole WHERE tabRole.name not in ("Administrator","Guest","All") AND tabRole.%(key)s LIKE "%s" LIMIT 50'
+// }
 
 
 // Master Name Trigger
 // --------------------
 cur_frm.fields_dict['master_name'].get_query = function(doc){
   if(doc.based_on == 'Customerwise Discount')
-    return 'SELECT `tabCustomer`.`name` FROM `tabCustomer` WHERE `tabCustomer`.docstatus !=2 and `tabCustomer`.`name` LIKE "%s" ORDER BY `tabCustomer`.`name` DESC LIMIT 50';
+    return {
+      filters:[
+        ['Customer', 'docstatus', '!=', 2]
+      ]
+    }
   else if(doc.based_on == 'Itemwise Discount')
-    return 'SELECT `tabItem`.`name` FROM `tabItem` WHERE (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` = "0000-00-00" OR `tabItem`.`end_of_life` > NOW()) and `tabItem`.is_sales_item = "Yes" and tabItem.%(key)s LIKE "%s" ORDER BY `tabItem`.`name` DESC LIMIT 50';
+    return {
+      query: "controllers.queries.item_query"
+    }
   else
-    return 'SELECT `tabItem`.`name` FROM `tabItem` WHERE `tabItem`.`name` = "cheating done to avoid null" ORDER BY `tabItem`.`name` DESC LIMIT 50';
+    return {
+      filters: [
+        ['Item', 'name', '=', 'cheating done to avoid null']
+      ]
+    }
 }
 
-cur_frm.fields_dict.to_emp.get_query = erpnext.utils.employee_query;
\ No newline at end of file
+cur_frm.fields_dict.to_emp.get_query = function(doc,cdt,cdn) {
+  return{ query:"controllers.queries.employee_query" } }
\ No newline at end of file
diff --git a/setup/doctype/company/company.js b/setup/doctype/company/company.js
index 489ed0c..dfe8e2a 100644
--- a/setup/doctype/company/company.js
+++ b/setup/doctype/company/company.js
@@ -45,43 +45,48 @@
   }
 }
 
+cur_frm.fields_dict.default_cash_account.get_query = cur_frm.fields_dict.default_bank_account.get_query;
+
 cur_frm.fields_dict.default_bank_account.get_query = function(doc) {    
-  return 'SELECT `tabAccount`.name, `tabAccount`.debit_or_credit, `tabAccount`.group_or_ledger FROM `tabAccount` WHERE `tabAccount`.company = "'+doc.name+'" AND `tabAccount`.group_or_ledger = "Ledger" AND `tabAccount`.docstatus != 2 AND `tabAccount`.account_type = "Bank or Cash" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name LIMIT 50';   
+	return{
+		filters:{
+			'company': doc.name,
+			'group_or_ledger': "Ledger",
+			'account_type': "Bank or Cash"
+		}
+	}  
 }
 
-cur_frm.fields_dict.default_cash_account.get_query = function(doc) {    
-  return 'SELECT `tabAccount`.name, `tabAccount`.debit_or_credit, `tabAccount`.group_or_ledger FROM `tabAccount` WHERE `tabAccount`.company = "'+doc.name+'" AND `tabAccount`.group_or_ledger = "Ledger" AND `tabAccount`.docstatus != 2 AND `tabAccount`.account_type = "Bank or Cash" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name LIMIT 50';   
-}
-
+cur_frm.fields_dict.payables_group.get_query = cur_frm.fields_dict.receivables_group.get_query;
 
 cur_frm.fields_dict.receivables_group.get_query = function(doc) {  
-  return 'SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company = "'+doc.name+'" AND `tabAccount`.group_or_ledger = "Group" AND `tabAccount`.docstatus != 2 AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name LIMIT 50';
-}
-
-
-cur_frm.fields_dict.payables_group.get_query = function(doc) {  
-  return 'SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company = "'+doc.name+'" AND `tabAccount`.group_or_ledger = "Group" AND `tabAccount`.docstatus != 2 AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.name LIMIT 50';
+	return{
+		filters:{
+			'company': doc.name,
+			'group_or_ledger': "Group"
+		}
+	}  
 }
 
 if (sys_defaults.auto_inventory_accounting) {
 	cur_frm.fields_dict["stock_in_hand_account"].get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_account_list", 
 			"filters": {
 				"is_pl_account": "No",
 				"debit_or_credit": "Debit",
-				"company": doc.name
+				"company": doc.name,
+				'group_or_ledger': "Ledger"
 			}
 		}
 	}
 
 	cur_frm.fields_dict["stock_adjustment_account"].get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_account_list", 
 			"filters": {
 				"is_pl_account": "Yes",
 				"debit_or_credit": "Debit",
-				"company": doc.name
+				"company": doc.name,
+				'group_or_ledger': "Ledger"
 			}
 		}
 	}
@@ -91,18 +96,17 @@
 
 	cur_frm.fields_dict["stock_received_but_not_billed"].get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_account_list", 
 			"filters": {
 				"is_pl_account": "No",
 				"debit_or_credit": "Credit",
-				"company": doc.name
+				"company": doc.name,
+				'group_or_ledger': "Ledger"
 			}
 		}
 	}
 
 	cur_frm.fields_dict["stock_adjustment_cost_center"].get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_cost_center_list", 
 			"filters": {"company": doc.name}
 		}
 	}
diff --git a/setup/doctype/contact_control/contact_control.js b/setup/doctype/contact_control/contact_control.js
index c427ec0..db0ed91 100755
--- a/setup/doctype/contact_control/contact_control.js
+++ b/setup/doctype/contact_control/contact_control.js
@@ -24,7 +24,11 @@
 // ---------------------------
 if(cur_frm.fields_dict['territory']){
 	cur_frm.fields_dict['territory'].get_query = function(doc,dt,dn) {
-		return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"  ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';
+		return {
+			filters: {
+				'is_group': "No" 
+			}
+		}
 	}
 }
 
diff --git a/setup/doctype/customer_group/customer_group.js b/setup/doctype/customer_group/customer_group.js
index af0c6f0..e865860 100644
--- a/setup/doctype/customer_group/customer_group.js
+++ b/setup/doctype/customer_group/customer_group.js
@@ -30,8 +30,10 @@
 
 //get query select Customer Group
 cur_frm.fields_dict['parent_customer_group'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabCustomer Group`.`name`,`tabCustomer Group`.`parent_customer_group` \
-	FROM `tabCustomer Group` WHERE `tabCustomer Group`.`is_group` = "Yes" AND \
-		`tabCustomer Group`.`docstatus`!= 2 AND `tabCustomer Group`.%(key)s LIKE "%s" \
-		ORDER BY  `tabCustomer Group`.`name` ASC LIMIT 50';
+	return{
+		searchfield:['name', 'parent_customer_group'],
+		filters: {
+			'is_group': "Yes"
+		}
+	} 
 }
\ No newline at end of file
diff --git a/setup/doctype/item_group/item_group.js b/setup/doctype/item_group/item_group.js
index 6bb6fe3..b642735 100644
--- a/setup/doctype/item_group/item_group.js
+++ b/setup/doctype/item_group/item_group.js
@@ -34,5 +34,10 @@
 
 //get query select item group
 cur_frm.fields_dict['parent_item_group'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabItem Group`.`name`,`tabItem Group`.`parent_item_group` FROM `tabItem Group` WHERE `tabItem Group`.`is_group` = "Yes" AND  `tabItem Group`.`docstatus`!= 2 AND `tabItem Group`.`name` !="'+doc.item_group_name+'" AND `tabItem Group`.%(key)s LIKE "%s" ORDER BY  `tabItem Group`.`name` ASC LIMIT 50';
+	return{
+		filters:[
+			['Item Group', 'is_group', '=', 'Yes'],
+			['Item Group', 'naem', '!=', doc.item_group_name]
+		]
+	}
 }
\ No newline at end of file
diff --git a/setup/doctype/sales_partner/sales_partner.js b/setup/doctype/sales_partner/sales_partner.js
index c5f0dba..acf6b31 100644
--- a/setup/doctype/sales_partner/sales_partner.js
+++ b/setup/doctype/sales_partner/sales_partner.js
@@ -97,5 +97,7 @@
 }
 
 cur_frm.fields_dict['partner_target_details'].grid.get_field("item_group").get_query = function(doc, dt, dn) {
-  return 'SELECT `tabItem Group`.`name`,`tabItem Group`.`parent_item_group` FROM `tabItem Group` WHERE `tabItem Group`.is_group="No" AND `tabItem Group`.docstatus != 2 AND `tabItem Group`.%(key)s LIKE "%s" LIMIT 50'
+  return{
+  	filters:{ 'is_group': "No" }
+  }
 }
\ No newline at end of file
diff --git a/setup/doctype/sales_person/sales_person.js b/setup/doctype/sales_person/sales_person.js
index c529488..fd03a44 100644
--- a/setup/doctype/sales_person/sales_person.js
+++ b/setup/doctype/sales_person/sales_person.js
@@ -35,11 +35,19 @@
 
 //get query select sales person
 cur_frm.fields_dict['parent_sales_person'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabSales Person`.`name`,`tabSales Person`.`parent_sales_person` FROM `tabSales Person` WHERE `tabSales Person`.`is_group` = "Yes" AND `tabSales Person`.`docstatus`!= 2 AND `tabSales Person`.`name` !="'+doc.sales_person_name+'" AND `tabSales Person`.%(key)s LIKE "%s" ORDER BY  `tabSales Person`.`name` ASC LIMIT 50';
+	return{
+		filters:[
+			['Sales Person', 'is_group', '=', 'Yes'],
+			['Sales Person', 'name', '!=', doc.sales_person_name]
+		]
+	}
 }
 
 cur_frm.fields_dict['target_details'].grid.get_field("item_group").get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabItem Group`.name FROM `tabItem Group` WHERE `tabItem Group`.is_group="No" AND `tabItem Group`.docstatus != 2 AND `tabItem Group`.%(key)s LIKE "%s" LIMIT 50'
+	return{
+		filters:{ 'is_group': "No" }
+	}
 }
 
-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(doc,cdt,cdn) {
+	return{	query:"controllers.queries.employee_query" } }
\ No newline at end of file
diff --git a/setup/doctype/territory/territory.js b/setup/doctype/territory/territory.js
index 2932006..7fdfee5 100644
--- a/setup/doctype/territory/territory.js
+++ b/setup/doctype/territory/territory.js
@@ -30,11 +30,18 @@
 
 //get query select territory
 cur_frm.fields_dict['parent_territory'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "Yes" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.`name` !="'+doc.territory_name+'" AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters:[
+			['Territory', 'is_group', '=', 'Yes'],
+			['Territory', 'name', '!=', doc.territory_name]
+		]
+	}
 }
 
 
 // ******************** ITEM Group ******************************** 
 cur_frm.fields_dict['target_details'].grid.get_field("item_group").get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabItem Group`.`name`,`tabItem Group`.`parent_item_group` FROM `tabItem Group` WHERE `tabItem Group`.is_group="No" AND `tabItem Group`.docstatus != 2 AND `tabItem Group`.%(key)s LIKE "%s" LIMIT 50'
+	return{
+		filters:{ 'is_group': "No"}
+	}
 }
diff --git a/stock/doctype/batch/batch.js b/stock/doctype/batch/batch.js
index 93979da..8b26d54 100644
--- a/stock/doctype/batch/batch.js
+++ b/stock/doctype/batch/batch.js
@@ -15,7 +15,10 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 cur_frm.fields_dict['item'].get_query = function(doc, cdt, cdn) {
-	return erpnext.queries.item({
-		'ifnull(tabItem.is_stock_item, "No")': 'Yes'
-	})
+	return {
+		query:"controllers.queries.item_query",
+		filters:{
+			'is_stock_item': 'Yes'	
+		}
+	}	
 }
\ No newline at end of file
diff --git a/stock/doctype/delivery_note/delivery_note.js b/stock/doctype/delivery_note/delivery_note.js
index bbc22b9..790d409 100644
--- a/stock/doctype/delivery_note/delivery_note.js
+++ b/stock/doctype/delivery_note/delivery_note.js
@@ -106,12 +106,12 @@
 
 // ***************** Get project name *****************
 cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
-	var cond = '';
-	if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
-	return repl('SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND %(cond)s `tabProject`.name LIKE "%s" \
-		ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
+	return {
+		query: "controllers.queries.get_project_name",
+		filters: {
+			'customer': doc.customer
+		}
+	}
 }
 
 cur_frm.cscript.serial_no = function(doc, cdt, cdn) {
@@ -122,7 +122,9 @@
 }
 
 cur_frm.fields_dict['transporter_name'].get_query = function(doc) {
-	return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
+	return{
+		filters: { 'supplier_type': "transporter" }
+	}	
 }
 
 cur_frm.cscript['Make Packing Slip'] = function() {
@@ -135,7 +137,9 @@
 
 //get query select Territory
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters: { 'is_group': "No" }
+	}
 }
 
 var set_print_hide= function(doc, cdt, cdn){
@@ -223,11 +227,11 @@
 	// expense account
 	cur_frm.fields_dict['delivery_note_details'].grid.get_field('expense_account').get_query = function(doc) {
 		return {
-			"query": "accounts.utils.get_account_list", 
-			"filters": {
+			filters: {
 				"is_pl_account": "Yes",
 				"debit_or_credit": "Debit",
-				"company": doc.company
+				"company": doc.company,
+				"group_or_ledger": "Ledger"
 			}
 		}
 	}
@@ -246,8 +250,11 @@
 	
 	cur_frm.fields_dict.delivery_note_details.grid.get_field("cost_center").get_query = function(doc) {
 		return {
-			query: "accounts.utils.get_cost_center_list",
-			filters: { company: doc.company}
+
+			filters: { 
+				'company_name': doc.company,
+				'group_or_ledger': "Ledger"
+			}
 		}
 	}
 }
\ No newline at end of file
diff --git a/stock/doctype/item/item.js b/stock/doctype/item/item.js
index 7a731d2..3d427ad 100644
--- a/stock/doctype/item/item.js
+++ b/stock/doctype/item/item.js
@@ -51,39 +51,64 @@
 
 cur_frm.fields_dict['default_bom'].get_query = function(doc) {
    //var d = locals[this.doctype][this.docname];
-   return 'SELECT DISTINCT `tabBOM`.`name` FROM `tabBOM` WHERE `tabBOM`.`item` = "' + doc.item_code + '"  AND ifnull(`tabBOM`.`is_active`, 0) = 0 and `tabBOM`.docstatus != 2 AND `tabBOM`.%(key)s LIKE "%s" ORDER BY `tabBOM`.`name` LIMIT 50'
+    return{
+   		filters:{
+   			'item': doc.item_code,
+   			'is_active': 0
+   		}
+   }
 }
 
 
 // Expense Account
 // ---------------------------------
 cur_frm.fields_dict['purchase_account'].get_query = function(doc){
-  return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Debit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
+	return{
+		filters:{
+			'debit_or_credit': "Debit",
+			'group_or_ledger': "Ledger"
+		}
+	}
 }
 
 // Income Account
 // --------------------------------
 cur_frm.fields_dict['default_income_account'].get_query = function(doc) {
-  return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Credit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.`account_type` ="Income Account" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
+	return{
+		filters:{
+			'debit_or_credit': "Credit",
+			'group_or_ledger': "Ledger",
+			'account_type': "Income Account"
+		}
+	}
 }
 
 
 // Purchase Cost Center
 // -----------------------------
 cur_frm.fields_dict['cost_center'].get_query = function(doc) {
-  return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50'
+	return{
+		filters:{ 'group_or_ledger': "Ledger" }
+	}
 }
 
 
 // Sales Cost Center
 // -----------------------------
 cur_frm.fields_dict['default_sales_cost_center'].get_query = function(doc) {
-  return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY  `tabCost Center`.`name` ASC LIMIT 50'
+	return{
+		filters:{ 'group_or_ledger': "Ledger" }
+	}
 }
 
 
 cur_frm.fields_dict['item_tax'].grid.get_field("tax_type").get_query = function(doc, cdt, cdn) {
-  return 'SELECT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`account_type` in ("Tax", "Chargeable") and `tabAccount`.`docstatus` != 2 and `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` DESC LIMIT 50'
+	return{
+		filters:[
+			['Account', 'account_type', 'in', 'Tax, Chargeable'],
+			['Account', 'docstatus', '!=', 2]
+		]
+	}
 }
 
 cur_frm.cscript.tax_type = function(doc, cdt, cdn){
@@ -94,10 +119,11 @@
 
 //get query select item group
 cur_frm.fields_dict['item_group'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabItem Group`.`name`,`tabItem Group`.`parent_item_group` \
-		FROM `tabItem Group` WHERE `tabItem Group`.`docstatus`!= 2 AND \
-		`tabItem Group`.%(key)s LIKE "%s"  ORDER BY  `tabItem Group`.`name` \
-		ASC LIMIT 50'
+	return {
+		filters: [
+			['Item Group', 'docstatus', '!=', 2]
+		]
+	}
 }
 
 // for description from attachment
@@ -137,10 +163,12 @@
 }
 
 cur_frm.fields_dict.item_customer_details.grid.get_field("customer_name").get_query = 
-	erpnext.utils.customer_query;
+function(doc,cdt,cdn) {
+		return{	query:"controllers.queries.customer_query" } }
 	
 cur_frm.fields_dict.item_supplier_details.grid.get_field("supplier").get_query = 
-	erpnext.utils.supplier_query;
+	function(doc,cdt,cdn) {
+		return{ query:"controllers.queries.supplier_query" } }
 
 cur_frm.cscript.on_remove_attachment = function(doc) {
 	if(!inList(cur_frm.fields_dict.image.df.options.split("\n"), doc.image)) {
diff --git a/stock/doctype/landed_cost_wizard/landed_cost_wizard.js b/stock/doctype/landed_cost_wizard/landed_cost_wizard.js
index eb0c3df..a093d6f 100644
--- a/stock/doctype/landed_cost_wizard/landed_cost_wizard.js
+++ b/stock/doctype/landed_cost_wizard/landed_cost_wizard.js
@@ -20,5 +20,12 @@
 
 
 cur_frm.fields_dict['landed_cost_details'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
-  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND (tabAccount.account_type = "Tax" OR tabAccount.account_type = "Chargeable" or (tabAccount.is_pl_account = "Yes" and tabAccount.debit_or_credit = "Debit")) AND  tabAccount.name LIKE "%s"';
+return{
+		filters:[
+			['Account', 'group_or_ledger', '=', 'Ledger'],
+			['Account', 'account_type', 'in', 'Tax, Chargeable'],
+			['Account', 'is_pl_account', '=', 'Yes'],
+			['Account', 'debit_or_credit', '=', 'Debit']
+		]
+	}
 }
diff --git a/stock/doctype/packing_slip/packing_slip.js b/stock/doctype/packing_slip/packing_slip.js
index 18a2486..e19ab49 100644
--- a/stock/doctype/packing_slip/packing_slip.js
+++ b/stock/doctype/packing_slip/packing_slip.js
@@ -15,17 +15,18 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 cur_frm.fields_dict['delivery_note'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name FROM `tabDelivery Note` WHERE docstatus=0 AND %(key)s LIKE "%s"';
+	return{
+		filters:{ 'docstatus': 0}
+	}
 }
 
 
 cur_frm.fields_dict['item_details'].grid.get_field('item_code').get_query = 
 		function(doc, cdt, cdn) {
-	var query = 'SELECT name, item_name, description FROM `tabItem` WHERE name IN ( \
-		SELECT item_code FROM `tabDelivery Note Item` dnd \
-		WHERE parent="'	+ doc.delivery_note + '" AND IFNULL(qty, 0) > IFNULL(packed_qty, 0)) \
-		AND %(key)s LIKE "%s" LIMIT 50';
-	return query;
+			return {
+				query: "stock.doctype.packing_slip.packing_slip.item_details",
+				filters:{ 'delivery_note': doc.delivery_note}
+			}
 }
 
 cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
diff --git a/stock/doctype/packing_slip/packing_slip.py b/stock/doctype/packing_slip/packing_slip.py
index 1375108..63aa6a9 100644
--- a/stock/doctype/packing_slip/packing_slip.py
+++ b/stock/doctype/packing_slip/packing_slip.py
@@ -171,4 +171,15 @@
 				ch.item_name = item.item_name
 				ch.stock_uom = item.stock_uom
 				ch.qty = flt(item.qty) - flt(item.packed_qty)
-		self.update_item_details()
\ No newline at end of file
+		self.update_item_details()
+
+def item_details(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+	return webnotes.conn.sql("""select name, item_name, description from `tabItem` 
+				where name in ( select item_code FROM `tabDelivery Note Item` 
+	 						where parent= %s 
+	 							and ifnull(qty, 0) > ifnull(packed_qty, 0)) 
+	 			and %s like "%s" %s 
+	 			limit  %s, %s """ % ("%s", searchfield, "%s", 
+	 			get_match_cond(doctype, searchfield), "%s", "%s"), 
+	 			(filters["delivery_note"], "%%%s%%" % txt, start, page_len))
\ No newline at end of file
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.js b/stock/doctype/purchase_receipt/purchase_receipt.js
index 852a9c6..e21d6a3 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -116,11 +116,15 @@
 }
 
 cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+		filters:{ 'supplier': doc.supplier}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+		filters:{ 'supplier': doc.supplier}
+	}
 }
 
 cur_frm.cscript.new_contact = function(){
@@ -131,15 +135,19 @@
 }
 
 cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabProject`.name FROM `tabProject` \
-		WHERE `tabProject`.status not in ("Completed", "Cancelled") \
-		AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['project', 'status', 'not in', 'Completed, Cancelled']
+		]
+	}
 }
 
 cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
 	if(d.item_code){
-		return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
+		return{
+			filters:{'item': d.item_code}
+		}
 	}
 	else{
 		alert("Please enter Item Code.");
@@ -156,11 +164,19 @@
 }
 
 cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
+	return{
+		filters:[
+			['Print Heading', 'docstatus', '!=', '2']
+		]
+	}
 }
 
 cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query = function(doc) {
-	return 'SELECT `tabQuality Inspection`.name FROM `tabQuality Inspection` WHERE `tabQuality Inspection`.docstatus = 1 AND `tabQuality Inspection`.%(key)s LIKE "%s"';
+	return {
+		filters: {
+			'docstatus': 1
+		}
+	}
 }
 
 cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
diff --git a/stock/doctype/serial_no/serial_no.js b/stock/doctype/serial_no/serial_no.js
index 9e1426c..0253ffb 100644
--- a/stock/doctype/serial_no/serial_no.js
+++ b/stock/doctype/serial_no/serial_no.js
@@ -46,7 +46,9 @@
 // territory
 // ----------
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters:{'is_group': "No"}
+	}
 }
 
 // Supplier
@@ -59,11 +61,22 @@
 //item code
 //----------
 cur_frm.fields_dict['item_code'].get_query = function(doc,cdt,cdn) {
- 	return erpnext.queries.item({
-		'ifnull(tabItem.has_serial_no, "No")': 'Yes'
-	});
+ 	return{
+		query:"controllers.queries.item_query",
+		filters:{
+			'has_serial_no': 'Yes'	
+		}
+	}	
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.customer_query"
+	}
+}
 
-cur_frm.fields_dict.supplier.get_query = erpnext.utils.supplier_query;
\ No newline at end of file
+cur_frm.fields_dict.supplier.get_query = function(doc,cdt,cdn) {
+	return{
+		query:"controllers.queries.supplier_query"
+	}
+}
\ No newline at end of file
diff --git a/stock/doctype/stock_entry/stock_entry.js b/stock/doctype/stock_entry/stock_entry.js
index 468d3d7..3fc03cb 100644
--- a/stock/doctype/stock_entry/stock_entry.js
+++ b/stock/doctype/stock_entry/stock_entry.js
@@ -56,7 +56,9 @@
 			this.frm.fields_dict.delivery_note_no.get_query;
 		
 		this.frm.fields_dict.purchase_receipt_no.get_query = function() {
-			return { query: "stock.doctype.stock_entry.stock_entry.query_purchase_return_doc" };
+			return { 
+				filters:{ 'docstatus': 1 }
+			};
 		};
 		
 		this.frm.fields_dict.mtn_details.grid.get_field('item_code').get_query = function() {
@@ -81,8 +83,10 @@
 
 			this.frm.fields_dict["expense_adjustment_account"].get_query = function() {
 				return {
-					"query": "accounts.utils.get_account_list", 
-					"filters": { "company": me.frm.doc.company }
+					filters: { 
+						"company": me.frm.doc.company,
+						"group_or_ledger": "Ledger"
+					}
 				}
 			}
 		}
@@ -280,9 +284,12 @@
 }
 
 cur_frm.fields_dict['production_order'].get_query = function(doc) {
-	return 'select name from `tabProduction Order` \
-		where docstatus = 1 and qty > ifnull(produced_qty,0) AND %(key)s like "%s%%" \
-		order by name desc limit 50';
+	return{
+		filters:[
+			['Production Order', 'docstatus', '=', 1],
+			['Production Order', 'qty', '>','`tabProduction Order`.produced_qty']
+		]
+	}
 }
 
 cur_frm.cscript.purpose = function(doc, cdt, cdn) {
@@ -307,17 +314,21 @@
 	var d = locals[cdt][cdn];		
 	if(d.item_code) {
 		if (d.s_warehouse) {
-			return "select batch_no from `tabStock Ledger Entry` sle \
-				where item_code = '" + d.item_code + "' and warehouse = '" + d.s_warehouse +
-				"' and ifnull(is_cancelled, 'No') = 'No' and batch_no like '%s' \
-				and exists(select * from `tabBatch` where \
-				name = sle.batch_no and expiry_date >= '" + doc.posting_date + 
-				"' and docstatus != 2) group by batch_no having sum(actual_qty) > 0 \
-				order by batch_no desc limit 50";
+			return{
+				query: "stock.doctype.stock_entry.stock_entry.get_batch_no",
+				filters:{
+					'item_code': d.item_code,
+					's_warehouse': d.s_warehouse,
+					'posting_date': doc.posting_date
+				}
+			}			
 		} else {
-			return "SELECT name FROM tabBatch WHERE docstatus != 2 AND item = '" + 
-				d.item_code + "' and expiry_date >= '" + doc.posting_date + 
-				"' AND name like '%s' ORDER BY name DESC LIMIT 50";
+			return{
+				filters:[
+					['Batch', 'item', '=', d.item_code],
+					['Batch', 'expiry_date', '>=', doc.posting_date]
+				]
+			}
 		}		
 	} else {
 		msgprint("Please enter Item Code to get batch no");
@@ -374,6 +385,8 @@
 	}
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{ query:"controllers.queries.customer_query" } }
 
-cur_frm.fields_dict.supplier.get_query = erpnext.utils.supplier_query;
\ No newline at end of file
+cur_frm.fields_dict.supplier.get_query = function(doc,cdt,cdn) {
+	return{	query:"controllers.queries.supplier_query" } }
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index c8babff..d985432 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -25,6 +25,7 @@
 from webnotes import msgprint, _
 from stock.utils import get_incoming_rate
 from stock.stock_ledger import get_previous_sle
+from controllers.queries import get_match_cond
 import json
 
 sql = webnotes.conn.sql
@@ -709,24 +710,31 @@
 	return result and result[0] or {}
 	
 def query_sales_return_doc(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
 	conditions = ""
 	if doctype == "Sales Invoice":
 		conditions = "and update_stock=1"
 	
 	return webnotes.conn.sql("""select name, customer, customer_name
 		from `tab%s` where docstatus = 1
-		and (`%s` like %%(txt)s or `customer` like %%(txt)s) %s
+			and (`%s` like %%(txt)s 
+				or `customer` like %%(txt)s) %s %s
 		order by name, customer, customer_name
-		limit %s""" % (doctype, searchfield, conditions, "%(start)s, %(page_len)s"),
-		{"txt": "%%%s%%" % txt, "start": start, "page_len": page_len}, as_list=True)
+		limit %s""" % (doctype, searchfield, conditions, 
+		get_match_cond(doctype, searchfield), "%(start)s, %(page_len)s"), 
+		{"txt": "%%%s%%" % txt, "start": start, "page_len": page_len}, 
+		as_list=True)
 	
 def query_purchase_return_doc(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
 	return webnotes.conn.sql("""select name, supplier, supplier_name
 		from `tab%s` where docstatus = 1
-		and (`%s` like %%(txt)s or `supplier` like %%(txt)s)
+			and (`%s` like %%(txt)s 
+				or `supplier` like %%(txt)s) %s
 		order by name, supplier, supplier_name
-		limit %s""" % (doctype, searchfield, "%(start)s, %(page_len)s"),
-		{"txt": "%%%s%%" % txt, "start": start, "page_len": page_len}, as_list=True)
+		limit %s""" % (doctype, searchfield, get_match_cond(doctype, searchfield), 
+		"%(start)s, %(page_len)s"),	{"txt": "%%%s%%" % txt, "start": 
+		start, "page_len": page_len}, as_list=True)
 		
 def query_return_item(doctype, txt, searchfield, start, page_len, filters):
 	txt = txt.replace("%", "")
@@ -752,6 +760,26 @@
 
 	return result[start:start+page_len]
 
+def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
+	from controllers.queries import get_match_cond
+
+	return webnotes.conn.sql("""select batch_no from `tabStock Ledger Entry` sle 
+			where item_code = '%(item_code)s' 
+				and warehouse = '%(s_warehouse)s'
+				and ifnull(is_cancelled, 'No') = 'No' 
+				and batch_no like '%(txt)s' 
+				and exists(select * from `tabBatch` 
+						where name = sle.batch_no 
+							and expiry_date >= %(posting_date)s 
+							and docstatus != 2) 
+			%(mcond)s
+			group by batch_no having sum(actual_qty) > 0 
+			order by batch_no desc 
+			limit %(start)s, %(page_len)s """ % {'item_code': filters['item_code'], 
+			's_warehouse': filters['s_warehouse'], 'posting_date': filters['posting_date'], 
+			'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 
+			"start": start, "page_len": page_len})
+
 def get_stock_items_for_return(ref_doclist, parentfields):
 	"""return item codes filtered from doclist, which are stock items"""
 	if isinstance(parentfields, basestring):
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.js b/stock/doctype/stock_reconciliation/stock_reconciliation.js
index dd49683..b003e05 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.js
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.js
@@ -46,9 +46,9 @@
 		
 			this.frm.fields_dict["expense_account"].get_query = function() {
 				return {
-					"query": "accounts.utils.get_account_list", 
 					"filters": {
-						"company": me.frm.doc.company
+						'company': me.frm.doc.company,
+						'group_or_ledger': 'Ledger'
 					}
 				}
 			}
diff --git a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
index e022bb7..94b3bf0 100644
--- a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
+++ b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.js
@@ -15,7 +15,9 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 cur_frm.fields_dict['item_code'].get_query = function(doc) {
- 	return erpnext.queries.item_std();	
+ 	return {
+ 		query: "controllers.queries.item_std"
+ 	}	
 }
 
 //==================== Get Items Stock UOM =====================================================
diff --git a/support/doctype/customer_issue/customer_issue.js b/support/doctype/customer_issue/customer_issue.js
index 9957c8e..2268493 100644
--- a/support/doctype/customer_issue/customer_issue.js
+++ b/support/doctype/customer_issue/customer_issue.js
@@ -64,24 +64,29 @@
 }
 
 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{
+		filters:{ 'customer': doc.customer}
+	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation \
-		FROM tabContact WHERE customer = "'	+ doc.customer +
-		'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+	return{
+		filters:{ 'customer': doc.customer}
+	}
 }
 
 cur_frm.fields_dict['serial_no'].get_query = function(doc, cdt, cdn) {
-	var cond = '';
-	if(doc.item_code) cond = ' AND `tabSerial No`.item_code = "'+ doc.item_code +'"';
-	if(doc.customer) cond += ' AND `tabSerial No`.customer = "' + doc.customer + '"';
-	return 'SELECT `tabSerial No`.name, `tabSerial No`.description \
-		FROM `tabSerial No` \
-		WHERE `tabSerial No`.docstatus != 2 AND `tabSerial No`.status = "Delivered" \
-		AND `tabSerial No`.name LIKE "%s" ' + cond + ' ORDER BY `tabSerial No`.name ASC LIMIT 50';
+	var cond = [];
+	var filter = [
+		['Serial No', 'docstatus', '!=', 2],
+		['Serial No', 'status', '=', "Delivered"]
+	];
+	if(doc.item_code) cond = ['Serial No', 'item_code', '=', doc.item_code];
+	if(doc.customer) cond = ['Serial No', 'customer', '=', doc.customer];
+	filter.push(cond);
+	return{
+		filters:filter
+	}
 }
 
 cur_frm.add_fetch('serial_no', 'item_code', 'item_code');
@@ -96,15 +101,16 @@
 
 cur_frm.fields_dict['item_code'].get_query = function(doc, cdt, cdn) {
 	if(doc.serial_no) {
-		return 'SELECT `tabSerial No`.item_code, `tabSerial No`.description \
-			FROM `tabSerial No` \
-			WHERE `tabSerial No`.docstatus != 2 AND `tabSerial No`.name = "' + doc.serial_no +
-			'" AND `tabSerial No`.item_code LIKE "%s" ORDER BY `tabSerial No`.item_code ASC LIMIT 50';
+		return{
+			filters:{ 'serial_no': doc.serial_no}
+		}		
 	}
 	else{
-		return 'SELECT `tabItem`.name, `tabItem`.item_name, `tabItem`.description \
-			FROM `tabItem` \
-			WHERE `tabItem`.docstatus != 2 AND `tabItem`.%(key)s LIKE "%s" ORDER BY `tabItem`.name ASC LIMIT 50';
+		return{
+			filters:[
+				['Item', 'docstatus', '!=', 2]
+			]
+		}		
 	}
 }
 
@@ -112,10 +118,10 @@
 cur_frm.add_fetch('item_code', 'description', 'description');
 
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-	return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` \
-		FROM `tabTerritory` \
-		WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 \
-		AND `tabTerritory`.%(key)s LIKE "%s"	ORDER BY	`tabTerritory`.`name` ASC LIMIT 50';
+	return{
+		filters:{ 'is_group': "No"}
+	}
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{	query:"controllers.queries.customer_query" } }
diff --git a/support/doctype/maintenance_schedule/maintenance_schedule.js b/support/doctype/maintenance_schedule/maintenance_schedule.js
index 6e43cb1..fab9b2a 100644
--- a/support/doctype/maintenance_schedule/maintenance_schedule.js
+++ b/support/doctype/maintenance_schedule/maintenance_schedule.js
@@ -71,16 +71,22 @@
 }
 
 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{
+    filters:{ 'customer': doc.customer}
+  }
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-  return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+  return{
+    filters:{ 'customer': doc.customer}
+  }
 }
 
 //
 cur_frm.fields_dict['item_maintenance_detail'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
-  return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+  return{
+    filters:{ 'is_service_item': "Yes"}
+  }
 }
 
 cur_frm.cscript.item_code = function(doc, cdt, cdn) {
@@ -118,7 +124,10 @@
 }
 
 cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
-  return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s"  ORDER BY  `tabTerritory`.`name` ASC LIMIT 50';
+  return{
+    filters:{ 'is_group': "No"}
+  }  
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+  return{ query:"controllers.queries.customer_query" } }
diff --git a/support/doctype/maintenance_visit/maintenance_visit.js b/support/doctype/maintenance_visit/maintenance_visit.js
index 8de80af..0b0d010 100644
--- a/support/doctype/maintenance_visit/maintenance_visit.js
+++ b/support/doctype/maintenance_visit/maintenance_visit.js
@@ -93,15 +93,21 @@
 }
 
 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{
+    	filters:{'customer': doc.customer}
+  	}
 }
 
 cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
-	return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
+  	return{
+    	filters:{'customer': doc.customer}
+  	}
 }
 
 cur_frm.fields_dict['maintenance_visit_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
-	return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND tabItem.%(key)s LIKE "%s" LIMIT 50';
+	return{
+    	filters:{ 'is_service_item': "Yes"}
+  	}
 }
 
 cur_frm.cscript.item_code = function(doc, cdt, cdn) {
@@ -112,4 +118,15 @@
 	}
 }
 
-cur_frm.fields_dict.customer.get_query = erpnext.utils.customer_query;
\ No newline at end of file
+//get query select Territory
+cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
+  	return{
+    	filters:{
+      		'is_group': "No"
+    	}
+  	}
+}
+
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return {query: "controllers.queries.customer_query" }
+}
\ No newline at end of file
diff --git a/support/doctype/support_ticket/support_ticket.js b/support/doctype/support_ticket/support_ticket.js
index 903f41c..bd7e6cc 100644
--- a/support/doctype/support_ticket/support_ticket.js
+++ b/support/doctype/support_ticket/support_ticket.js
@@ -14,7 +14,8 @@
 // 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.fields_dict.customer.get_query = erpnext.utils.customer_query;
+cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) {
+	return{	query:"controllers.queries.customer_query" } }
 
 wn.provide("erpnext.support");
 // TODO commonify this code