

(function(){
	
	var saw = window.saw;
	
	saw.lang = {
		defaultCode:"en",
		_code:"en"
	};	
	
	
	saw.lang.code = function(langCode){
		if(arguments.length){
			this._code = langCode;
			return this;
		}
		return this._code;
	};
	
	
	saw.lang.table = function(tableKey, rows){
		var exists = typeof(this.tables[tableKey]) === "object",
			tbl;
		if(arguments.length===1){
			return exists ? this.tables[tableKey] : null;
		}else if(exists && !rows){
			this.tables[tableKey].remove();
		}else if(!exists && $.isArray(rows)){
			tbl = this.tables[tableKey]	= new Table(tableKey, rows);
			return tbl;
		}
		return this;
	};
	
	// row = {"key":"sample_lang_key", "en": "Sample Language Key", "es":"El Samplo Lango Keyo"}
	var Table = saw.lang.Table = function(key, rows){
		assert(!!key, "saw.lang.Table construct must be given a key.");
		this.key = key;
		this._rows = [];
		if(rows.length) this.addRows(rows);
	}
	Table.prototype = {		
		key:null,
		keyCol:"key",
		_rows:null,
		addRow:function(row){			
			return new TableRow(this, row);;
		},
		addRows:function(){
			var rows = [];
			for(var r=0; r < rows.length; r++){
				rows.push(this.addRow(rows[r]));
			}
			return rows;
		},
		row:function(rowKey){
			for(var r = 0; r<this._rows; r++){
				if(this._rows[r][this.keyCol] == rowKey){
					return this._rows[r];
				}
			}			
			return this.addRow({"key":rowKey, "en":rowKey});
		},		
		remove:function(){
			delete saw.lang.tables[this.key];
		}
	};
	
	
	
	var TableRow = saw.lang.TableRow = function(table, data){
		this.table(table);
		this.clear();
		this.data(data);
	};
	TableRow.prototype = {
		clear:function(){
			this._data = {};
		},
		_data:null,
		data:function(value){
			if(arguments.length){
				$.extend(this._data, value);
				return this;
			}
			return this._data;
		},
		_table:null,
		table:function(table){
			if(arguments.length){
				//to do - remove from previous table
				this._table = table;	
				table
				return this;
			}
			return this._table;
		},		
		val:function(langCode){
			langCode = langCode!=null ? langCode : saw.lang.code();
			var val = this.data()[langCode] || this.data()[saw.lang.defaultCode];
			return val!=null ? val : null;
		},
		toString:function(){
			return this.val() || "";
		}
	}
	
	
	/*
		LANGUAGE TABLES, WHERE ALL OF THE TRANSLATIONS ARE STORED
	*/
	saw.lang.tables = {};	
	
	//Create the common translation table
	saw.lang.table("common", [
		{"key":"cover", "en":"Cover"}
	]);
	
})();
