[merge]
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.js b/accounts/doctype/purchase_invoice/purchase_invoice.js
index fa58d9f..665fbb7 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -97,7 +97,7 @@
 cur_frm.cscript.get_items = function(doc, dt, dn) {
 	var callback = function(r,rt) { 
 		unhide_field(['supplier_address', 'contact_person']);				
-		refresh_many(['credit_to','supplier','supplier_address','contact_person','supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email','entries', 'purchase_receipt_main', 'purchase_order_main', 'purchase_tax_details']);
+		cur_frm.refresh_fields();
 	}
 	$c_obj(make_doclist(dt,dn),'pull_details','',callback);
 }
diff --git a/accounts/doctype/sales_invoice/sales_invoice.js b/accounts/doctype/sales_invoice/sales_invoice.js
index f776db5..ab10534 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/accounts/doctype/sales_invoice/sales_invoice.js
@@ -182,7 +182,7 @@
 cur_frm.cscript.get_items = function(doc, dt, dn) {
 	var callback = function(r,rt) {
 		unhide_field(['customer_address','contact_person', 'territory','customer_group']);
-		cur_frm.refresh();
+		cur_frm.refresh_fields();
 	}
 	get_server_fields('pull_details','','',doc, dt, dn,1,callback);
 }
diff --git a/accounts/page/accounts_home/accounts_home.js b/accounts/page/accounts_home/accounts_home.js
index 07c8b66..31660eb 100644
--- a/accounts/page/accounts_home/accounts_home.js
+++ b/accounts/page/accounts_home/accounts_home.js
@@ -171,11 +171,6 @@
 				page: "financial-analytics"
 			},
 			{
-				"label":wn._("Trend Analyzer"),
-				route: "Report/Profile/Trend Analyzer",
-				doctype: "Sales Invoice"
-			},
-			{
 				"label":wn._("Gross Profit"),
 				route: "query-report/Gross Profit",
 				doctype: "Sales Invoice"
diff --git a/accounts/page/general_ledger/general_ledger.js b/accounts/page/general_ledger/general_ledger.js
index 6a7d604..ff72104 100644
--- a/accounts/page/general_ledger/general_ledger.js
+++ b/accounts/page/general_ledger/general_ledger.js
@@ -68,6 +68,7 @@
 				
 		];
 	},
+	
 	filters: [
 		{fieldtype:"Select", label: "Company", link:"Company", default_value: "Select Company...",
 			filter: function(val, item, opts) {
@@ -96,6 +97,7 @@
 			return dateutil.str_to_obj(val) >= dateutil.str_to_obj(item.posting_date);
 		}},
 		{fieldtype: "Check", label: "Group by Ledger"},
+		{fieldtype: "Check", label: "Group by Voucher"},
 		{fieldtype:"Button", label: "Refresh", icon:"icon-refresh icon-white", cssClass:"btn-info"},
 		{fieldtype:"Button", label: "Reset Filters"}
 	],
@@ -116,9 +118,14 @@
 			me.filter_inputs.group_by_ledger
 				.parent().toggle(!!(me.account_by_name[$(this).val()] 
 					&& me.account_by_name[$(this).val()].group_or_ledger==="Group"));
+					
+			me.filter_inputs.group_by_voucher
+				.parent().toggle(!!(me.account_by_name[$(this).val()] 
+					&& me.account_by_name[$(this).val()].group_or_ledger==="Ledger"));
 		});
 		
 		this.trigger_refresh_on_change(["group_by_ledger"]);
+		this.trigger_refresh_on_change(["group_by_voucher"]);
 	},
 	setup_account_filter: function(company_filter) {
 		var me = this;
@@ -139,12 +146,14 @@
 	init_filter_values: function() {
 		this._super();
 		this.filter_inputs.group_by_ledger.parent().toggle(false);
+		this.filter_inputs.group_by_voucher.parent().toggle(false);
 		this.filter_inputs.company.change();
 		this.filter_inputs.account.change();
 	},
 	apply_filters_from_route: function() {
 		this._super();
 		this.filter_inputs.group_by_ledger.parent().toggle(false);
+		this.filter_inputs.group_by_voucher.parent().toggle(false);
 		this.filter_inputs.company.change();
 		this.filter_inputs.account.change();
 	},
@@ -196,13 +205,21 @@
 				if(!grouped_ledgers[item.account]) {
 					grouped_ledgers[item.account] = {
 						entries: [],
+						entries_group_by_voucher: {},
 						opening: me.make_summary_row("Opening", item.account),
 						totals: me.make_summary_row("Totals", item.account),
 						closing: me.make_summary_row("Closing (Opening + Totals)",
 							item.account)
 					};
 				}
-
+				
+				if(!grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no]) {
+					grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no] = {
+						row: {},
+						totals: {"debit": 0, "credit": 0}
+					}
+				}
+				
 				if(date < from_date || item.is_opening=="Yes") {
 					opening.debit += item.debit;
 					opening.credit += item.credit;
@@ -215,6 +232,11 @@
 
 					grouped_ledgers[item.account].totals.debit += item.debit;
 					grouped_ledgers[item.account].totals.credit += item.credit;
+					
+					grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no]
+						.totals.debit += item.debit;
+					grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no]
+						.totals.credit += item.credit;
 				}
 				if(item.account) {
 					item.against_account = me.voucher_accounts[item.voucher_type + ":"
@@ -224,6 +246,11 @@
 				if(me.apply_filters(item) && item.is_opening=="No") {
 					out.push(item);
 					grouped_ledgers[item.account].entries.push(item);
+					
+					if(grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no].row){
+						grouped_ledgers[item.account].
+							entries_group_by_voucher[item.voucher_no].row = item;
+					}
 				}
 			}
 		});
