var SearchStores = {
	stores: Stores,
	search: function () {
		this.stores = Stores;
		// Check store names
		if($('store_name').value.length > 0) {
			var regexp = new RegExp($('store_name').value.replace(/\\/g, ''), "i");
			this.stores = findByKeyExpPair(this.stores, {name:regexp});
		}
		
		// Check categories
		if($('store_category').value.length > 0) {
			var regexp = new RegExp($('store_category').value.replace(/\\/g, ''), "i");
			this.stores = findByKeyExpPair(this.stores, {category:regexp});
		}
		
		// Check loyalty cards
		if($('store_loyalty_card').value.length > 0) {
			var regexp = new RegExp($('store_loyalty_card').value.replace(/\\/g, ''), "i");
			this.stores = findByKeyExpPair(this.stores, {loyalty_card:regexp});
		}
		return this.stores;
	},
	checkForDocumentParams: function () {
		if(document.location.search.length > 0) {
			var query_strings = document.location.search.split('?')[1].split('&');
			for(var i = 0; query_strings.length < i; i++) {
				var key_chunk = query_strings[i].split('=')[0];
				var value_chunk = query_strings[i].split('=')[1];

				if(key_chunk == 'name') $('store_name').value = value_chunk;
				if(key_chunk == 'category') $('store_category').value = value_chunk;
			}
		}
	}
}
var Stores = [];
handleStoreQuery = function (result) {
	Stores = result;
}

new DataStore('http://public.mirvacretail.com.au/mirvacs/retail.js?table=stores&centre_id=' + document.getElementsByTagName("body")[0].id.split('_')[2] + '&return=name,category,loyalty_card,url', 'handleStoreQuery');

// Requirement to build table based on multi-dimensional array / hash

var searchResults = {}
// Create table rows for results
searchResults.buildNodes = function (stores) {
	
	// Clear the current contents of the table
	var table = document.getElementById('results');
	if(table.tBodies) {
		tableRowLength = table.tBodies[0].rows.length;
		for(var i = 0; i < tableRowLength; i++) {
			table.tBodies[0].deleteRow(table.tBodies[0].rows[0].sectionRowIndex);
		}
	}else{
		table.getElementsByTagName('tbody')[0].innerHTML = '';
	}
	
	// Sort search results by name, case insensitive
	stores = stores.sortBy(function(store) { return store.name.toLowerCase(); });
	
	for(var i = 0; i < stores.length; i++) {
		
		// Alternating rows
		var className = ''
		
		// Apply the 'first' class if its the first item
		if(i == 1) className += 'first';
		
		// Add the odd / even class
		if((i % 2 ) != 0) {
			className += 'odd'
		}else{
			className += 'even'
		}
		
		// Build a new row
		var resultRow = document.createElement("tr");
		
		// Build name column
		var name_cell = document.createElement("td");
		var shopping_cart_image = document.createElement("img");
		shopping_cart_image.setAttribute('src', '/templates/mirvac_retail_centre/images/icons/icn_trolley.gif');
		shopping_cart_image.setAttribute('alt', 'Store');
		
		name_cell.appendChild(shopping_cart_image);
		var link = document.createElement("a");
		link.setAttribute('href', site_url + "/" + stores[i].url);
		link.setAttribute('title', "Visit "+stores[i].name);
		link.appendChild(document.createTextNode(stores[i].name));
		
		/*
			IE will not recieve the styles for the element, write them in by hand (grr)
		*/
		
		shopping_cart_image.style.display = 'inline';
		shopping_cart_image.style.marginRight = '3px';
		shopping_cart_image.verticalAlign = 'text-bottom';
		
		name_cell.appendChild(link);
		
		// Build category
		var category_cell = document.createElement("td");
		category_cell.appendChild(document.createTextNode(stores[i].category));
		
		// Build loyalty cards
		var loyalty_cell = document.createElement("td");
		loyalty_cell.appendChild(document.createTextNode(stores[i].loyalty_card || ''));
		
		// Append our new nodes
		resultRow.appendChild(name_cell);
		resultRow.appendChild(category_cell);
		resultRow.appendChild(loyalty_cell);
		
		// Add to the DOM
		document.getElementById('results').getElementsByTagName("tbody")[0].appendChild(resultRow);
		
		// Apply the correct class name
		resultRow.setAttribute('class', className);
		
		// Apply class names to the newly created elements
		name_cell.setAttribute('class', 'name');
		category_cell.setAttribute('class', 'category');
		loyalty_cell.setAttribute('class', 'loyalty_cards');
	}
}
searchResults.updateCount = function (results) {
	if(results.length > 0) {
		document.getElementById('result_count').innerHTML = results.length + ' stores found';
	} else {
		document.getElementById('result_count').innerHTML = 'No stores found';
	}
}

// Observe our form fields, on key press, search the stores!
Event.observe(document, 'keyup', function (event) {
	var origin = Event.element(event);
	if(/(store_name|store_category|store_loyalty_card)/.test(origin.id)) {
		var results = SearchStores.search()
		searchResults.buildNodes(results);
		searchResults.updateCount(results);
	}
});

Event.observe(window, 'load', function () {
	SearchStores.checkForDocumentParams();
	SearchStores.search();
}, false)