var fbDatabasejoin = FbElement.extend({
	initialize: function(element, options) {
		this.plugin = 'fabrikdatabasejoin';
		this.options = {
			'liveSite':'',
			'popupform':49,
			'id':0,
			'formid':0,
			'key':'',
			'label':'',
			'popwiny':0,
			'windowwidth':360,
			'displayType':'dropdown'
		};
		$extend(this.options, 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',
			evalScripts:true,
			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.get('value');
					return v;
				}
				return null;
			});
			return v;
		}
		if($type(this.element.get('value')) === false){
			return '';
		}
		return this.element.get('value');
	},
	
	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){
		var found = false;
		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;
					found = true;
					break;
				}
			}
		}
		if(!found && this.options.show_please_select){
			this.element.options[0].selected = true;
		}
		this.options.value = val;
	},
	//
	appendInfo: function(data){
		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;
				}
					
				//make ajax call to update this dd
				// code requires 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.getForm().getElement('input[name=rowid]').get('value')
					},
					onSuccess:function(json){
						var values = this.getValues();
						json = Json.evaluate(json);
						json.each(function(row){
						
						
						if (values.contains(row.value) == false) {
							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',
										'checked':true,
							  		'name': this.options.element,
							  		'value': row.value
							  	}), new Element('span').setText(row.text)]));
									opt.injectAfter($(this.element.id).getElements('.fabrik_subelement').getLast());
						  }else{
								opt = new Element('option', {'value':row.value,'selected':'selected'}).appendText(row.text);
								$(this.element.id).adopt(opt);
							}
							
						}
						}.bind(this));
						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);
			}
		}
	},
	
	getValues:function()
	{
		var v = $A([]);
		var search = (this.options.display_type != 'dropdown') ? 'input' : 'option';
			$(this.element.id).getElements(search).each(function(f){
				v.push(f.value);
			});
		return v;
	},
	
	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 (action == 'load') {
			eval(js);
			return;
		}
		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 {
			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).selectedIndex;
  	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 = new 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');
  		}
  	});
  }
});
