var fbDatabasejoin = FbElement.extend({
	initialize: function(element, options) {
		this.plugin = 'fabrikdatabasejoin';
		this.options = Object.extend({
			'liveSite':'',
			'popupform':49,
			'id':0,
			'formid':0,
			'key':'',
			'label':'',
			'popwiny':0,
			'windowwidth':360,
			'displayType':'dropdown'
		}, options || {});
		
		this.setOptions(element, this.options);
		//if users can add records to the database join drop down
		if($(element + '_add')){
			this.startEvent = this.start.bindAsEventListener(this);
			$(element + '_add').addEvent('click', this.startEvent);
			
			//register the popup window with the form this element is in
			//do this so that the database join drop down can be updated
			oPackage.bindListener('form_' + this.options.popupform, 'form_' + this.options.formid);
		}
		
		if($(element + '_select')){
			$(element + '_select').addEvent('click', this.selectRecord.bindAsEventListener(this));
			
			//register the popup window with the form this element is in
			//do this so that the database join drop down can be updated
			oPackage.bindListener('table_' + this.options.tableid, 'form_' + this.options.formid);
		}
		
		if(this.options.showDesc === true) {
			this.element.addEvent('change', this.showDesc.bindAsEventListener(this));
		}
	},
	
	selectRecord: function(e){
  	e = new Event(e).stop();
  	var id = this.element.id + '-popupwin';
  	var url = this.options.liveSite + "index.php?option=com_fabrik&view=table&tmpl=component&layout=dbjoinselect&_postMethod=ajax&tableid=" + this.options.tableid;
  	url += "&triggerElement="+this.element.id;
  	url += "&winid="+id;
  	this.windowopts = {
			'id': id,
			title: 'Select',
			contentType: 'xhr',
			loadMethod: 'xhr',
			contentURL: url,
			width: this.options.windowwidth.toInt(),
			height: 320,
			y: this.options.popwiny,
			'minimizable': false,
			'collapsible': true,
			onContentLoaded: function(){
				oPackage.resizeMocha(id);
			}
		};
		if(this.options.mooversion > 1.1){
			var mywin = new MochaUI.Window(this.windowopts);
		}else{
			document.mochaDesktop.newWindow(this.windowopts);
		}
	},
	
	getValue:function(){
		this.getElement();
		if(!this.options.editable){
			return this.options.value;
		}
		if($type(this.element) === false){
			return '';
		}
		if(this.options.display_type != 'dropdown') {
			var v = '';
			this._getSubElements().each(function(sub){
				if(sub.checked){
					v = sub.getValue();
					return v;
				}
				return null;
			});
			return v;
		}
		if($type(this.element.getValue()) === false){
			return '';
		}
		return this.element.getValue();
	},
	
	start: function(event){
		var e = new Event(event);
		var url = this.options.liveSite + "index.php?option=com_fabrik&view=form&tmpl=component&_postMethod=ajax&fabrik=" + this.options.popupform;
		var id = this.element.id + '-popupwin';
		url += "&winid="+id;
		this.windowopts = {
			'id': id,
			title: 'Add',
			contentType: 'xhr',
			loadMethod:'xhr',
			contentURL: url,
			width: this.options.windowwidth.toInt(),
			height: 320,
			y:this.options.popwiny,
			'minimizable':false,
			'collapsible':true,
			onContentLoaded: function(){
				oPackage.resizeMocha(id);
			}
		};
				
		if(this.options.mooversion > 1.1){
			this.win = new MochaUI.Window(this.windowopts);
		}else{
			document.mochaDesktop.newWindow(this.windowopts);
		}
		e.stop();

	},
	
	update:function(val){
		this.getElement();
		if($type(this.element) === false){
			return;
		}
		if (!this.options.editable) {
			this.element.innerHTML = '';
			if(val === ''){
				return;
			}
			val = val.split(this.options.splitter);
			//was a security issue as options.data contained unaccessible element data
			//var h = $H(this.options.data);
			var h = this.form.getFormData();
			if ($type(h) === 'object') {
				h = $H(h);
			}
			val.each(function(v){
				if ($type(h.get(v)) !== false) {
					this.element.innerHTML += h.get(v) + "<br />";
				}else{
					//for detailed view prev/next pagination v is set via elements 
					//getROValue() method and is thus in the correct format - not sure that
					// h.get(v) is right at all but leaving in incase i've missed another scenario 
					this.element.innerHTML += v + "<br />";
				}	
			}.bind(this));
			return;
		}
		this.setValue(val);
	},
	
	setValue:function(val){
		if($type(this.element.options) !== false) { //needed with repeat group code
			for (var i = 0; i < this.element.options.length; i++) {
				if (this.element.options[i].value == val) {
					this.element.options[i].selected = true;
					break;
				}
			}
		}
		this.options.value = val;
	},
	//
	appendInfo: function(data){
		var opts = [];
		if(data === '' || $type(data.data) === false){
			return;
		}
		var key = this.options.key;
		var label = this.options.label;
		data = data.data;
		outerLoop:
		for(var i=0;i<data.length;i++){
			if($type(data[i] === 'array')){
				var group = data[i];
			}else{
				group = data;
			}
			for(var j=0;j<group.length;j++){
				if($type(data[i] === 'array')){
					var row = group[j];
				}else{
					row = group;
				}
				// $$$ hugh - elements might not be published to table, and we don't use these anyway
				//if( row[key] && row[label] ){
					
					//make ajax call to update this dd
				
					// code requiers us to post and querystring the main vars - not sure y but doesnt work otherwise
					var myajax = new Ajax( this.options.liveSite + 'index.php?option=com_fabrik&format=raw&controller=plugin&task=pluginAjax&method=ajax_getOptions', {
						data :{
							'option':'com_fabrik',
							'format':'raw',
							'controller':'plugin',
							'task':'pluginAjax',
							'plugin':'fabrikdatabasejoin',
							'method':'ajax_getOptions',
							'element_id':this.options.id,
							'formid':this.options.formid,
							'rowid':this.form.form.getElement('input[name=rowid]').getValue()
						},
						onSuccess:function(json){
							json = Json.evaluate(json);
							json.each(function(row){
							
								if(this.options.display_type != 'dropdown') {
									var opt = new Element('div',{'class':'fabrik_subelement'}).adopt(
											new Element('label').adopt([
											new Element('input', {'class':'fabrikinput','type':'radio','name':this.options.element,'value':row.value}),
											new Element('span').setText(row.text)
											])
									);
								}else{
									opt = new Element('option', {'value':row.value}).appendText(row.text);
									if(this.options.value.indexOf(row.value) != -1){
										opt.selected = "selected";
									}
								}
								opts.push(opt);
							}.bind(this));
							$(this.element.id).empty();
							$(this.element.id).adopt(opts);
							this.setErrorMessage('updated', 'fabrikSuccess');
						}.bind(this)
					}).request();
					break outerLoop;
				//}
				
			}
		}
		if($type(this.element) === false){
			return;
		}
		var id = this.element.id + '-popupwin';
		//this if was at the end of the onSuccess method - but if no data added it wasnt called
		if ($type($(id)) !== false) {
			if (this.options.mooversion > 1.1) {
				//@TODO this isnt working in IE8 - some issue with mt element.retrive() method
				if(this.options.mooversion == 1.2){
					id = $(id);
				}
				MochaUI.closeWindow(id);
			} else {
				document.mochaDesktop.closeWindow(id);
			}
		}
	},
	cloned: function(c){
		//@TODO this is going to wipe out any user added change events to the element
		// cant' figure out how to just remove the cdd change events.
		this.element.removeEvents('change');
		//c is the repeat group count
	},
	
	addNewEvent: function( action, js ){
		if (this.options.displayType == 'dropdown') {
			if (this.element) {
		  	this.element.addEvent(action, function(e){
		  		e = new Event(e).stop();
		  		($type(js) === 'function') ? js.delay(0) : eval(js);
		  	});
	  	}
		} else {
			if (action == 'load') {
				eval(js);
			} else {
				this._getSubElements();
				this.subElements.each(function(el){
					el.addEvent(action, function(e){
						($type(js) === 'function')?js.delay(0):eval(js);
					});
				});
			}
		}
	},
	
	showDesc: function(e){
  	e = new Event(e);
  	var v = $(e.target).getValue();
  	var c = this.element.findClassUp('fabrikElementContainer').getElement('.dbjoin-description');
  	var show = c.getElement('.description-' + v);
  	c.getElements('.notice').each(function(d){
  		if (d === show) {
  			var myfx = Fx.Style(show, 'opacity', {
  				duration: 400,
  				transition: Fx.Transitions.linear
  			});
  			myfx.set(0);
  			d.setStyle('display', '');
  			myfx.start(0, 1);
  		} else {
  			d.setStyle('display', 'none');
  		}
  	});
  }
});