var RC;
Event.observe(window, 'load', function(e) {
	RC = new RemoteControl();

	// ### Initialize Quick Search Autocompleter
		new Autocompleter.DWR('rc_token', 'rc_suggestions', autocomplete, {
			valueSelector : renderItemLabel,
			afterUpdateElement : itemSelectionCallback,
			minChars : 2,
			delay : 0.6
		});

		// ### Default texts in Quick Search fields
		new DefaultText('rc_token', 'e.g. reference, designer, maker, color');

		// ### Initialize Home Search Autocompleter
		new Autocompleter.DWR('home_token', 'home_suggestions', autocomplete, {
			valueSelector : renderItemLabel,
			afterUpdateElement : homeItemSelectionCallback,
			minChars : 2,
			delay : 0.6
		});

		// ### Default texts in Home Search fields
		new DefaultText('home_token',
				'e.g. reference, designer, maker, color, style, showroom');

	});

// ### AJAX: Search ALL for Autocompleter
function autocomplete(autocompleter, query) {
	RemoteControlComponent.autocomplete(query, 'ALL', function(items) {
		autocompleter.setChoices(items);
		$('rc_search_info').update('');
	});
}

// ### AJAX: Renders item label for suggestions in Autocompleter
function renderItemLabel(item) {
	return item.value + '|' + item.info;
}

// ### AJAX: Handles selected item in Autocompleter
function itemSelectionCallback(inputElement, selectedElement, item) {
	$('rc_token').blur();
	$('rc_token').value = item.value;
	var name;
	if (item.bean == 'TAG') {
		location.href = '/search.action?q.t=' + item.id;
	} else if (item.bean == 'DESIGNER') {
		location.href = item.url;
	} else if (item.bean == 'PRODUCT') {
		location.href = '/search.action?q.tpl=' + item.id;
	} else if (item.bean == 'MAKER') {
		location.href = item.url;
	} else if (item.bean == 'ID') {
		location.href = item.url;
	} else if (item.bean == 'SHOWROOM') {
		location.href = item.url;
	}
}

function homeItemSelectionCallback(inputElement, selectedElement, item) {
	$('home_token').blur();
	$('home_token').value = item.value;

	$('rc_token').blur();
	$('rc_token').value = item.value;

	var name;
	if (item.bean == 'TAG') {
		location.href = '/search.action?q.t=' + item.id;
	} else if (item.bean == 'DESIGNER') {
		location.href = item.url;
	} else if (item.bean == 'PRODUCT') {
		location.href = '/search.action?q.tpl=' + item.id;
	} else if (item.bean == 'MAKER') {
		location.href = item.url;
	} else if (item.bean == 'ID') {
		location.href = item.url;
	} else if (item.bean == 'SHOWROOM') {
		location.href = item.url;
	}
}

// ### CLASS: DefaultText
DefaultText = Class.create();
DefaultText.prototype = {
	initialize : function(target, text) {
		var element = $(target);
		this.element = element;
		this.text = text;

		var color = this.element.getStyle('color');
		if (!color) {
			color = 'inherit';
		}
		
		var fontStyle = this.element.getStyle('font-style');
		if (!fontStyle) {
			fontStyle = 'inherit';
		}
		
		this.style = {
			color : color,
			fontStyle : fontStyle
		};

		var instance = this;
		this.element.observe('blur', function() {
			instance.onBlur();
		});
		
		this.element.observe('focus', function() {
			instance.onFocus();
		});

		var form = this.element.up('form');
		if (form) {
			form.observe('submit', function() {
				if (instance.isDefault()) {
					instance.clearText();
				}
			});
		}

		this.onBlur();
	},

	isDefault : function() {
		return (this.element.getValue() == this.text);
	},

	onFocus : function() {
		if (this.isDefault()) {
			this.hideText();
		}
		this.element.select();
	},

	onBlur : function() {
		if (this.element.getValue().strip().empty()) {
			this.showText();
		}
	},

	showText : function() {
		this.element.setStyle( {
			color : '#999999',
			fontStyle : 'italic'
		});
		this.element.value = this.text;
	},

	hideText : function() {
		this.clearText();
		this.element.setStyle(this.style);
	},

	clearText : function() {
		this.element.clear();
	}
}

