/*
 *
 * search.js: client-side support for nbb search.
 *
*/

/*
 * nbblib__search_focus(): called when search text box has focus
*/
function nbblib__search_focus() {
	var s = $("sqry").value;
	if (s == "search") {
		$("sqry").value = "";
	} /* else leave it! */
}

/*
 * nbblib__search(): called when the search box [GO] button is clicked
*/
function nbblib__search() {
	nbblib__search_se(0,10, "center_column_content");
}

function nbblib__search_main() {
	nbblib__search_se(0,10, "nb_sr", "std_results");
}

function nbblib__search_lq_sort(s_by) {
	var r_s = $("nbb_sr_rs").innerHTML;
	var r_e = $("nbb_sr_re").innerHTML;
	var c_el = $("nbb__search_el").innerHTML;
	var r_tpl = "";
	if ($("nbb__search_tpl")) {
		r_tpl = $("nbb__search_tpl").innerHTML;
	}
	nbblib__search_se(r_s, r_e, c_el, r_tpl, s_by);
}

/*
 * nbblib__search_se_dyn( result_page ):
 *
 * dynamically show different sections of search results based on the page requested
 *
*/
function nbblib__search_se_dyn(rp) {
	var i=0;
	
	/* alt method?: (by row number instead of pre-paged?
	 * rp: ex 1 -> from rp*10-10 to (rp+1)*10)-1
	*/

	/* hide all rows */
	var tx = $("dyn_search_results")
	if (!tx) return;
	var x = tx.rows;	
	for(i=1;i<x.length;i++) {
		x[i].style.display = 'none';
	} /* for */
	
	/* show page rows */
	var tr_els = document.getElementsByClassName('sr_page_' + rp, document);
	for(i=0; i < tr_els.length ; i++) {
		var el = tr_els[i];
		el.style.display = '';
	}
	if ($("sr_cur_pg")) {
		$("sr_cur_pg").innerHTML = rp;
	}
	
	/* reset std_pager.tpl elements */
	var pg_els = document.getElementsByClassName('sr_pager_all', document);
	for(i=0; i < pg_els.length; i++) {
		el = pg_els[i];
		var pnum = (el.id+"").replace(/sr_pager_/, "");
		if (el.id == "sr_pager_" + rp) {
			el.innerHTML = "<B>" + pnum + "</B>";
		} else {
			el.innerHTML = "" + pnum;
		}
	}
}

/*
 * nbblib__searchable ( search_terms, searchable_group, destination_element )
 *
 * initiates a search through generic search infrastructure (nbb_searchable) via
 *   search, find wslib call.
*/
function nbblib__searchable_main(g, d_el, tab_name) {
	var st = $F("sqry");
	nbblib__searchable(st, g, d_el, "std_searchable", tab_name);
}

function nbblib__searchable(st, g, c_el, tpl, tab_name) {
	var u = "/nbblib/ws/wslib.php?s=search&f=find" +
				"&g=" + g +
				"&r=h" +
				"&tpl=" + tpl +
				"&tab=" + tab_name + 
				"&st=" + st;
	nbb_aj_start();
	new Ajax.Request(u, {
			method: 'get',
			onSuccess: function(t) {
				/* clear ajax work div */
				nbb_aj_stop();

				/* set center content column to response */
				$(c_el).innerHTML = "";
				$(c_el).innerHTML = t.responseText;
				/* show! */
				$(c_el).style.display = '';
				
				/* pop the number of results returned into the tab text */
				if (tab_name) {
					$(tab_name).firstChild.innerHTML = $(tab_name).firstChild.innerHTML + " (" + $(tab_name + "_c").innerHTML + ")";
				}
			} /* onSuccess */
		} /* params */
	); /* Ajax.Request */
	
} /* nbblib__searchable */

