var params = new Array();
params[0] = {name: 'product', query: '', page: 1, sort: '', resultsPerPage: 10, filters: [new Array(), new Array(), new Array(), new Array(), new Array(), new Array(), new Array()]};
params[1] = {name: 'article', query: '', page: 1, sort: '', resultsPerPage: 10, filters: []};

function search(query) {

	resetAllParams();

	if (!query || query.length < 1) {
		query = document.getElementById('query').value;
		if (document.getElementById('refineQuery') && document.getElementById('refineQuery').value.length > 0) {
			query += ' ' + document.getElementById('refineQuery').value;
		}
	}
	
	params[0].query = query;
	params[1].query = query;

	searchProducts(0, buildSearchParams(0), true);
	searchArticles(1, buildSearchParams(1));
}

/*
function search(feedId, params) {

	var url = 'searchSpring.php?' + params;
	
	new Ajax.Request(url,
	{
		method:'get',
		onSuccess: function(transport){
			
			var searchResult = eval('(' + transport.responseText + ')');
			
			clearSearchResults(feedId);
			
			var i;

			for (i = 0; i < searchResult.results.length; i++) {
				addSearchResult(feedId, searchResult.pagination.begin + i, searchResult.results[i]);
			}
			
			updatePagination(feedId, searchResult.pagination);
			
			// Update filters
			updateFilters(feedId, searchResult.facets);
			
			window.location.href = "#top";

			return;
		},
		onFailure: function(){
			alert('There was a problem perfoming the search...');
		}
	});
	
}

function addSearchResult(feedId, no, product) {

	var p = document.getElementById('emptyProduct').cloneNode(true);
	p.id = '';
	
	p.innerHTML = p.innerHTML.replace(/\@NUMBER/g, no);
	p.innerHTML = p.innerHTML.replace(/\@URL/g, 'http://www.bikeman.com/' + product.code + '.html');
	p.innerHTML = p.innerHTML.replace(/\@IMAGE/g, '<img src=' + product.thumbnail.unescapeHTML() + ' border=0>');
	p.innerHTML = p.innerHTML.replace(/\@NAME/g, product.name.unescapeHTML());
	p.innerHTML = p.innerHTML.replace(/\@DESCRIPTION/g, product.description.unescapeHTML());
	
	var category;
	if (product.type.length > 0) {
		category = product.type + ' - '; 
	}
	category += product.category;
	
	p.innerHTML = p.innerHTML.replace(/\@CATEGORY/g, category.unescapeHTML());
	p.innerHTML = p.innerHTML.replace(/\@PRICE/g, product.price);
	
	var products = document.getElementById('productResults');
	products.appendChild(p);

	//alert(p.innerHTML);
}
*/

function clearSearchResults(feedId) {
	var x = document.getElementById(params[feedId].name + 'Results');
        while (x.childNodes.length > 0) {
                x.removeChild(x.childNodes[0]);
        }
}

function searchProducts(feedId, params, animate) {

	if (animate) {
		//Element.scrollTo('productStart');
		Element.show('productLoading');
		Element.hide('productContainer');
	}

	var url = 'searchSpring.php?' + params;

	new Ajax.Request(url,
	{
		method:'get',
		onSuccess: function(transport){
	
			var searchResult = eval('(' + transport.responseText + ')');
		
			clearSearchResults(0);
			
			document.getElementById('productDivs').innerHTML = '';

			var i;

			for (i = 0; i < searchResult.results.length; i++) {
				addProduct(searchResult.pagination.begin + i, searchResult.results[i]);
			}
		
			updatePagination('product', 0, searchResult.pagination);

			// Update filters
			updateFilters('product', searchResult.facets);
			
			if (animate) {
				Element.hide('productLoading');
				Effect.BlindDown('productContainer');
			} else {
				//Element.scrollTo('productStart');
			}
			
			return;
		},
		onFailure: function(){
			alert('Failed to perform product search');
		}
	});
	
}

function searchArticles(feedId, params, animate, scroll) {

	var url = 'searchSpring.php?' + params;
	
	new Ajax.Request(url,
	{
		method:'get',
		onSuccess: function(transport){
			
			var searchResult = eval('(' + transport.responseText + ')');
			
			clearSearchResults(1);
			
			var i;

			for (i = 0; i < searchResult.results.length; i++) {
				addArticle(searchResult.pagination.begin + i, searchResult.results[i]);
			}
	
			if (searchResult.results.length > 5) {
				Element.show('showMoreArticles');
			} else {
				Element.hide('showMoreArticles');
			}
	
			if (searchResult.results.length == 0) {
				Element.show('articleNoResults');
			} else {
				Element.hide('articleNoResults');
			}
	
			return;
		},
		onFailure: function(){
			alert('Failed to perform article search');
		}
	});
	
}