ShowroomSearchAction = Class.create();
ShowroomSearchAction.prototype = {}

// ### CLASS: RemoteControl
RemoteControl = Class.create();
RemoteControl.prototype = {
	initialize : function() {
		this.panels = new Hash();
		this.available = $('rc_browse_form') ? true : false;
	},

	getPanelById : function(id) {
		var panel = this.panels.get(id);

		if (!panel) {
			panel = new Panel(this, id);
			this.panels.set(id, panel);
		}

		return panel;
	},

	getPanel : function(callerElement) {
		var panel = this.getPanelById($(callerElement).up('.panel').id);

		/*
		 * if (this.currentPanel && this.currentPanel.id != panel.id) {
		 * this.currentPanel.closeOptions(); }
		 */

		this.currentPanel = panel;

		return panel;
	},

	reset : function() {
		var rc = this;
		if (rc.available) {
			$('rc_sort').clear();
			$('rc_pageSize').clear();
			$('rc_page').clear();
			$('rc_browse_form').select('div.panel').each(function(element) {
				rc.getPanelById(element.id).reset();
			});
			rc.count();
		}
	},

	getFieldArray : function(type, name) {
		return $A($('rc_browse_form').getInputs(type, name).invoke('getValue'))
				.compact();
	},

	// ### AJAX: Count products
	count : function() {
		var rc = this;

		var query = {
			'categories' : rc.getFieldArray('checkbox', 'q.c'),
			'styles' : rc.getFieldArray('checkbox', 'q.s'),
			'designers' : rc.getFieldArray('hidden', 'q.d'),
			'sellerTypes' : rc.getFieldArray('checkbox', 'q.st'),
			'minPrice' : $F('rc_minPrice'),
			'maxPrice' : $F('rc_maxPrice')
		};

		try {
			RemoteControlComponent.count(query, function(count) {
				$('rc_searchResultCount').update(count);
			});
		} catch (e) {
			// alert("ERROR: " + e.message);
		}
	},

	sort : function(sort) {
		$('rc_sort').value = sort;
		this.search();
	},

	gotoPage : function(page) {
		$('rc_page').value = page;
		this.search();
	},

	gotoPreviousPage : function() {
		this.gotoPage(parseInt($('rc_page').value, 10) - 1);
	},

	gotoNextPage : function() {
		this.gotoPage(parseInt($('rc_page').value, 10) + 1);
	},

	limitPageSize : function(size) {
		$('rc_page').value = 0;
		$('rc_pageSize').value = size;
		this.search();
	},

	search : function() {
		$('rc_browse_form').submit();
	}
}