@@ -241,6 +268,11 @@
 					out = this.group_data_by_ledger(grouped_ledgers);
 			}
 			
+			if(this.account_by_name[this.account].group_or_ledger==="Ledger"
+				&& this.group_by_voucher) {
+					out = this.group_data_by_voucher(grouped_ledgers);
+			}
+			
 			opening = me.get_balance(me.account_by_name[me.account].debit_or_credit, opening)
 			closing = me.get_balance(me.account_by_name[me.account].debit_or_credit, closing)
 			
@@ -283,6 +315,26 @@
 		return [{id: "_blank_first", _no_format: true, debit: "", credit: ""}].concat(out);
 	},
 	
+	group_data_by_voucher: function(grouped_ledgers) {
+		var me = this;
+		var out = []
+		$.each(Object.keys(grouped_ledgers).sort(), function(i, account) {
+			if(grouped_ledgers[account].entries.length) {
+				$.each(Object.keys(grouped_ledgers[account].entries_group_by_voucher).sort(),
+				 	function(j, voucher) {
+						voucher_dict = grouped_ledgers[account].entries_group_by_voucher[voucher];
+						if(voucher_dict.totals.debit || voucher_dict.totals.credit) {
+							voucher_dict.row.debit = voucher_dict.totals.debit;
+							voucher_dict.row.credit = voucher_dict.totals.credit;
+							voucher_dict.row.id = "entry" + voucher
+							out = out.concat(voucher_dict.row);
+						}
+				});
+			}
+		});
+		return [{id: "_blank_first", _no_format: true, debit: "", credit: ""}].concat(out);
+	},
+	
 	get_balance: function(debit_or_credit, balance) {
 		if(debit_or_credit == "Debit") {
 			balance.debit -= balance.credit; balance.credit = 0;
diff --git a/accounts/report/purchase_invoice_trends/purchase_invoice_trends.py b/accounts/report/purchase_invoice_trends/purchase_invoice_trends.py
index b2f376b..a558a6c 100644
--- a/accounts/report/purchase_invoice_trends/purchase_invoice_trends.py
+++ b/accounts/report/purchase_invoice_trends/purchase_invoice_trends.py
@@ -21,14 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Purchase Invoice"
-	tab = ["tabPurchase Invoice","tabPurchase Invoice Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-
-	if not data :
-		webnotes.msgprint("Data not found for selected criterias")
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/accounts/report/sales_invoice_trends/sales_invoice_trends.py b/accounts/report/sales_invoice_trends/sales_invoice_trends.py
index 11d6665..a106834 100644
--- a/accounts/report/sales_invoice_trends/sales_invoice_trends.py
+++ b/accounts/report/sales_invoice_trends/sales_invoice_trends.py
@@ -21,14 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Sales Invoice"
-	tab = ["tabSales Invoice","tabSales Invoice Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-	
-	if not data :
-		webnotes.msgprint("Data not found for selected criterias")
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/buying/page/buying_home/buying_home.js b/buying/page/buying_home/buying_home.js
index bda2eb9..e996c04 100644
--- a/buying/page/buying_home/buying_home.js
+++ b/buying/page/buying_home/buying_home.js
@@ -91,11 +91,6 @@
 				"label":wn._("Purchase Analytics"),
 				page: "purchase-analytics"
 			},
-			{
-				"label":wn._("Trend Analyzer"),
-				route: "Report/Profile/Trend Analyzer",
-				doctype: "Purchase Order"
-			},
 		]
 	},
 	{
diff --git a/buying/report/item_wise_last_purchase_rate/item_wise_last_purchase_rate.txt b/buying/report/item_wise_last_purchase_rate/item_wise_last_purchase_rate.txt
deleted file mode 100644
index db99e72..0000000
--- a/buying/report/item_wise_last_purchase_rate/item_wise_last_purchase_rate.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-[
- {
-  "creation": "2013-06-18 11:24:36", 
-  "docstatus": 0, 
-  "modified": "2013-06-18 15:28:57", 
-  "modified_by": "Administrator", 
-  "owner": "Administrator"
- }, 
- {
-  "doctype": "Report", 
-  "is_standard": "Yes", 
-  "name": "__common__", 
-  "query": "select * from (select \n    result.item_code as \"Item Code:Link/Item:120\",\n    result.item_name as \"Item Name::120\",\n    result.description as \"Description::150\",\n    result.posting_date as \"Date::150\",\n    result.purchase_ref_rate as \"Price List Rate::180\", \n    result.discount_rate as \"Discount::120\", \n    result.purchase_rate as \"Rate::120\"\nfrom (\n    (select \n        po_item.item_code,\n        po_item.item_name,\n        po_item.description,\n        po.transaction_date as posting_date,\n        po_item.purchase_ref_rate, \n        po_item.discount_rate, \n        po_item.purchase_rate\n    from `tabPurchase Order` po, `tabPurchase Order Item` po_item\n    where po.name = po_item.parent and po.docstatus = 1)\n    union\n    (select \n        pr_item.item_code,\n        pr_item.item_name,\n        pr_item.description,\n        pr.posting_date,\n        pr_item.purchase_ref_rate,\n        pr_item.discount_rate,\n        pr_item.purchase_rate\n    from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item\n    where pr.name = pr_item.parent and pr.docstatus = 1)\n) result\norder by result.item_code asc, result.posting_date desc) result_wrapper\ngroup by `Item Code:Link/Item:120`\n", 
-  "ref_doctype": "Purchase Order", 
-  "report_name": "Item-wise Last Purchase Rate", 
-  "report_type": "Query Report"
- }, 
- {
-  "doctype": "Report", 
-  "name": "Item-wise Last Purchase Rate"
- }
-]
\ No newline at end of file
diff --git a/buying/report/purchase_order_trends/purchase_order_trends.py b/buying/report/purchase_order_trends/purchase_order_trends.py
index 301124f..9b29465 100644
--- a/buying/report/purchase_order_trends/purchase_order_trends.py
+++ b/buying/report/purchase_order_trends/purchase_order_trends.py
@@ -21,14 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Purchase Order"
-	tab = ["tabPurchase Order","tabPurchase Order Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-	
-	if not data :
-		webnotes.msgprint("Data not found for selected criterias")
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/controllers/trends.py b/controllers/trends.py
index c0636cb..eaaf4d1 100644
--- a/controllers/trends.py
+++ b/controllers/trends.py
@@ -22,23 +22,23 @@
 def get_columns(filters, trans):
 	validate_filters(filters)
 	
-	# based_on_cols, based_on_select, based_on_group_by, addl_tables
-	bonc, query_bon, based, sup_tab = basedon_wise_colums_query(filters.get("based_on"), trans)
-	# period_cols, period_select
-	pwc, query_pwc = period_wise_colums_query(filters, trans)
-	
-	# group_by_cols
-	grbc = group_wise_column(filters.get("group_by"))
+	# get conditions for based_on filter cond
+	based_on_details = based_wise_colums_query(filters.get("based_on"), trans)
+	# get conditions for periodic filter cond
+	period_cols, period_select = period_wise_colums_query(filters, trans)
+	# get conditions for grouping filter cond
+	group_by_cols = group_wise_column(filters.get("group_by"))
 
-	columns = bonc + pwc + ["TOTAL(Qty):Float:120", "TOTAL(Amt):Currency:120"]
-	if grbc:	
-		columns = bonc + grbc + pwc +["TOTAL(Qty):Float:120", "TOTAL(Amt):Currency:120"] 
+	columns = based_on_details["based_on_cols"] + period_cols + ["Total(Qty):Float:120", "Total(Amt):Currency:120"]
+	if group_by_cols:	
+		columns = based_on_details["based_on_cols"] + group_by_cols + period_cols + \
+			["Total(Qty):Float:120", "Total(Amt):Currency:120"] 
 
-	# conditions
-	details = {"query_bon": query_bon, "query_pwc": query_pwc, "columns": columns, 
-		"basedon": based, "grbc": grbc, "sup_tab": sup_tab}
+	conditions = {"based_on_select": based_on_details["based_on_select"], "period_wise_select": period_select, 
+		"columns": columns, "group_by": based_on_details["based_on_group_by"], "grbc": group_by_cols, "trans": trans,
+		"addl_tables": based_on_details["addl_tables"]}
 
-	return details
+	return conditions
 
 def validate_filters(filters):
 	for f in ["Fiscal Year", "Based On", "Period", "Company"]:
@@ -48,17 +48,17 @@
 	if filters.get("based_on") == filters.get("group_by"):
 		webnotes.msgprint("'Based On' and 'Group By' can not be same", raise_exception=1)
 
-def get_data(filters, tab, details):
+def get_data(filters, conditions):
 	data = []
 	inc, cond= '',''
-	query_details =  details["query_bon"] + details["query_pwc"]
+	query_details =  conditions["based_on_select"] + conditions["period_wise_select"]
 	
-	if details["query_bon"] in ["t1.project_name,", "t2.project_name,"]:
-		cond = 'and '+ details["query_bon"][:-1] +' IS Not NULL'
+	if conditions["based_on_select"] in ["t1.project_name,", "t2.project_name,"]:
+		cond = 'and '+ conditions["based_on_select"][:-1] +' IS Not NULL'
 
 	if filters.get("group_by"):
 		sel_col = ''
-		ind = details["columns"].index(details["grbc"][0])
+		ind = conditions["columns"].index(conditions["grbc"][0])
 
 		if filters.get("group_by") == 'Item':
 			sel_col = 't2.item_code'
@@ -71,15 +71,13 @@
 			inc = 2
 		else :
 			inc = 1
-
-		data1 = webnotes.conn.sql(""" select %s from `%s` t1, `%s` t2 %s
-					where t2.parent = t1.name and t1.company = %s 
-					and t1.fiscal_year = %s and t1.docstatus = 1 %s 
+		data1 = webnotes.conn.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
+					where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and 
+					t1.docstatus = 1 %s 
 					group by %s 
-				""" % (query_details, tab[0], tab[1], details["sup_tab"], "%s", 
-					"%s", cond, details["basedon"]), (filters.get("company"), 
-					filters["fiscal_year"]),
-			as_list=1)
+				""" % (query_details,  conditions["trans"],  conditions["trans"], conditions["addl_tables"], "%s", 
+					"%s", cond, conditions["group_by"]), (filters.get("company"), 
+					filters["fiscal_year"]),as_list=1)
 
 		for d in range(len(data1)):
 			#to add blanck column
@@ -88,39 +86,42 @@
 			data.append(dt)
 
 			#to get distinct value of col specified by group_by in filter
-			row = webnotes.conn.sql("""select DISTINCT(%s) from `%s` t1, `%s` t2 %s
+			row = webnotes.conn.sql("""select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
 						where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s 
 						and t1.docstatus = 1 and %s = %s 
-					"""%(sel_col, tab[0], tab[1], details["sup_tab"], "%s", "%s", details["basedon"], "%s"),
-						(filters.get("company"), filters.get("fiscal_year"), data1[d][0]), 
-				as_list=1)
+					""" % 
+					(sel_col,  conditions["trans"],  conditions["trans"], conditions["addl_tables"], 
+						"%s", "%s", conditions["group_by"], "%s"),
+					(filters.get("company"), filters.get("fiscal_year"), data1[d][0]), as_list=1)
 
 			for i in range(len(row)):
-				des = ['' for q in range(len(details["columns"]))]
+				des = ['' for q in range(len(conditions["columns"]))]
 				
-				#get data for each group_by filter 
-				row1 = webnotes.conn.sql(""" select %s , %s from `%s` t1, `%s` t2 %s
+				#get data for group_by filter 
+				row1 = webnotes.conn.sql(""" select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
 							where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s 
 							and t1.docstatus = 1 and %s = %s and %s = %s 
-						""" % (sel_col, details["query_pwc"], tab[0], tab[1], details["sup_tab"], 
-							"%s", "%s", sel_col, "%s", details["basedon"], "%s"), 
-							(filters.get("company"), filters.get("fiscal_year"), 
-							row[i][0], data1[d][0]), as_list=1)
+						""" % 
+						(sel_col, conditions["period_wise_select"], conditions["trans"], 
+						 	conditions["trans"], conditions["addl_tables"], "%s", "%s", sel_col, 
+							"%s", conditions["group_by"], "%s"), 
+						(filters.get("company"), filters.get("fiscal_year"), row[i][0], 
+							data1[d][0]), as_list=1)
 
 				des[ind] = row[i]
-				for j in range(1,len(details["columns"])-inc):	
+				for j in range(1,len(conditions["columns"])-inc):	
 					des[j+inc] = row1[0][j]
 					
 				data.append(des)
 	else:
-		data = webnotes.conn.sql(""" select %s from `%s` t1, `%s` t2 %s
-					where t2.parent = t1.name and t1.company = %s 
-					and t1.fiscal_year = %s and t1.docstatus = 1 %s 
+		data = webnotes.conn.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
+					where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and 
+					t1.docstatus = 1 %s 
 					group by %s	
-				"""%(query_details, tab[0], tab[1], details["sup_tab"], "%s", 
-					"%s", cond,details["basedon"]), (filters.get("company"), 
-					filters.get("fiscal_year")), 
-			as_list=1)
+				""" % 
+				(query_details, conditions["trans"], conditions["trans"], conditions["addl_tables"], 
+					"%s", "%s", cond,conditions["group_by"]), 
+				(filters.get("company"), filters.get("fiscal_year")), as_list=1)
 
 	return data
 
@@ -130,126 +131,132 @@
 def period_wise_colums_query(filters, trans):
 	query_details = ''
 	pwc = []
-	ysd = webnotes.conn.get_value("Fiscal year", filters.get("fiscal_year"), "year_start_date")
+	bet_dates = get_period_date_ranges(filters.get("period"), filters.get("fiscal_year"))
 
 	if trans in ['Purchase Receipt', 'Delivery Note', 'Purchase Invoice', 'Sales Invoice']:
 		trans_date = 'posting_date'
 	else:
 		trans_date = 'transaction_date'
-
-	if filters.get("period") == "Monthly":
-		month_name = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
-
-		for month_idx in range(ysd.month-1,len(month_name)) + range(0, ysd.month-1):
-			query_details = get_monthly_conditions(month_name, month_idx, trans_date, 
-				pwc, query_details)
 	
-	elif filters.get("period") == "Quarterly":
-
-		first_qsd, second_qsd, third_qsd, fourth_qsd = ysd, add_months(ysd,3), add_months(ysd,6), add_months(ysd,9)
-		first_qed, second_qed, third_qed, fourth_qed = add_days(add_months(first_qsd,3),-1), add_days(add_months(second_qsd,3),-1), add_days(add_months(third_qsd,3),-1), add_days(add_months(fourth_qsd,3),-1)
-		bet_dates = [[first_qsd,first_qed],[second_qsd,second_qed],[third_qsd,third_qed],[fourth_qsd,fourth_qed]] 
-		
-		pwc = [get_mon(first_qsd)+"-"+get_mon(first_qed)+" (Qty):Float:120", get_mon(first_qsd)+"-"+get_mon(first_qed)+"(Amt):Currency:120", 
-			get_mon(second_qsd)+"-"+get_mon(second_qed)+" (Qty):Float:120", get_mon(second_qsd)+"-"+get_mon(second_qed)+" (Amt):Currency:120", 
-			get_mon(third_qsd)+"-"+get_mon(third_qed)+" (Qty):Float:120", get_mon(third_qsd)+"-"+get_mon(third_qed)+" (Amt):Currency:120", 
-			get_mon(fourth_qsd)+"-"+get_mon(fourth_qed)+" (Qty):Float:120", get_mon(fourth_qsd)+"-"+get_mon(fourth_qed)+" (Amt):Currency:120"]
-
-		for d in bet_dates:
-			query_details += """
-				SUM(IF(t1.%(trans)s BETWEEN '%(sd)s' AND '%(ed)s', t2.qty, NULL)), 
-				SUM(IF(t1.%(trans)s BETWEEN '%(sd)s' AND '%(ed)s', t1.grand_total, NULL)),
-			"""%{"trans": trans_date, "sd": d[0],"ed": d[1]}
-
-	elif filters.get("period") == "Half-yearly":
-
-		first_half_start = ysd
-		first_half_end = add_days(add_months(first_half_start,6),-1)
-		second_half_start = add_days(first_half_end,1)
-		second_half_end = add_days(add_months(second_half_start,6),-1)
-
-		pwc = [get_mon(first_half_start)+"-"+get_mon(first_half_end)+"(Qty):Float:120", get_mon(first_half_start)+"-"+get_mon(first_half_end)+" (Amt):Currency:120",
-		 	get_mon(second_half_start)+"-"+get_mon(second_half_end)+" (Qty):Float:120",	get_mon(second_half_start)+"-"+get_mon(second_half_end)+" (Amt):Currency:120"]
-
-		query_details = """ 
-			 	SUM(IF(t1.%(trans)s BETWEEN '%(fhs)s' AND '%(fhe)s', t2.qty, NULL)),
-			 	SUM(IF(t1.%(trans)s BETWEEN '%(fhs)s' AND '%(fhe)s', t1.grand_total, NULL)), 
-			 	SUM(IF(t1.%(trans)s BETWEEN '%(shs)s' AND '%(she)s', t2.qty, NULL)), 
-			 	SUM(IF(t1.%(trans)s BETWEEN '%(shs)s' AND '%(she)s', t1.grand_total, NULL)),
-			"""%{"trans": trans_date, "fhs": first_half_start, "fhe": first_half_end,"shs": second_half_start, 
-		"she": second_half_end}	 
-	
+	if filters.get("period") != 'Yearly':
+		for dt in bet_dates:
+			get_period_wise_columns(dt, filters.get("period"), pwc)
+			query_details = get_period_wise_query(dt, trans_date, query_details)
 	else:
-		pwc = [filters.get("fiscal_year")+" (Qty):Float:120", filters.get("fiscal_year")+" (Amt):Currency:120"]
+		pwc = [filters.get("fiscal_year") + " (Qty):Float:120", 
+			filters.get("fiscal_year") + " (Amt):Currency:120"]
 		query_details = " SUM(t2.qty), SUM(t1.grand_total),"
 
 	query_details += 'SUM(t2.qty), SUM(t1.grand_total)'
 	return pwc, query_details
-	
-def get_monthly_conditions(month_list, month_idx, trans_date, pwc, query_details):
-	pwc += [month_list[month_idx] + ' (Qty):Float:120', 
-		month_list[month_idx] + ' (Amt):Currency:120']
 
-	query_details += """
-		Sum(IF(MONTH(t1.%(trans_date)s)= %(mon_num)s, t2.qty, NULL)),
-		SUM(IF(MONTH(t1.%(trans_date)s)= %(mon_num)s, t1.grand_total, NULL)),
-	""" % {"trans_date": trans_date, "mon_num": cstr(month_idx+1)}
-	
+def get_period_wise_columns(bet_dates, period, pwc):
+	if period == 'Monthly':
+		pwc += [get_mon(bet_dates[0]) + " (Qty):Float:120", 
+			get_mon(bet_dates[0]) + " (Amt):Currency:120"]
+	else:
+		pwc += [get_mon(bet_dates[0]) + "-" + get_mon(bet_dates[1]) + " (Qty):Float:120", 
+			get_mon(bet_dates[0]) + "-" + get_mon(bet_dates[1]) + " (Amt):Currency:120"]
+
+def get_period_wise_query(bet_dates, trans_date, query_details):
+	query_details += """SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.qty, NULL)), 
+					SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t1.grand_total, NULL)),
+				""" % {"trans_date": trans_date, "sd": bet_dates[0],"ed": bet_dates[1]}
 	return query_details
 
-def basedon_wise_colums_query(based_on, trans):
-	sup_tab = ''
+def get_period_date_ranges(period, fiscal_year):
+  from dateutil.relativedelta import relativedelta
 
+  year_start_date = webnotes.conn.get_value("Fiscal Year", fiscal_year, "year_start_date")
+  increment = {
+    "Monthly": 1,
+    "Quarterly": 3,
+    "Half-Yearly": 6,
+    "Yearly": 12
+  }.get(period)
+
+  period_date_ranges = []
+  for i in xrange(1, 13, increment): 
+    period_end_date = year_start_date + relativedelta(months=increment, days=-1)
+    period_date_ranges.append([year_start_date, period_end_date])
+    year_start_date = period_end_date + relativedelta(days=1)
+
+  return period_date_ranges
+
+def get_period_month_ranges(period, fiscal_year):
+	from dateutil.relativedelta import relativedelta
+	period_month_ranges = []
+
+	for start_date, end_date in get_period_date_ranges(period, fiscal_year):
+		months_in_this_period = []
+		while start_date <= end_date:
+			months_in_this_period.append(start_date.strftime("%B"))
+			start_date += relativedelta(months=1)
+		period_month_ranges.append(months_in_this_period)
+
+	return period_month_ranges
+
+def based_wise_colums_query(based_on, trans):
+	based_on_details = {}
+
+	# based_on_cols, based_on_select, based_on_group_by, addl_tables
 	if based_on == "Item":
-		bon = ["Item:Link/Item:120", "Item Name:Data:120"]
-		query_details = "t2.item_code, t2.item_name," 
-		based = 't2.item_code'
+		based_on_details["based_on_cols"] = ["Item:Link/Item:120", "Item Name:Data:120"]
+		based_on_details["based_on_select"] = "t2.item_code, t2.item_name," 
+		based_on_details["based_on_group_by"] = 't2.item_code'
+		based_on_details["addl_tables"] = ''
 
 	elif based_on == "Item Group":
-		bon = ["Item Group:Link/Item Group:120"]
-		query_details = "t2.item_group," 
-		based = 't2.item_group'
+		based_on_details["based_on_cols"] = ["Item Group:Link/Item Group:120"]
+		based_on_details["based_on_select"] = "t2.item_group," 
+		based_on_details["based_on_group_by"] = 't2.item_group'
+		based_on_details["addl_tables"] = ''
 
 	elif based_on == "Customer":
-		bon = ["Customer:Link/Customer:120", "Territory:Link/Territory:120"]
-		query_details = "t1.customer_name, t1.territory, "
-		based = 't1.customer_name'
+		based_on_details["based_on_cols"] = ["Customer:Link/Customer:120", "Territory:Link/Territory:120"]
+		based_on_details["based_on_select"] = "t1.customer_name, t1.territory, "
+		based_on_details["based_on_group_by"] = 't1.customer_name'
+		based_on_details["addl_tables"] = ''
 
 	elif based_on == "Customer Group":
-		bon = ["Customer Group:Link/Customer Group"]
-		query_details = "t1.customer_group,"
-		based = 't1.customer_group'
-	
+		based_on_details["based_on_cols"] = ["Customer Group:Link/Customer Group"]
+		based_on_details["based_on_select"] = "t1.customer_group,"
+		based_on_details["based_on_group_by"] = 't1.customer_group'
+		based_on_details["addl_tables"] = ''
+
 	elif based_on == 'Supplier':
-		bon = ["Supplier:Link/Supplier:120", "Supplier Type:Link/Supplier Type:120"]
-		query_details = "t1.supplier, t3.supplier_type,"
-		based = 't1.supplier'
-		sup_tab = '`tabSupplier` t3',
+		based_on_details["based_on_cols"] = ["Supplier:Link/Supplier:120", "Supplier Type:Link/Supplier Type:140"]
+		based_on_details["based_on_select"] = "t1.supplier, t3.supplier_type,"
+		based_on_details["based_on_group_by"] = 't1.supplier'
+		based_on_details["addl_tables"] = ',`tabSupplier` t3'
 	
 	elif based_on == 'Supplier Type':
-		bon = ["Supplier Type:Link/Supplier Type:120"]
-		query_details = "t3.supplier_type,"
-		based = 't3.supplier_type'
-		sup_tab ='`tabSupplier` t3',
+		based_on_details["based_on_cols"] = ["Supplier Type:Link/Supplier Type:140"]
+		based_on_details["based_on_select"] = "t3.supplier_type,"
+		based_on_details["based_on_group_by"] = 't3.supplier_type'
+		based_on_details["addl_tables"] =',`tabSupplier` t3'
 
 	elif based_on == "Territory":
-		bon = ["Territory:Link/Territory:120"]
-		query_details = "t1.territory,"
-		based = 't1.territory'
+		based_on_details["based_on_cols"] = ["Territory:Link/Territory:120"]
+		based_on_details["based_on_select"] = "t1.territory,"
+		based_on_details["based_on_group_by"] = 't1.territory'
+		based_on_details["addl_tables"] = ''
 
 	elif based_on == "Project":
 		if trans in ['Sales Invoice', 'Delivery Note', 'Sales Order']:
-			bon = ["Project:Link/Project:120"]
-			query_details = "t1.project_name,"
-			based = 't1.project_name'
+			based_on_details["based_on_cols"] = ["Project:Link/Project:120"]
+			based_on_details["based_on_select"] = "t1.project_name,"
+			based_on_details["based_on_group_by"] = 't1.project_name'
+			based_on_details["addl_tables"] = ''
 		elif trans in ['Purchase Order', 'Purchase Invoice', 'Purchase Receipt']:
-			bon = ["Project:Link/Project:120"]
-			query_details = "t2.project_name,"
-			based = 't2.project_name'
+			based_on_details["based_on_cols"] = ["Project:Link/Project:120"]
+			based_on_details["based_on_select"] = "t2.project_name,"
+			based_on_details["based_on_group_by"] = 't2.project_name'
+			based_on_details["addl_tables"] = ''
 		else:
 			webnotes.msgprint("Project-wise data is not available for Quotation", raise_exception=1)
 
-	return bon, query_details, based, sup_tab
+	return based_on_details
 
 def group_wise_column(group_by):
 	if group_by:
diff --git a/patches/june_2013/p05_remove_search_criteria_reports.py b/patches/june_2013/p05_remove_search_criteria_reports.py
new file mode 100644
index 0000000..48a8221
--- /dev/null
+++ b/patches/june_2013/p05_remove_search_criteria_reports.py
@@ -0,0 +1,24 @@
+# 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
+
+def execute():
+	try:
+		webnotes.conn.sql("""delete from `tabSearch Criteria` where ifnull(standard, 'No') = 'Yes'""")
+	except Exception, e:
+		pass
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index a5c4d80..dc489f6 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -245,4 +245,5 @@
 	"patches.june_2013.p05_remove_unused_doctypes",
 	"patches.june_2013.p06_drop_unused_tables",
 	"patches.june_2013.p08_shopping_cart_settings",
+	"patches.june_2013.p05_remove_search_criteria_reports",
 ]
\ No newline at end of file
diff --git a/patches/september_2012/repost_stock.py b/patches/september_2012/repost_stock.py
index 9720701..deb2186 100644
--- a/patches/september_2012/repost_stock.py
+++ b/patches/september_2012/repost_stock.py
@@ -22,7 +22,7 @@
 	i=0
 	for d in res:
 	    try:
-	        update_entries_after({ "item_code": d[0], "warehouse": d[1]	})
+			update_entries_after({ "item_code": d[0], "warehouse": d[1]})
 	    except:
 	        pass
 	    i += 1
diff --git a/public/js/complete_setup.js b/public/js/complete_setup.js
index f0b21c8..37c2fba 100644
--- a/public/js/complete_setup.js
+++ b/public/js/complete_setup.js
@@ -75,12 +75,17 @@
 			if(!data) return;
 			$(this).set_working();
 			$c_obj('Setup Control','setup_account',data,function(r, rt){
-				sys_defaults = r.message;
-				user_fullname = r.message.user_fullname;
-				wn.boot.user_info[user].fullname = user_fullname;
-				d.hide();
-				$('header').toggle(true);
-				wn.container.wntoolbar.set_user_name();
+				if(!r.exc) {
+					sys_defaults = r.message;
+					user_fullname = r.message.user_fullname;
+					wn.boot.user_info[user].fullname = user_fullname;
+					d.hide();
+					$('header').toggle(true);
+					wn.container.wntoolbar.set_user_name();
+					
+					setTimeout(function() { window.location.reload(); }, 3000);
+				}
+				
 			});
 		};
 		
