﻿var MultipleOptionSelect = new Class({
	options : {
		intMinVal : -1
	},
	initialize : function (source, sink, btnAdd, btnDel, input, options)
	{
		this.setOptions(options)
		this.source = source;
		this.sink = sink;
		this.btnAdd = btnAdd;
		this.btnDelete = btnDel;
		this.input = input;
		this.addEvents();
	},
	
	addEvents : function ()
	{
		// set up the toggle events
		this.btnAdd.addEvent('click',function(e)
		{
			this.addSelection();
		}.bind(this));
		this.source.addEvent('dblclick',function(e)
		{
			this.addSelection();
		}.bind(this));
		
		this.btnDelete.addEvent('click',function(e)
		{
			this.deleteSelection();
		}.bind(this));
		this.sink.addEvent('dblclick',function(e)
		{
			this.deleteSelection();
		}.bind(this));
	},
	
	addSelection : function ()
	{
		if (this.source.selectedIndex >= 0) {
			var elOptNew = new Element('option');
			elOptNew.text = this.source.options[this.source.selectedIndex].text;
			elOptNew.value = this.source.options[this.source.selectedIndex].value;
			// remove the entire area selection
			// or the added entry if it exists
			var i;
			for (i = this.sink.length - 1; i>=0; i--) {
				if ((this.sink.options[i].value == this.options.intMinVal) ||
					(this.sink.options[i].value == elOptNew.value)) {
					this.sink.remove(i);
				}
			}						
			try {
				this.sink.add(elOptNew, null); // standards compliant; doesn't work in IE
			}
			catch(ex) {
				this.sink.add(elOptNew); // IE only
			}
			this.assignInputValue();
		}
		else {
			new Confirmer("Select a value first");
		}

	},
	deleteSelection : function() {
		var i;
		for (i = this.sink.length - 1; i>=0; i--) {
			if (this.sink.options[i].selected) {
				this.sink.remove(i);
			}
		}
		if (this.sink.options.length == 0 )
		{
			// add the entire area option
			var el = new Element('option');
			el.value = this.options.intMinVal;
			el.text = "Entire Area";
			try {
				this.sink.add(el, null); // standards compliant; doesn't work in IE
			}
			catch(ex) {
				this.sink.add(el); // IE only
			}				
		}
		this.assignInputValue();
	},
	
	assignInputValue : function()
	{
		if ( this.input )
		{
			this.input.value = '';
			for (var i=0; i < this.sink.options.length; i++) {
				this.input.value = this.input.value ==
					'' ? this.sink.options[i].value : this.input.value + ',' + this.sink.options[i].value;
			}
		}	
		else 
		{
			alert('input for storing values was not found');
		}
	}
});

MultipleOptionSelect.implement(new Options);