/*
 * Core jsodb constructor - we create instances of this
 */
var jsodb = function(extend){
	this.cache = [];	
	this.data = [];
	this.add = function(obj){ 	return this.data.push(obj); },
	this.extend = function(obj){ 	for(k in obj){ this[k] = obj[k]; }}
	this.clearCache = function(){return this.cache = []}
	this.appendCache = function(obj){ this.cache.push(obj)}
}


/*
 * Define our own jsodb tables - we may not use all of them
 * but it's good for reference
 */

affUI.locations	= new jsodb();
affUI.interests 	= new jsodb();
affUI.offers 		= new jsodb();

/*
 * Extend the offers jsodb table with custom functions
 */

affUI.offers.extend({
	runFilter : function(){
		var locationSelections = arguments[0];
		var interestSelections = arguments[1];

		this.clearCache();
		
		/*
		 * Allow location to be empty (select all)
		 */
		
		if(locationSelections.length == 0){
			this.cache = this.data;
		}else{
			if(locationSelections instanceof Array){
				for(s=0; s<locationSelections.length;s++){				
					var value = locationSelections[s];				 
					this.applyFilter(value, 'locations');
				}
			}
		}
		
		if(interestSelections instanceof Array){
			for(s=0; s<interestSelections.length;s++){				
				var value = interestSelections[s];				 
				this.applyFilter(value, 'interests', this.cache.slice()); // Copy our current data cache
			}
		}
		
		return this.cache;
	},
	applyFilter:function(compareValue, collection, runAgainst){
		var dataArray = typeof runAgainst != 'undefined' ? runAgainst : this.data;
		
		this.clearCache();
		
		for(i=0; i<dataArray.length; i++){
			var entry = dataArray[i];
			for(j=0;j<entry[collection].length;j++){
				if(compareValue == entry[collection][j]){
					this.appendCache(entry);
					continue;
				}
			}				
		}		
	}
});	


/*
 * Finally, add the data
 */

affUI.locations.add({id:5000, name:'Chicago'});
affUI.locations.add({id:5001, name:'Washington D.C'});
affUI.locations.add({id:5002, name:'New York City'});	

affUI.interests.add({id:6000,name:'City Getaways'});
affUI.interests.add({id:6001,name:'Family'});
affUI.interests.add({id:6002,name:'Romance'});
affUI.interests.add({id:6003,name:'Shopping'});
affUI.interests.add({id:6004,name:'Spa'});
affUI.interests.add({id:6005,name:'Government'});
affUI.interests.add({id:6006,name:'Business'});
affUI.interests.add({id:6007,name:'Extended Stay'});

affUI.offers.add({id: 1000, locations:[5000], interests:[6004, 6006, 6007]});
affUI.offers.add({id: 1001, locations:[5001,5002], interests:[6001, 6003]});
affUI.offers.add({id: 1002, locations:[5002], interests:[6005, 6006]});
affUI.offers.add({id: 1003, locations:[5000,5001], interests:[6002, 6004]});
affUI.offers.add({id: 1004, locations:[5001], interests:[6001, 6003, 6007]});
affUI.offers.add({id: 1005, locations:[5001,5002], interests:[6000, 6001]});
affUI.offers.add({id: 1006, locations:[5000,5001,5002], interests:[6000,6001,6006]});
affUI.offers.add({id: 1007, locations:[5000,5002], interests:[6004, 6005]});