diff --git a/public/js/purchase_trends_filters.js b/public/js/purchase_trends_filters.js
index e994a47..117b9de 100644
--- a/public/js/purchase_trends_filters.js
+++ b/public/js/purchase_trends_filters.js
@@ -4,7 +4,7 @@
 			"fieldname":"period",
 			"label": "Period",
 			"fieldtype": "Select",
-			"options": ["Monthly", "Quarterly", "Half-yearly", "Yearly"].join("\n"),
+			"options": ["Monthly", "Quarterly", "Half-Yearly", "Yearly"].join("\n"),
 			"default": "Monthly"
 		},
 		{
diff --git a/public/js/sales_trends_filters.js b/public/js/sales_trends_filters.js
index 14dcbe3..f461d08 100644
--- a/public/js/sales_trends_filters.js
+++ b/public/js/sales_trends_filters.js
@@ -4,7 +4,7 @@
 			"fieldname":"period",
 			"label": "Period",
 			"fieldtype": "Select",
-			"options": ["Monthly", "Quarterly", "Half-yearly", "Yearly"].join("\n"),
+			"options": ["Monthly", "Quarterly", "Half-Yearly", "Yearly"].join("\n"),
 			"default": "Monthly"
 		},
 		{
diff --git a/selling/doctype/sales_order/sales_order.js b/selling/doctype/sales_order/sales_order.js
index 062130a..d8aab21 100644
--- a/selling/doctype/sales_order/sales_order.js
+++ b/selling/doctype/sales_order/sales_order.js
@@ -112,7 +112,7 @@
 					'contact_person', 'territory', 'customer_group']);
 				if(doc.customer) get_server_fields('get_shipping_address', doc.customer, '', doc, dt, dn, 0);
 			}			
