// Search code //

var newcellhtml, oldcell, oldcellhtml, oldeServContent;
var rownumber = 0;
var preview = 0;
var loading = '<div class="Loading"><img src="TW_assets/images/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');
		//window.status='Search results returned.';
		//alert('Search results returned.');
	}
}

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.
		if (sm_replaced === 0) { 	
			// Need to replace content with search results.
			TW_changeStyle('eServContent','HideMe');
			MM_showHideLayers('eServContent','','hide');
			TW_changeStyle('SearchContent','ShowMe');
			sm_replaced = 1; // Content has been replaced
		}

		TW_changeStyle('SearchMatches','HideMe');
		TW_changeStyle('LoadingSearch','ShowMe');
	
		loadURL = "TW_assets/TW_search/xml/search_results.asp?Term="+document.SearchForm.Term.value;
		dsSearchMatches.setURL(loadURL);
		dsSearchMatches.loadData();
		window.status='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);
	window.status='Preview loaded.';
	
	preview = 1;
}

function updateResponse_AddtoOrder(req,thisform) {
	var returnmsg = req.xhRequest.responseText;
	var msg = '';
	TW_changeStyle('Processing','HideMe');
	if (returnmsg.indexOf("duplicate") > -1) { msg = "Error: This item is already in your order."; }
	if (returnmsg.indexOf("Error") > -1) { msg = "Error: There was a problem finding or adding this item."; }
	if (msg !== '') { alert(msg); }
	if (returnmsg.indexOf("added to order") > -1) {
		window.status='Item added to order. Reloading order summary.';
		Spry.Utils.setInnerHTML('OrderSummaryBox',loading);
		Spry.Utils.submitForm('ReloadOS', updateResponse_ReloadOS);
	}
}

function updateResponse_ReloadOS(req) {
	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 = parseFloat(row.price).toFixed(2);
	row.formattedPrice = formatCurrency(row.price);
	return row;
}

function TW_FindReplace(element,whattofind,newtext) {
	var thiselement=document.getElementById(element);
	var tags=thiselement.getElementsByTagName("span");
	for(i=0;i < tags.length; i++){
		if(tags[i].firstChild){
			if(tags[i].className == whattofind) {
				// tags[i].className = newstyle;
				tags[i].firstChild.nodeValue = newtext;
			}
		}
	}
}

function TW_AddProcess(thisform) {
	TW_changeStyle('Processing','ShowMe');
	Spry.Utils.submitForm(thisform, updateResponse_AddtoOrder);
	return false;
}