/** 
 * @fileOverview Colour auto complete.
 * @author Oliver Bishop / Tom McCourt
 * @version 1.0.0
 * @changeLog Created
 */

/* This sets the global namespaces */
var UKISA = UKISA || {};
UKISA.widget = UKISA.widget || {};

/**
 * Create a form validation instance with localisation and fancy error messages.
 */
UKISA.widget.ColourSuggest = function(field, options) {
	var el, ac, itemSelectHandler, container, swatch, formatter, selecter;

	// Get the field.
	el = document.getElementById(field);

	selecter = function(data) {
		swatch = document.getElementById(id + "-yui-ac-cs-swatch");
		if (swatch) {
			swatch.src = "/files/images/colours/swatch/" + data[1] + ".jpg";
			swatch.width = 20;
			swatch.height = 20;
			swatch.alt = data[0];
		}
	};
	
	// Create a custom handler when an item is selected.
	itemSelectHandler = function(sType, aArgs) {
		var ac, item, data, id, swatch;

		ac	 = aArgs[0]; // The AutoComplete instance.
		item = aArgs[1]; // The <li> element selected in the suggestion container
		data = aArgs[2]; // object literal of data for the result

		id = ac.getInputEl().getAttribute("id");
		
		// Set the value.
		ac.getInputEl().value = data[0];

		selecter(data);
	};


	// If the container property exists, then it has the Id for the hard coded HTML one.
	if (!options || !options.container)  {
		container = document.createElement("div");
		container.id = field + "-yui-ac-results";

		YAHOO.util.Dom.getAncestorByTagName(el, "p").parentNode.appendChild(container);

		// Set the Id for the AutoComplete.
		container = container.id;
	}

	// Check to see if the swatch is not wanted (on by default).
	swatch = (options && typeof options.swatch === "boolean" && options.swatch === false) ? false : true;

	if (swatch) {
		// Create a new colour swatch if required.
		swatch = document.createElement("img");
		swatch.alt = "";
		swatch.src = "/web/images/swatch/blank.jpg";
		swatch.id = field + "-yui-ac-cs-swatch";
		swatch.className = "yui-ac-cs-swatch";
		el.parentNode.parentNode.appendChild(swatch);
	}

	formatter = function(result, query, match) {
		var markup;

		markup = [
			"<img width=\"31\" height=\"13\" src=\"/files/images/colours/swatch/" + result[1] + ".jpg\" />",
			" " + match
		];

		return (markup.join(""));
	};

	if (options && options.format) {
		formatter = options.format;
	}

	// Set up the instance of the auto complete.
	ac = new YAHOO.widget.AutoComplete(field, container, UKISA.widget.ColourSuggest.getDataSource());
	ac.itemSelectEvent.subscribe(itemSelectHandler);
	ac.forceSelection = true;
	ac.formatResult = formatter;
	
	// If a product parameter is required, this will add it to a custom data source request.
	if (options && options.product) {
		ac.generateRequest = function(query) { 
			return "?query=" + query + "&product=" + options.product; 
		}; 
	}

	// Return the auto complete to use if required.
	return ac;
};

/**
 * Add a text field to apply the autocomplete to.
 */ 
UKISA.widget.ColourSuggest.add = function(field, options) {
	var i;

	if (typeof field == "string") {
		// Create only one instance.
		new UKISA.widget.ColourSuggest(field, options);
	} else {
		// Create multiple instances.
		for (i in field) {
			new UKISA.widget.ColourSuggest(field[i], options);
		}
	}
};

/**
 * Shared datasource.
 */ 
UKISA.widget.ColourSuggest._dataSource = null;

/**
 * Get the data source for the ajax search.
 */ 
UKISA.widget.ColourSuggest.getDataSource = function() {
	if (this._dataSource === null) {

		// Create the colour data source. ajax/colours/search.jsp?query=Sundrenched&product=TEST
		this._dataSource = new YAHOO.util.XHRDataSource("/ajax/colours/search.jsp"); 

		// Set the responseType .
		this._dataSource.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;

		// Define the schema of the delimited results .
		this._dataSource.responseSchema = { 
			recordDelim: "\n", 
			fieldDelim: "\t" 
		};

		// Limit the entries.
		this._dataSource.maxCacheEntries = 150; 
	}

	// Return the new or existing instance.
	return this._dataSource;
};