-			cur_frm.refresh();
+			cur_frm.refresh_fields();
 		}
 	} 
 
diff --git a/selling/page/selling_home/selling_home.js b/selling/page/selling_home/selling_home.js
index 87e12db..73cc718 100644
--- a/selling/page/selling_home/selling_home.js
+++ b/selling/page/selling_home/selling_home.js
@@ -137,11 +137,6 @@
 				"label":wn._("Sales Analytics"),
 				page: "sales-analytics"
 			},
-			{
-				"label":wn._("Trend Analyzer"),
-				route: "Report/Profile/Trend Analyzer",
-				doctype: "Sales Order"
-			},
 		]
 	},
 	{
@@ -190,6 +185,10 @@
 				route: "query-report/Sales Order Trends",
 				doctype: "Sales Order"
 			},
+			{
+				"label":wn._("Pending SO Items For Purchase Request"),
+				route: "query-report/Pending SO Items For Purchase Request"
+			},
 		]
 	}
 ]
diff --git a/buying/report/item_wise_last_purchase_rate/__init__.py b/selling/report/pending_so_items_for_purchase_request/__init__.py
similarity index 100%
rename from buying/report/item_wise_last_purchase_rate/__init__.py
rename to selling/report/pending_so_items_for_purchase_request/__init__.py
diff --git a/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.txt b/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.txt
new file mode 100644
index 0000000..e0c450a
--- /dev/null
+++ b/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.txt
@@ -0,0 +1,22 @@
+[
+ {
+  "creation": "2013-06-21 16:46:45", 
+  "docstatus": 0, 
+  "modified": "2013-06-21 16:55:54", 
+  "modified_by": "Administrator", 
+  "owner": "Administrator"
+ }, 
+ {
+  "doctype": "Report", 
+  "is_standard": "Yes", 
+  "name": "__common__", 
+  "query": "select \n so_item.item_code as \"Item Code:Link/Item:120\",\n so_item.item_name as \"Item Name::120\",\n so_item.description as \"Description::120\",\n so.`name` as \"S.O. No.:Link/Sales Order:120\",\n so.`transaction_date` as \"Date:Date:120\",\n mr.name as \"Material Request:Link/Material Request:120\",\n so.customer as \"Customer:Link/Customer:120\",\n so.territory as \"Terretory:Link/Territory:120\",\n sum(so_item.qty) as \"SO Qty:Float:100 \",\n sum(mr_item.qty) as \"Requested Qty:Float:100\"\nfrom\n `tabSales Order` so, `tabSales Order Item` so_item, \n `tabMaterial Request` mr, `tabMaterial Request Item` mr_item\nwhere\n so_item.`parent` = so.`name` and mr_item.sales_order_no = so.name\n and mr_item.parent = mr.name \n and so.docstatus = 1 and so.status != \"Stopped\" \n and mr.docstatus = 1 and mr.status != \"Stopped\"\ngroup by so.name, so_item.item_code\norder by so.name desc, so_item.item_code asc", 
+  "ref_doctype": "Sales Order", 
+  "report_name": "Pending SO Items For Purchase Request", 
+  "report_type": "Query Report"
+ }, 
+ {
+  "doctype": "Report", 
+  "name": "Pending SO Items For Purchase Request"
+ }
+]
\ No newline at end of file
diff --git a/selling/report/quotation_trends/quotation_trends.py b/selling/report/quotation_trends/quotation_trends.py
index c6a54c7..d08e0f8 100644
--- a/selling/report/quotation_trends/quotation_trends.py
+++ b/selling/report/quotation_trends/quotation_trends.py
@@ -21,11 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Quotation"
-	tab = ["tabQuotation","tabQuotation Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/selling/report/sales_order_trends/sales_order_trends.py b/selling/report/sales_order_trends/sales_order_trends.py
index d556a58..455fbd4 100644
--- a/selling/report/sales_order_trends/sales_order_trends.py
+++ b/selling/report/sales_order_trends/sales_order_trends.py
@@ -21,14 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Sales Order"
-	tab = ["tabSales Order","tabSales Order Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 	
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-	
-	if not data :
-		webnotes.msgprint("Data not found for selected criterias")
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/setup/doctype/setup_control/setup_control.py b/setup/doctype/setup_control/setup_control.py
index f8290da..098417f 100644
--- a/setup/doctype/setup_control/setup_control.py
+++ b/setup/doctype/setup_control/setup_control.py
@@ -98,7 +98,7 @@
 		self.create_email_digest()
 
 		webnotes.clear_cache()
-		msgprint("Company setup is complete. Please refresh the page before continuing.")
+		msgprint("Company setup is complete. This page will be refreshed in a moment.")
 		
 		import webnotes.utils
 		user_fullname = (args.get('first_name') or '') + (args.get('last_name')
@@ -262,4 +262,4 @@
 				"parent_territory": root_territory,
 				"is_group": "No"
 			}).insert()
-		
\ No newline at end of file
+		
diff --git a/startup/report_data_map.py b/startup/report_data_map.py
index 501db4f..068e470 100644
--- a/startup/report_data_map.py
+++ b/startup/report_data_map.py
@@ -47,8 +47,8 @@
 		"order_by": "lft"
 	},
 	"GL Entry": {
-		"columns": ["name", "account", "posting_date", "cost_center", "debit", "credit", "is_opening",
-			"company", "voucher_type", "voucher_no", "remarks"],
+		"columns": ["name", "account", "posting_date", "cost_center", "debit", "credit", 
+			"is_opening", "company", "voucher_type", "voucher_no", "remarks"],
 		"conditions": ["ifnull(is_cancelled, 'No')='No'"],
 		"order_by": "posting_date, account",
 		"links": {
diff --git a/stock/doctype/delivery_note/delivery_note.js b/stock/doctype/delivery_note/delivery_note.js
index e1b23f0..ac2c4e9 100644
--- a/stock/doctype/delivery_note/delivery_note.js
+++ b/stock/doctype/delivery_note/delivery_note.js
@@ -64,10 +64,7 @@
 			if(doc.sales_order_no) {					
 				unhide_field(['customer_address','contact_person','territory','customer_group']);														
 			}			
-			
-			refresh_many(['delivery_note_details', 'customer', 'customer_address',
-			 	'contact_person', 'customer_name', 'address_display', 'contact_display',
-			 	'contact_mobile', 'contact_email', 'territory', 'customer_group']);
+			cur_frm.refresh_fields();
 		}
 	} 
  $c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback); 
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.js b/stock/doctype/purchase_receipt/purchase_receipt.js
index 0f656c4..1f32b78 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -97,11 +97,9 @@
 // Get Purchase Order Button
 // -----------------
 cur_frm.cscript.pull_purchase_order_details = function(doc, dt, dn) {
-	var callback = function(r,rt) { 
-		//unhide_field(['supplier_address','contact_person','supplier_name','address_display', 'contact_display', 'contact_mobile','contact_email']);				
-		refresh_many(['supplier','supplier_address','contact_person', 'supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email', 'purchase_receipt_details', 'purchase_tax_details']);
-	}
-	$c_obj(make_doclist(dt,dn),'get_po_details','',callback);
+	$c_obj(make_doclist(dt,dn),'get_po_details','',function(r,rt) { 
+		cur_frm.refresh_fields();
+	});
 }
 
 
