var Query = {
	send: function(queryInstance, url, onSuccess, onFailure) {
		new Ajax.Request(url, {
			method: 'post',
			contentType: 'text/plain',
			postBody: Object.toJSON(queryInstance),
			onSuccess: onSuccess,
			onFailure: onFailure});
	},
	
	getValue: function(elementID) {
		var element = $(elementID);
		var value;
		if (!element.hasClassName('empty'))
			value = element.value;
		else
			value = '';
		
		return value;
	},

	getValueArray: function(elementID) {
		var element = $(elementID);
		var values;
		if (!element.hasClassName('empty'))
			values = element.value.split(',');
		else
			values = [];
			
		return values;
	},
	
	isChecked: function(elementID) {
		return $(elementID).hasClassName('checked');
	},
	
	getTimeRanges: function() {
        var rangeList = [];
		return $A($('timeRanges').rows).inject(rangeList, Query._getTimeRange);
	},
	
	_getTimeRange: function(rangeList, row, index) {
		var startmonth = Query.getValue('startmonth_' + String(index));
		var startyear  = Query.getValue('startyear_' + String(index));
		var endmonth   = Query.getValue('endmonth_' + String(index));
		var endyear    = Query.getValue('endyear_' + String(index));
		
		if (startyear != '' || endyear != '') {
            var timeRange = {
    			startmonth: startmonth,
    			startyear:  startyear,
    			endmonth:   endmonth,
    			endyear:    endyear
    		}
    		
            rangeList.push(timeRange);
        }
		return rangeList;
	},
	
	getDataSources: function() {
		return $('dataSources').getElementsByClassName('checked').invoke('readAttribute', 'collection');
	}
}

Query.Format = {
	HTML: 1,
	CSV: 2,
	TEXT: 3,
	TEXT_AND_CRITERIA: 4,
	CRITERIA: 5
}

Query.Fieldset = {
	NONE: 0,
	VIEW: 1,
	DOWNLOAD: 2,
	VIEW_TEXT: 3
}

Query.Basic = Class.create()
Query.Basic.prototype = {
	initialize: function(queryFormat, queryFieldset) {
		this.type = 'BASIC';
		this.format = queryFormat;
		this.fieldset = queryFieldset;
		this._loadCriteria();
		
//		if ($('showAsText').checked) {
//			this.format = Query.Format.TEXT;
//			this.fieldset = Query.Fieldset.VIEW_TEXT;
//		}
	},
	
	_loadCriteria: function() {
		this.collections = Query.getDataSources();
		this.scientificnames = Query.getValue('scientificname');
		this.commonnames = Query.getValue('commonname');
		this.regions = Query.getValue('physioregion');
		this.timeranges = Query.getTimeRanges();
		this.showAllEfforts = Query.isChecked('showAllEfforts');
	}
}