function clearProducts() {
	var x = document.getElementById('productResults');
	while (x.childNodes.length > 0) {
		x.removeChild(x.childNodes[0]);
	}
}

function addProduct(no, product) {

	var tr = document.createElement('tr');
	var td = document.createElement('td');

	td.style.textAlign = 'left';
	td.style.width = '50px';

	var a = document.createElement('a');
	a.href = '/' + product.code + '.html';

	var img = document.createElement('img');

	if (product.thumbnail) {

		img.src = '/store/' + product.thumbnail;
		img.setAttribute('name', product.code + 'thumb');

		//a.setAttribute('onMouseOut', 'MM_showHideLayers(\'' + product.code + '-layer\',\'\',\'hide\');alert(\'MouseOut\');');
		//a.setAttribute('onMouseOver', 'P7_Snap(\'' + product.code + 'shim\',\'' + product.code + '-layer\',0,-310);MM_showHideLayers(\'' + product.code + '-layer\',\'\',\'show\');alert(\'MouseOver\');');
		
		//a.onMouseOver = function(){alert('MouseOver begin');P7_Snap(product.code + 'shim', product.code + '-layer', 0, -310); MM_showHideLayers(product.code + '-layer', '', 'show');alert('MouseOver end');}
		
		a.onmouseover = function(){P7_Snap(product.code + 'shim', product.code + '-layer', 0, -310); MM_showHideLayers(product.code + '-layer', '', 'show');}
		a.onmouseout = function(){MM_showHideLayers(product.code + '-layer', '', 'hide');}
		
		//alert(a.getAttribute('onMouseOver'));

	} else {
		img.src = '/store/graphics/00000001/imagesoon.gif';
	}

	img.setAttribute('border', '0');

	a.appendChild(img);
	td.appendChild(a);
	tr.appendChild(td);

	td = document.createElement('td');
	td.style.textAlign = 'center';
	var a = document.createElement('a');
	a.style.fontWeight = 'bold';
	a.href = '/' + product.code + '.html';
	a.appendChild(document.createTextNode('Purchase'));
	a.appendChild(document.createElement('br'));

	var em = document.createElement('em');
	em.appendChild(document.createTextNode('More Info'));
	a.appendChild(em);

	td.appendChild(a);
	tr.appendChild(td);

	td = document.createElement('td');
	td.style.textAlign = 'center';
	td.style.fontWeight = 'bold';
	td.appendChild(document.createTextNode('$' + product.price));

	tr.appendChild(td);

	td = document.createElement('td');
	
	var span = document.createElement('span');

/*
	if (product.thumbnail) {
		var div = document.createElement('div');
	
		div.setAttribute('style', 'position:absolute; left:100px; top:389px; width:252px; height:260px; z-index:1; visibility: hidden;');
		div.setAttribute('id', product.code + '-layer');
	}
*/

	var desc = product.description.unescapeHTML();
	if (desc.length > 100) {
		span.innerHTML = desc.substring(0, 100) + '...';
	} else {
		span.innerHTML = desc;
	}

/*
	if (product.thumbnail) {
		div.innerHTML = '<table width="252" border="0" cellpadding="1" cellspacing="0" bgcolor="#FF0000"><tr><td><table width="100%" border="0" cellpadding="8" cellspacing="0" bgcolor="#FFFFFF"><tr><td align="center" valign="middle"><img src="/store/' + product.image + '" name="' + product.code + '" border="0"></td></tr><tr><td align="left" valign="top"><b>' + product.name + '</b><br>Bikeman Product Code: ' + product.code + '</td></tr></table></td><tr></table>';
		td.appendChild(div);
	}
*/

	td.appendChild(span);

	if (product.manum != undefined && product.manum.length > 0) {
		td.appendChild(document.createElement('br'));
		td.appendChild(document.createTextNode('Manufacturer\'s Part #: '));
		var span = document.createElement('span');
		span.style.fontWeight = 'bold';
		span.appendChild(document.createTextNode(product.manum.unescapeHTML()));
		td.appendChild(span);
	}

	td.appendChild(document.createElement('br'));
	td.appendChild(document.createTextNode('Bikeman Product Code: '));
	span = document.createElement('span');
	span.style.fontWeight = 'bold';
	span.appendChild(document.createTextNode(product.code.unescapeHTML()));
	td.appendChild(span);

	if (product.thumbnail) {
		// Hidden thumbnail anchor
		td.innerHTML += '<br/><img src="/store/graphics/00000001/blank.gif" width="1" height="1" name="' + product.code + 'shim">';
	}

	tr.appendChild(td);

	var products = document.getElementById('productResults');
	products.appendChild(tr);

	addProductDiv(no, product);

}