diff --git a/stock/report/delivery_note_trends/delivery_note_trends.py b/stock/report/delivery_note_trends/delivery_note_trends.py
index 369b6a3..9878ecc 100644
--- a/stock/report/delivery_note_trends/delivery_note_trends.py
+++ b/stock/report/delivery_note_trends/delivery_note_trends.py
@@ -21,14 +21,8 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Delivery Note"
-	tab = ["tabDelivery Note","tabDelivery Note Item"]
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, conditions)
 	
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
-	
-	if not data :
-		webnotes.msgprint("Data not found for selected criterias")
-
-	return details["columns"], data 
\ No newline at end of file
+	return conditions["columns"], data 
\ No newline at end of file
diff --git a/stock/report/purchase_receipt_trends/purchase_receipt_trends.py b/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
index bd089fa..56c0023 100644
--- a/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
+++ b/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
@@ -21,14 +21,11 @@
 def execute(filters=None):
 	if not filters: filters ={}
 	data = []
-
 	trans = "Purchase Receipt"
-	tab = ["tabPurchase Receipt","tabPurchase Receipt Item"]
-
-	details = get_columns(filters, trans)
-	data = get_data(filters, tab, details)
+	conditions = get_columns(filters, trans)
+	data = get_data(filters, tab, conditions)
 	
 	if not data :
 		webnotes.msgprint("Data not found for selected criterias")
 
-	return details["columns"], data  
\ No newline at end of file
+	return conditions["columns"], data  
\ No newline at end of file