// ### CLASS: Panel
Panel = Class.create();
Panel.prototype = {
	initialize : function() {
		this.remoteControl = arguments[0];
		this.panel = $(arguments[1]);
		this.id = this.panel.id;
		this.options = $(this.panel.id + '_options');
		this.info = $(this.panel.id + '_info');
		this.infoOptionsLimit = 8;
	},

	toggleOptions : function() {
		if (this.options.visible()) {
			this.closeOptions();
		} else {
			this.openOptions();
		}
	},

	openOptions : function() {
		var panelOffset = this.panel.positionedOffset();

		this.options
				.setStyle( {
					left : (panelOffset.left + parseInt(this.panel.getWidth()) - 7) + 'px', // parseInt(this.panel.getWidth())
					// +
					// 'px',
					top : (panelOffset.top - 7) + 'px'
				});

		this.options.show();
	},

	closeOptions : function() {
		this.options.hide();
	},

	selectOption : function(callerElement) {
		var checkbox = $(callerElement);
		var isParent = checkbox.hasClassName('parent');
		var hasSelectedOptions = false;

		this.options.select('input[type="checkbox"]').each(function(checkbox) {
			if (!hasSelectedOptions && checkbox.checked) {
				hasSelectedOptions = true;
			}
		});

		if (isParent || !hasSelectedOptions) {
			if (hasSelectedOptions) {
				this.reset();
			}
			var parentObject = this.info.down('input[type="checkbox"]');
			parentObject.checked = true;
			parentObject.writeAttribute( {
				'disabled' : true
			});
		} else if (hasSelectedOptions) {
			var parentObject = this.info.down('input[type="checkbox"]');
			parentObject.checked = false;
			parentObject.writeAttribute( {
				'disabled' : false
			});
		}

		/*
		 * var checkbox = $(callerElement); var isParent =
		 * checkbox.hasClassName('parent'); // ### Remove (previous) info option
		 * var dbId = checkbox.value; var infoOptionId =
		 * this.identifyInfoOption(dbId);
		 * 
		 * this.removeInfoOption(checkbox.value);
		 * 
		 * 
		 * if (checkbox.checked) { var showInfo = true;
		 * 
		 * if (isParent) { var childCount = this.selectChildOptions(checkbox);
		 * showInfo = (childCount == 0); }
		 * 
		 * if (showInfo) { this.addInfoOption(dbId,
		 * checkbox.next('label').innerHTML,null); } } else if (isParent) {
		 * this.clearChildOptions(checkbox); }
		 * 
		 * if (!isParent) { var childContainer = checkbox.up('.children'); if
		 * (childContainer) { var children = childContainer.select('input'); var
		 * checkedCount = 0; for ( var i = 0; i < children.length; i++) { if
		 * (children[i].checked) { checkedCount++; } } if (checkedCount ==
		 * children.length) { this.getParentOption(checkbox).checked = true; }
		 * else { this.getParentOption(checkbox).checked = false; } } }
		 * 
		 * if (!this.hasInfoOptions()) { this.showInfoLabel(); }
		 */
	},

	selectAllOptions : function() {
		var thisPanel = this;
		this.panel.select('input[type="checkbox"]').each(function(checkbox) {
			checkbox.checked = true;
			thisPanel.selectOption(checkbox);
		});
	},

	getParentOption : function(childOption) {
		return $(childOption).up('.children').previous('.all').down('input');
	},

	getChildOptions : function(parentOption) {
		return $(parentOption).up('.all').next('.children').select('input');
	},

	selectChildOptions : function(parentOption) {
		var children = this.getChildOptions(parentOption);
		for ( var i = 0; i < children.length; i++) {
			children[i].checked = true;
			this.selectOption(children[i]);
		}
		return children.length;
	},

	clearChildOptions : function(parentOption) {
		var children = this.getChildOptions(parentOption);
		for ( var i = 0; i < children.length; i++) {
			children[i].checked = false;
			this.selectOption(children[i]);
		}
		return children.length;
	},

	addOption : function(dbId, label, field) {
		this.addInfoOption(dbId, label, field);
	},

	updatePriceRange : function() {
		var min = $F('rc_minPrice');
		var max = $F('rc_maxPrice');

		/*
		 * this.clearInfoOptions();
		 * 
		 * if (min != '' || max != '') { this.hideInfoLabel();
		 * 
		 * var html = RCHTML.infoOptionRange.evaluate( { min :(min != '') ? 'USD ' +
		 * Math.round(min) : 'No Minimum', max :(max != '') ? 'USD ' +
		 * Math.round(max) : 'No Maximum' }); if(this.info != null) {
		 * this.info.insert( { bottom :html }); } } else { this.showInfoLabel(); }
		 */

		this.remoteControl.count();
	},

	identifyInfoOption : function(dbId) {
		if (this.info != null) {
			return (this.info.id + '_' + dbId);
		}
	},

	hasInfoOptions : function() {
		if (this.info != null) {
			var children = this.info.childElements();
			for ( var i = 0; i < children.length; i++) {
				if (children[i].visible() && !children[i].hasClassName('all')) {
					return true;
				}
			}
		}

		return false;
	},

	addInfoOption : function(dbId, label, field) {
		var infoOption = $(this.identifyInfoOption(dbId));

		if (infoOption) {
			// ### Show ev. hidden option
			infoOption.show();
		} else {
			// ### Add new option
			var properties = {
				styleId : this.identifyInfoOption(dbId),
				label : label,
				id : dbId,
				field : field
			}

			var template = (field != null) ? RCHTML.infoOptionField
					: RCHTML.infoOption;
			var html = template.evaluate(properties);

			if (this.info != null) {
				this.info.insert( {
					bottom : html
				});
			}
		}

		this.limitInfoOptions();
		this.hideInfoLabel();
	},

	removeInfoOption : function(dbId) {
		var infoOption = $(this.identifyInfoOption(dbId));
		if (infoOption) {
			if (infoOption.hasClassName('option')) {
				infoOption.remove();
			} else {
				infoOption.hide();
			}
			this.limitInfoOptions();
		}
	},

	getInfoOptions : function() {
		if (this.info != null) {
			return this.info.select('.option');
		}
	},

	limitInfoOptions : function() {
		var infoOptions = this.getInfoOptions();
		var count = infoOptions.length;
		var visibleCount = 0;

		if (count >= this.infoOptionsLimit) {
			for ( var i = 0; i < infoOptions.length; i++) {
				var option = infoOptions[i];
				if (visibleCount < this.infoOptionsLimit) {
					visibleCount++;
					if (!option.visible()) {
						option.show();
					}
				} else {
					option.hide();
				}
			}
		}
	},

	unlimitInfoOptions : function() {
		this.getInfoOptions().invoke('show');
	},

	clearInfoOptions : function() {
		if (this.info != null) {
			var children = this.info.childElements();
			for ( var i = 0; i < children.length; i++) {
				var child = children[i];
				if (!child.hasClassName('all')) {
					if (child.hasClassName('option')) {
						child.remove();
					} else {
						child.hide();
					}
				}
			}
		}
	},

	getInfoLabel : function() {
		if (this.info != null) {
			if (!this.infoLabel) {
				this.infoLabel = this.info.down('li.all');
			}
		}

		return this.infoLabel;
	},

	showInfoLabel : function() {
		var aoi = this.getInfoLabel();
		if (aoi) {
			aoi.show();
		}
	},

	hideInfoLabel : function() {
		var aoi = this.getInfoLabel();
		if (aoi) {
			aoi.hide();
		}
	},

	reset : function() {
		// ### Clear checkboxes
	if (this.options) {
		this.options.select('input[type="checkbox"]').each(function(checkbox) {
			checkbox.checked = false;
		});
	}

	// ### Clear textfields
	this.panel.select('input[type="text"]').invoke('clear');

	// ### Reset dropdowns
	this.panel.select('select').each(function(select) {
		select.value = '';
	});

	// ### Clear info
	this.clearInfoOptions();

	this.showInfoLabel();
	// this.closeOptions();

	// this.remoteControl.count();
}
}

