//<![CDATA[

	    google.load("gdata", "1.x");
	    var baseService;

	    // Set to 1 to enable debugging info at bottom of page
	    var DEBUG_ON = 1;
		var customerid = '5898518';  //betterwalking

	    // Global refinement vars
	    var sortOrder = 'price_low';
	    var priceMatch = '';
	    var categoryMatch = '';
	    var brandMatch = '';
	    var queryString = '';
	    var resultsLimit = 15;
	    var currentPage = 1;


		
		

		// This callback will run when the snippets feed query has complete
		// Customize based on which attributes you want to display
	  	var handleSnippetsFeed = function(result) {

		//fire analytics tracking event
		pageTracker._trackPageview("/searchResult");
		
	   		var entries = result.feed.entry;
	   		var totalResults = result.feed.getTotalResults().getValue();
			var	totalPages = Math.min(Math.ceil(totalResults / 15),8);
			var pagingText = '';

	   		//document.getElementById("foundText").innerHTML = 'Your search for <strong>' + queryString + '</strong> produced <strong>' + totalResults + '</strong> items.' + totalPages;
			
			for (var i = 1; i <= totalPages; i++) {
				//pagingText += '<li class="pageNumber"><a href="javascript:void(0);"  onClick="pagesubmit(' + i + ');">' + i + '</a></li><li class="pipe">|</li>';
				pagingText += '<a href="javascript:void(0);"  onClick="pagesubmit(' + i + ');">' + i + '</a>&nbsp |&nbsp';

			}

			//document.getElementById("pagenav").innerHTML = pagingText;

			//error message if no results
			if (totalResults != 0) {
			var ret_str = "<h1>Search Results</h1><table>";
			} else {
				var ret_str = "<h1>Sorry! No Results Found</h1><p><strong>Please try another search term, or use the navigation to the left.</strong></p><table>";
			}

	   		for (var i = 0, item; item = entries[i]; i++) {
	    		var title = item.getTitle().getText();
	    		var description = item.getContent().getText();
	    		var href = item.getLink('alternate').getHref();
	    		var img_obj = item.getAttribute('image_link');
				var thumb;
			    thumb = item.getAttribute('image_link').getValue();

	    		var price =  item.getAttribute('price').getValue();
				
				//remove unwanted info from title and price strings
				price = price.replace('usd','');
				href = href.replace(/\?utm.*$/, '');				

				//if (i % 3 == 0) {
					ret_str = ret_str + "<tr>";
				//	col = 1;
				//}
			
			ret_str = ret_str +  '<td xwidth="20">' + '<div class="subcats">'+
					  '<ul class="subcatItem">'+
					  //'<li>' + i % 3 + '</li>'+
					  '<a href="' + href + '">'+
					     '<img src="' + thumb + '" width="200" height="129" alt="' + title + '" title="' + title + '" border="0" /></a><br/></td><td>'+
					  '<a href="' + href + '">' + title + ' </a><br/>'+ description + ' <br/><p class="price">$' + price + ' <a href="' + href + '">Buy &raquo;</p>'
					  '</td><td>'+

					  '</ul></div>' + '</td>'

			    //if (i % 3 == 2) {
			    	ret_str = ret_str + "</tr>";
			    //}

	  		}
			
			ret_str = ret_str + "</table>"

			PRINT (ret_str);
			
		};

		// This callback will run when the snippets feed query has completed
		// You may need to customize the attribute names depending on your customer - for apple we use product_type & brand
	  	var handleAttributesFeed = function(result) {
	   		var entries = result.feed.entry;
			var catStr = '<ul>';
			var brandStr = '';

			for (var i = 0, item; item = entries[i]; i++) {
				var t = item.getAttribute();
				var attribs = t.getValues();
				if (t.name == 'product type' || t.name == 'brand') {
					for (var j = 0, attrib; attrib = attribs[j]; j++) {
						if (t.name == 'product type') {
							catStr += '<li><a href="javascript:void(0)" onClick="javascript:categorysubmit(\'' + attrib.getValue() + '\')">' + attrib.getValue() + ' (' + attrib.getCount() + ')</a></li>';
						} else if (t.name == 'brand') {
							brandStr += '<a href="javascript:void(0)" onClick="javascript:brandsubmit(\'' + attrib.getValue() + '\')">' + attrib.getValue() + ' (' + attrib.getCount() + ')</a><br/>';
						}

					}
				}
			}

			if (categoryMatch != '') {
				catStr += '<li><a href="javascript:void(0)" onClick="javascript:categorysubmit(\'\')">View all categories</a></li>';
			}

			if (brandMatch != '') {
				brandStr += '<a href="javascript:void(0)" onClick="javascript:brandsubmit(\'\')">View all brands</a><br/>';
			}

			
			
			catStr += '</ul>';
			brandStr += '';
			//document.getElementById("categoryList").innerHTML = catStr;
			//document.getElementById("brandList").innerHTML = brandStr;
			
			document.getElementById("brandList").innerHTML = "<table> <tbody> <tr> <td valign=\"top\"> <strong>Refine by brand:</strong><br>" + brandStr + "</td></tr></tbody></table>";

	   	};

		// This callback will run if getSnippetFeed throws any errors
		var handleError = function(error) {
			DEBUG(error.cause ? error.cause.statusText : error.message);
		};

		// This is the actual meat - Here we construct the call to Base using the GDATA API.
		// We make two requrests:
		//  - One to fetch the search results
		//  - The other to get the attribute counts & buckets
	    function getMyFeed(queryString) {
	    	baseService = new google.gdata.gbase.GoogleBaseService('BetterWalking-Demo');

			var query = new google.gdata.gbase.SnippetsQuery('http://www.google.com/base/feeds/snippets');
			query.setFullTextQuery(queryString);
			query.setBq('[customer id:' + customerid + ']' + priceMatch + brandMatch + categoryMatch);
			
			

			if (sortOrder == 'match') {
				query.setOrderby('relevancy');
				query.setSortorder('descending');
			} else if (sortOrder == 'price_low') {
				query.setOrderby('price(float usd)');
				query.setSortorder('ascending');
			} else if (sortOrder == 'price_high') {
				query.setOrderby('price(float usd)');
				query.setSortorder('descending');
			} else if (sortOrder == 'name') {
				query.setOrderby('title(text)');
				query.setSortorder('ascending');
			}

			query.setMaxResults(resultsLimit);
			query.setStartIndex(((currentPage - 1 ) * 15) +1);
			baseService.getSnippetsFeed(query, handleSnippetsFeed, handleError);

			var queryUri = query.getUri();
			DEBUG('<b>Query: <a href="' + queryUri + '" target="_new">' + queryUri + '</a></b>');

			// Get Attributes
			var attributes = new google.gdata.gbase.AttributesQuery('http://www.google.com/base/feeds/attributes');
			attributes.setFullTextQuery(queryString);
            attributes.setMaxValues(30);
			attributes.setBq('[customer id:' + customerid + ']'+ priceMatch + brandMatch + categoryMatch);
			baseService.getAttributesFeed(attributes, handleAttributesFeed, handleError);

			DEBUG(attributes.getUri());
			
			var ele = document.getElementById("priceList");
    		ele.style.display = "block";
		
			
		}

	// Called when we click on a price refinement
	function pricesubmit(price) {
		if (price == 0) {
			priceMatch = '[price < 10.00 USD]';
		} else if (price == 20) {
			priceMatch = '[price:10.0..20.00 USD]';
		} else if (price == 40) {
			priceMatch = '[price:20.0..40.00 USD]';
		} else if (price == 100) {
			priceMatch = '[price:40.0..100.00 USD]';
		} else if (price == 101) {
			priceMatch = '[price >= 100.0 USD]';
		}
		document.getElementById("main_content").innerHTML = '';

		getMyFeed(queryString);
	}

	// Called when we click on a category refinement
	function categorysubmit(form,category) {
		if (category != '') {
			categoryMatch = '[category type:' + category + ']';
		} else {
			categoryMatch = '';
		}
		document.getElementById("main_content").innerHTML = '';
		getMyFeed(form.q.value);
	}

	// Called when we click on a brand refinement
	function brandsubmit(brand) {
		if (brand != '') {
			brandMatch = '[brand:' + brand + ']';
		} else {
			brandMatch = '';
		}
		document.getElementById("main_content").innerHTML = '';
		getMyFeed(queryString);
	}

	function spellsubmit(form) {
		form.q.value = spell_suggestion;

		document.getElementById("module_top").innerHTML =
					'<h2>Search results: <em>' + form.q.value + '</em></h2>';
		document.getElementById("main_content").innerHTML = '';

		getMyFeed(spell_suggestion);

	}

	function pagesubmit(page) {
			currentPage = page;
			resultsLimit = 15;
			document.getElementById("main_content").innerHTML = '';
			getMyFeed(queryString);
	}


	// Called when we submit a new search term
	function formsubmit(form,order) {
		sortOrder ='price_low';
		priceMatch ='';
		categoryMatch = '';
		brandMatch = '';

		if (order != null) {
			sortOrder = order;
		}

		queryString = document.forms.search.q.value;


		//document.getElementById("module_top").innerHTML =
		//	'<h2>Search results: <em>' + document.forms.search.q.value + '</em></h2>';
		document.getElementById("main_content").innerHTML = '';


		getMyFeed(document.forms.search.q.value);
	}

	// Add search results to main_content
    function PRINT(str) {
      document.getElementById("main_content").innerHTML += str;
	  
	  
    }

	function DEBUG(str) {
		if (DEBUG_ON == 1) {
			document.getElementById("debugPanel").innerHTML += '<br>' + str;
		}
    }

	//returns true is it is an array
    function isArray(obj) {
		if (obj.constructor.toString().indexOf("Array") == -1) {
			return false;
		} else {
			return true;
		}
	}


	// Get URL Parameters
	function gup(url,name) {
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}

	
	
	
	//google.setOnLoadCallback(formsubmit());
//]]>