function addProductDiv(no, product) {

	if (product.thumbnail) {
		var div = document.createElement('div');
	
		//div.setAttribute('style', 'position:absolute; left:100px; top:389px; width:252px; height:260px; z-index:100; visibility: hidden;');

		div.style.position = 'absolute';
		div.style.left = '100px';
		div.style.top = '100px';
		div.style.width = '252px';
		div.style.height = '260px';
		div.style.zIndex = '100';
		div.style.visibility = 'hidden';
		
		div.id = product.code + '-layer';

		div.innerHTML = '<table width="252" border="0" cellpadding="1" cellspacing="0" bgcolor="#FF0000"><tr><td><table width="100%" border="0" cellpadding="8" cellspacing="0" bgcolor="#FFFFFF"><tr><td align="center" valign="middle"><img src="/store/' + product.image + '" name="' + product.code + '" border="0"></td></tr><tr><td align="left" valign="top"><b>' + product.name + '</b><br>Bikeman Product Code: ' + product.code + '</td></tr></table></td><tr></table>';

		var divs = document.getElementById('productDivs');
		divs.appendChild(div);
	}

}

function updateFilters(section, facets) {
	
	var x = document.getElementById(section + 'Facets');
	x.innerHTML = '';

	for (i = 0; i < facets.length; i++) {
	
		if (facets[i].values.length == 0) {
			continue;
		}
		
		var filterNode = document.createElement('div');
		filterNode.setAttribute('class', 'filter');
		
		var t = document.createElement('span');
		t.style.fontWeight = 'bold';
		t.appendChild(document.createTextNode(facets[i].displayName));
		filterNode.appendChild(t);
		
		var valueList = document.createElement('ul')

		if (params[0].filters[i].length > 0) {

			for (var j = 0; j < params[0].filters[i].length; j++) {
				var value = document.createElement('li');

				var strong = document.createElement('strong');
				//strong.appendChild(document.createTextNode(params[0].filters[i][j].displayValue.replace(/\//, ' / ') + ' '));
				strong.appendChild(document.createTextNode(('' + params[0].filters[i][j].displayValue).replace(/\//, ' / ') + ' '));
				value.appendChild(strong);

				var a = document.createElement('a');
				a.href = 'javascript:removeFilter(\'0\', ' + i + ', ' + j + ')';
				a.appendChild(document.createTextNode('Remove'));
				value.appendChild(document.createTextNode(' '));
				value.appendChild(a);
				
				valueList.appendChild(value);
			}

		} else {

			for (var j = 0; j < facets[i].values.length; j++) {
			
				var value = document.createElement('li');
				
				var a = document.createElement('a');
				//a.href = 'javascript:applyFilter(\'0\', ' + i + ', \'' + facets[i].name.replace(/\'/g, '\\\'') + '\', \'' + facets[i].values[j].value.replace(/\'/g, '\\\'') + '\', \'' + facets[i].values[j].displayValue.replace(/\'/g, '\\\'') + '\')';
				//a.appendChild(document.createTextNode(facets[i].values[j].displayValue.replace(/\//g, ' / ')));
				
				// Make sure we convert our JSON values to strings before .replace()...
				a.href = 'javascript:applyFilter(\'0\', ' + i + ', \'' + ('' + facets[i].name).replace(/\'/g, '\\\'') + '\', \'' + ('' + facets[i].values[j].value).replace(/\'/g, '\\\'') + '\', \'' + ('' + facets[i].values[j].displayValue).replace(/\'/g, '\\\'') + '\')';
				a.appendChild(document.createTextNode(('' + facets[i].values[j].displayValue).replace(/\//g, ' / ')));

				value.appendChild(a);

				value.appendChild(document.createTextNode(' (' + facets[i].values[j].count + ')'));
				valueList.appendChild(value);
			}
		}
		
		filterNode.appendChild(valueList);
		x.appendChild(filterNode);
	}
}

function applyFilter(feedId, filterId, fieldName, value, displayValue) {
	params[feedId].page = 1;
	params[feedId].filters[filterId][params[feedId].filters[filterId].length] = {field: fieldName, value: value, displayValue: displayValue};

	searchProducts(feedId, buildSearchParams(feedId));
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

function removeFilter(feedId, filterId, index) {

	params[feedId].page = 1;
	params[feedId].filters[filterId].remove(index);
	/*
	for (var k = 0; k < params[feedId].filters[filterId].length; k++) {
		if (params[feedId].filters[filterId][k].field == fieldName && params[feedId].filters[filterId][k].value == value) {
			params[feedId].filters[filterId].remove(k);
		}
	}
	*/
	
	//console.log(params);
	
	searchProducts(feedId, buildSearchParams(feedId));
}

function changePage(feedId, page) {
	params[feedId].page = page;
	if (feedId == 0) {
		searchProducts(feedId, buildSearchParams(feedId));
	} else {
		searchArticles(feedId, buildSearchParams(feedId), false, true);
	}
}

function changeSort(sort) {
	var feedId = 0;
	params[feedId].sort = sort;
	searchProducts(feedId, buildSearchParams(feedId));
}

function buildSearchParams(feedId) {

	var qs = '&version=1.1&feed=' + feedId + '&query=' + escape(params[feedId].query) + '&page=' + params[feedId].page + '&sort=' + escape(params[feedId].sort) + '&resultsPerPage=' + params[feedId].resultsPerPage;
	
	for (var i = 0; i < params[feedId].filters.length; i++) {
		
		var f = '';
		
		for (var j = 0; j < params[feedId].filters[i].length; j++) {
			f += params[feedId].filters[i][j].field + ':' + params[feedId].filters[i][j].value + ' '; 
		}
		
		if (f.length > 0) {
			qs += '&filters[]=' + escape(f);
		}
	}

	return qs;
}

function resetParams(feedId) {
	params[feedId].page = 1;
	params[feedId].sort = '';
	for (var i = 0; i < params[feedId].filters.length; i++) {
		params[feedId].filters[i] = new Array();
	}
}

function resetAllParams() {
	for (var i = 0; i < params.length; i++) {
		resetParams(i);
	}
}

function updatePagination(type, feedId, page) {

	var pageNode = document.getElementById(params[feedId].name + 'PaginationTop');
	pageNode.innerHTML = params[feedId].name + 's found: <strong>' + page.totalResults + '</strong>&#160;&#160;&#160;';

	if (page.previousPage != 0 && page.previousPage < page.currentPage) {
		// Show previous
		pageNode.innerHTML += '<a href="#" onclick="changePage(' + feedId + ', ' + page.previousPage + ');return false;">&laquo;</a>&#160;&#160;';
	}
	
	var start = page.currentPage - 2 > 0 ? page.currentPage - 2 : 1;

	if (start > 1) {
		pageNode.innerHTML += '...&#160;&#160;';
	} 

	for (var i = start; i <= page.totalPages && i - start <= 4; i++) {
		if (i == page.currentPage) {
			// Show current page
			pageNode.innerHTML += '<span class="pageNo">' + page.currentPage + '</span>';
		} else {
			// Show page link
			pageNode.innerHTML += '<a href="#" class="pageNo" onclick="changePage(' + feedId + ', ' + i + ');return false;">' + i + '</a>';
		}
		pageNode.innerHTML += '&#160;&#160;';
	}
	
	if (page.totalPages > i) {
		pageNode.innerHTML += '...&#160;&#160;';
	} 
	
	if (page.nextPage > page.currentPage) {
		// Show next
		pageNode.innerHTML += '<a href="#" onclick="changePage(' + feedId + ', ' + page.nextPage + ');return false;">&raquo;</a>';
	}

	pageNode.innerHTML += '&#160;&#160;&#160; Page ' + page.currentPage + ' of ' + page.totalPages;

	var pageNode2 = document.getElementById(params[feedId].name + 'PaginationBottom');
	if (pageNode2) {
		pageNode2.innerHTML = pageNode.innerHTML;
	}
}

function clearArticles() {
	document.getElementById('articleResults').innerHTML = '';
}

function addArticle(no, article) {

	var tr = document.createElement('tr');

	if (no > 5) {
		tr.style.display = 'none';
	}

	var td = document.createElement('td');
	td.style.fontWeight = 'bold';
	td.appendChild(document.createTextNode(no + '.'));

	tr.appendChild(td);

	td = document.createElement('td');
	var a = document.createElement('a');
	a.href = article.url;
	a.appendChild(document.createTextNode(article.title));

	td.appendChild(a);
	tr.appendChild(td);
	
	var articles = document.getElementById('articleResults');
	
	articles.appendChild(tr);
}

function showMoreArticles() {
	var articles = document.getElementById('articleResults');

	for (var i = 0; i < articles.childNodes.length; i++) {
		articles.childNodes[i].style.display = '';
	}

	document.getElementById('showMoreArticles').style.display = 'none';
}

function refineSearch() {
	
}

