// Search code //

var newcellhtml, oldcell, oldcellhtml, oldeServContent;
var rownumber = 0;
var preview = 0;
var loading = '<div class="Loading"><img src="TW_assets/images/misc/loading.gif" alt="Loading" width="32" height="32" /></div>';


function load_dsSearchMatches(notificationType, dataSet, data) {
	//alert(notificationType);
	if (notificationType == "onPostLoad") {
		TW_changeStyle('SearchMatches','showme');
		TW_changeStyle('LoadingSearch','hideme');
	}
	if (notificationType == 'onLoadError') {
		alert("Error loading search results.");
	}
}

function TW_UpdateSearch() {
	// Are we showing the results on this page or sending to the search page?
	if (sm_gotosearchpage == 1) { // No; go to search page.
		document.SearchForm.submit();
		
	} else { // Yes; show results here.
		pageTracker._trackPageview('search');
	
		if (sm_replaced === 0) { 	
			// Need to replace content with search results.
			//TW_changeStyle('eServContent','hideme');
			//MM_showHideLayers('eServContent','','hide');
			TW_changeStyle('SearchContent','showme');
			MM_showHideLayers('SearchContent','','show');
			sm_replaced = 1; // Content has been replaced
			//alert('Content replaced');
		}

		TW_changeStyle('SearchMatches','hideme');
		TW_changeStyle('LoadingSearch','showme');
		//alert('Loading should be displayed');
	
		loadURL = "/TW_assets/TW_search/xml/search_results.asp?Term="+document.SearchForm.Term.value;
		dsSearchMatches.setURL(loadURL);
		dsSearchMatches.loadData();
		//alert('Requesting search results.');
		
		oldcell = null; oldcellhtml = null; rownumber = 0;
	}
}

function TW_TogglePreview(thiscell, source, hide) {
	var findcell = document.getElementById(thiscell); 
	if ((oldcell != thiscell)) {
		if (oldcell != '') { // Restore the old product view.
			Spry.Utils.setInnerHTML(oldcell,oldcellhtml);
			preview = 0;
		}
		// Store old HTML
		oldcell = thiscell;
		oldcellhtml = findcell.innerHTML;
		Spry.Utils.setInnerHTML(thiscell, loading);
		
		if ((thiscell == 'searchmatches_0') && (rownumber === 0)) { // Clicked on the first item
			TW_ShowPreview(thiscell,source);
		} else { // Click on some other item; wait for update.	
			function watchforchange(notifier,data) {
				if (notifier == 'onCurrentRowChanged') {
					rownumber = dsSearchMatches.getCurrentRowNumber();
					TW_ShowPreview(thiscell,source);
					dsSearchMatches.removeObserver(watchforchange);
				}
			}				
			dsSearchMatches.addObserver(watchforchange);
		}
	} else { // This cell is the old cell
		if (hide == 1) { // Going into small-mode
			Spry.Utils.setInnerHTML(oldcell,oldcellhtml);
			preview = 0;
		} else if (preview === 0) { 
			// If we're already in preview mode do nothing.  Otherwise, return to preview mode.
			// We're in preview mode if the HTML for thiscell = to the Preview cell.
			TW_ShowPreview(thiscell,source); // Show preview
		}
	}
}

function TW_ShowPreview(thiscell,source) {
	// Grab preview HTML
	var previewcell = document.getElementById(source);
	newcellhtml = previewcell.innerHTML;
	
	// Populate preview
	Spry.Utils.setInnerHTML(thiscell, newcellhtml);
	preview = 1;
	
	var exitloop = 0;
	for (i=0; i<document.forms.length; i++) {
		if (document.forms[i].id == 'AddtoOrder') {
			for(x=0; x<document.forms[i].elements.length; x++) {
				if (document.forms[i].elements[x].name == 'qty') {
					document.forms[i].elements[x].focus();
					// alert('focused on qty field');
					exitloop = 1;
					break;
				}
			}
		}
		if (exitloop == 1) { break; }
	}	
}

function updateResponse_AddtoOrder(req,thisform) {
	var returnmsg = req.xhRequest.responseText;
	var msg = '';
	TW_changeStyle('Processing','hideme');
	if (returnmsg.indexOf("item is already") > -1) { msg = "Error: This item is already in your order. You'll need to edit the quantity on the View Cart page or in Order Summary (left column)"; }
	if (returnmsg.indexOf("Error") > -1) { msg = "Error: There was a problem finding or adding this item."; }
	if (msg !== '') { alert(msg); }
	//alert(returnmsg);
	if (returnmsg.indexOf("added to order") > -1) {
		Spry.Utils.setInnerHTML('add_msg', 'Item added to order. <br />');
		Spry.Utils.submitForm('OrderSummaryUpdate', updateResponse_ReloadOS);
		pageTracker._trackPageview('item_added_to_order_search');
	}
}

function updateResponse_ReloadOS(req) {
	//alert("updateResponse_ReloadOS");
	Spry.Utils.setInnerHTML('OrderSummaryBox', req.xhRequest.responseText);
	window.status='Order summary re-loaded.';
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents); /* + '$' */
}

function myDataSetPreProcessor(ds, row, rowIndex) {
	row.formattedPrice = formatCurrency(row.price); /* row.price.toFixed(2); */
	return row;
}

function TW_AddProcess(thisform) {
	// alert("TW_AddProcess");
	TW_changeStyle('Processing','showme');
	Spry.Utils.submitForm(thisform, updateResponse_AddtoOrder);
	return false;
}

function load_dsAddCookie(notificationType, dataSet, data) {
	/*
	if (notificationType == "onPostLoad") {
		alert("Set cookie");
	}
	*/
	if (notificationType == 'onLoadError') {
		alert("Error setting cookie.  The tip may reappear.");
	}
}