// ### HTML Templates for rendering
var RCHTML = {
	infoOption : new Template(
			'<li id="#{styleId}" class="option"><img src="img/checked-blue.gif" alt="Checked Blue" /><span>#{label}</span></li>'),
	infoOptionField : new Template(
			'<li id="#{styleId}" class="option"><img src="img/checked-blue.gif" alt="Checked Blue" /><span>#{label}<input type="hidden" name="#{field}" value="#{id}" /></span></li>'),
	infoOptionRange : new Template(
			'<li id="#{styleId}" class="option"><img src="img/checked-blue.gif" alt="Checked Blue" /><span>#{min} to #{max}</span></li>'),
	infoOptionType : new Template(
			'<li id="#{styleId}" class="option"><span class="seller-type-#{label}">#{letter}</span><img src="img/checked-blue.gif" alt="Checked Blue" /><span>#{label}</span></li>'),
	infoOptionHidden : new Template(
			'<input type="hidden" name="#{name}" value="#{value}" class="option" />')
};

function display(id) {
	if ($('children' + id).style.display == 'none') {
		$('down-arrow' + id).style.display = '';
		$('right-arrow' + id).style.display = 'none';
		$('children' + id).style.display = '';
	} else {
		$('down-arrow' + id).style.display = 'none';
		$('right-arrow' + id).style.display = '';
		$('children' + id).style.display = 'none';
	}
}