/*
 * nbblib__search_se(result_start_position, result_end_position):
 * 
 * requests a local start and stop point for returned results within the
 *  global result set.
 *
 * c_el: content element id to place results data into
 *
*/
function nbblib__search_se(r_s, r_e, c_el, a_tpl, c_sort) {

	/* detect/provide default destination content element endpoint */
	if (!c_el) {
		if ($("nbb__search_el")) {
			c_el = $("nbb__search_el").innerHTML;
		}
	}

	/* hide main content pane */
	/* disabled for now, it will just get "pushed" down if "dashboard" results are utilized */
	/*
	if (c_el !== "center_content") {
		$("center_content").style.display = 'none';
	}
	*/

	var st = $F("sqry");

	/* reset value to be friendly, focus nukes it */
	$("sqry").value = st;
	
	/* static span element in std_lh_column above search box.  shady, but effective. 
	 * note: if you are using this code for a different affiliateID, but still getting
	 *  an $afid of "470", then one of your template controllers (tpl3col.php, tpl3col_b.php,
	 *  etc.) is not setting the affiliateID from the request object when filling smarty with
	 *  the "standard" data package for a client web request (via the nbb controller).
	 *
	 *  the right way to "fix" this would be to detect if $request->get("affiliateID") is
	 *   "legal" (in that request is an object, and get is a function of it), and use the
	 *   value if it exists; otherwise default to something you catch here (like -1, not 407).
	*/
	var afid = $("nbb__af_id_static").innerHTML;
	
	var g = "products";
	var r = "h";

	/* allow specifying an alternate render template, but default to std.tpl */
	var tpl = "std";
	/* TODO: this is a hack i will have to clean up */
	if ($("nbb__search_tpl")) {
		a_tpl = $("nbb__search_tpl").innerHTML;
	}
	if (!a_tpl) {
		tpl = "std";
		alert("TODO: code still using std.tpl for search results?");
	} else {
		tpl = a_tpl;
	}
	
	/* sort params: brand, type, price, name, bestseller, relevance */
	var r_sort = "relevance"; /* default sort parameter */
	/* TODO: more hackish code; clean it up. */
	if (!c_sort && $("nbb_sr_sort")) {
		r_sort = $("nbb_sr_sort").innerHTML;
	} else if (c_sort != "" && c_sort != "undefined") {
		r_sort = c_sort;
	}
	if (r_sort == "") {
		r_sort = "relevance";
	}
	if ($("nbb_sr_sort")) { /* save last sort param so subsequent navigations work as expected */
		$("nbb_sr_sort").innerHTML = r_sort;
	}

	var catid_filter = $("catid_filter").innerHTML;
	if (catid_filter != "-1") {
		r_sort = "price";
	}

	var u = "/nbblib/ws/wslib.php?s=search&f=search&afid=" + afid +
				"&g=" + g +
				"&r=" + r +
				"&tpl=" + tpl +
				"&r_s=" + r_s +
				"&r_e=" + r_e +
				"&srt=" + r_sort +
				"&catid=" + catid_filter +
				"&st=" + st;

	/* update local tracking elements for r_s, r_e, u */
	if ($("nbb_sr_rs") && $("nbb_sr_re") && $("nbb_sr_lq")) {
		$("nbb_sr_rs").innerHTML = r_s;
		$("nbb_sr_re").innerHTML = r_e;
		$("nbb_sr_lq").innerHTML = u; /* last query */
	}

	nbb_aj_start();

	new Ajax.Request(u, {
			method: 'get',
			onSuccess: function(t) {
				/* clear ajax work div */
				nbb_aj_stop();

				/* set center content column to response */
				$(c_el).innerHTML = "";
				$(c_el).innerHTML = t.responseText;
				/* show! */
				$(c_el).style.display = '';
				
				/* ding the client-side table sort code to do it's magic */
				sortables_init();
				/* update the prices laissez-faire for the new results per the current
				 *  quickquote settings (so expectation of price is preserved)
				*/
				nbb__s_upd(); /* this function is dynamically generated in d_size_search.tpl */
				/* show the first page of results automatically (since paging is client-side) */
				nbblib__search_se_dyn(1);
				qq__x_regreen();
				
				/* pop the number of results returned into the tab text */
				$("tab_products").firstChild.innerHTML = "Products (" + $("sr_productcount").innerHTML + ")";

				var catid_filter = $("catid_filter").innerHTML;
				if (catid_filter != "-1") { /* auto sort by price on category filtered searches (see more <product type>) */
						setTimeout('ts_resortTable($("sr_hdr_price").childNodes[0], 3);', 500);
				}

			} /* onSuccess */
		} /* params */
	); /* Ajax.Request */
	
} /* qq_update */

/*
 * nbblib_search_pop_dyn: called when "return to previous page" link 
 *  is clicked from dynamic search results
*/

function nbblib_search_pop_dyn() {
	nbb_hide_dyn_c(); 
	$("center_content").style.display = "";
}

/*
 * shady; this "re-greens" the table so the alternating row colors are right after a sort.
 *
 * now extra-shady: since sorttable "re-greens" every time the table is sorted, we also have to
 *  recompute & reapply the sr_page_[n] class to each row.  this is getting a little too shifty..
 *
*/
function qq__x_regreen() {
	var c1 = "#c4dfa0";
	var c2 = "#ffffff";
	var ct = 0;
	
	var rc = 0;
	var pc = 1;

	var tx = $("dyn_search_results")
	if (!tx) return; /* ignore other requests for "re-greening"...  */

	var x = tx.rows;

	/* re-page */
	for(i=1;i<x.length;i++) {
		if (rc == 10) {
			rc = 0;
			pc++;
		}
		rc++;
		x[i].className = "sr_page_" + pc;
	}
	
	/* re-green */
	for(i=1;i<x.length;i++) {
		if (ct==0) {
			col=c1; ct=1;
		} else {
			col=c2; ct=0;
		}
		x[i].style.backgroundColor = col;
	} /* for */
	
	/* ding the page-display mechanism to refresh our client's view of the result set 
	 *  now that the rows are re-ordered, re-classed, and re-greened.
	*/
	if ($("sr_cur_pg")) {
		var sr_cp = $("sr_cur_pg").innerHTML;
		nbblib__search_se_dyn(sr_cp);
	}
}



