dojo.require("dojo.io.*");
dojo.require("dojo.event.*");


var RPtableData;
var RPgetTableData;
var RPqueryLang;
//var RPlibName = "rp_" + $C('NUID');
var RPlibName = "rp_" + (dojo.io.cookie.get('NUID') != null ? dojo.io.cookie.get('NUID') : "");
var rp = new Object();
var RPstoreinitialized = false;
var RPgetinitialized = false;

rp.store = {
	initialize: function() {
		// dojo.debug("rp.store running...");
		//this.connectSQL();
		var results = dojo.storage.get(RPlibName);
		// dojo.debug("rp.store RPlibName is: " + RPlibName);
		// dojo.debug("rp.store results are: " + results);
		var self = this;
		if(results != null && results != "") {
			// build the table with existing info
			try { // check to make sure we have a working local data set
				RPtableData = eval(results);
			} catch(e) { // if it's bad, clear it and try again
				results = null;
				try {
					dojo.storage.remove(RPlibName);
				} catch(e2) {
					dojo.storage.clear();
				}
				rp.store.initialize();
				return;
			}
		} else {
			//build the table
			jsonInit = "{\"PLAYS\":[]}";
			self.buildTable(jsonInit);
			//danCommentself.saveData(RPlibName,RPtableData.toSource());
			self.saveData(RPlibName,rpToSource(RPtableData));
		}
		RPstoreinitialized = true;
	},

	saveData: function(key,jsonData) {
		//fix for the funny toSource method at bottom of file
		if(jsonData.indexOf("(") != 0) {
			//append parens onto string to make compatible
			jsonData = "(" + jsonData + ")";
		}
		try { dojo.storage.remove(key); } catch(e) { dojo.debug("failed on dojo.storage.remove(" + key + ")");}
		rpStorage._save(key,jsonData);
	},

	buildTable: function(jsonData) {
		RPtableData = eval("(" + jsonData + ")");
	},

	appendPlaysTable: function(tid,tn,aid,an,lid,ln,d,x,o,gid) {
		inData = "{id: \"" + tid + "\", n: \"" + tn + "\", an: \"" + an + "\", aid: \"" + aid  + "\", ln: \"" + ln + "\", lid: \"" + lid  + "\", d: \"" + d  + "\", x: \"" + x  + "\", o: \"" + o + "\", gid: \"" + gid + "\"}";
		var playsData =eval("(" + inData + ")");
		if(!RPtableData.PLAYS) {
			// race condition, we need to wait
			setTimeout("this.appendPlaysTable(tid,tn,aid,an,lid,ln,d,x,o,gid)",500);
		}
		else {
			// we need to reverse the in data so we can add it on last to first 
			RPtableData.PLAYS.unshift(playsData);
		}
		if((self.window.opener) && (typeof self.window.opener.RPgetTableData == 'object')) {
			//danComment//self.window.opener.rp.get.buildTable(RPtableData.toSource());
			self.window.opener.rp.get.buildTable(rpToSource(RPtableData));
		}
		//danComment//this.saveData(RPlibName,RPtableData.toSource());
		this.saveData(RPlibName,rpToSource(RPtableData));

	}
};

rp.get = {
	initialize: function() {
		// dojo.debug("rp.store running...");
		this.connectSQL();
		var results = dojo.storage.get(RPlibName);
		// dojo.debug("rp.get RPlibName is: " + RPlibName);
		// dojo.debug("rp.get results are: " + results);
		var self = this;
		if(results != null && results != "") {
			// build the table with existing info
			try { // check to make sure we have a working local data set
				RPgetTableData = eval(results);
			} catch(e) { // if it's bad, clear it and try again
				results = null;
				try {
					dojo.storage.remove(RPlibName);
				} catch(e2) {
					dojo.storage.clear();
				}
				rp.get.initialize();
				return;
			}
		}
		else {
			//build the table
			jsonInit = "{\"PLAYS\":[]}";
			self.buildTable(jsonInit);
			//danComment//self.saveData(RPlibName,RPgetTableData.toSource());
			self.saveData(RPlibName,rpToSource(RPgetTableData));
		}
		RPgetinitialized = true;
	},

	saveData: function(key,jsonData) {
		//fix for the funny toSource method at bottom of file
		if(jsonData.indexOf("(") != 0) {
			//append parens onto string to make compatible
			jsonData = "(" + jsonData + ")";
		}
		try { dojo.storage.remove(key); } catch(e) { dojo.debug("failed on dojo.storage.remove(" + key + ")");}
		rpLib._save(key,jsonData);
	},

	buildTable: function(jsonData) {
		RPgetTableData = eval("(" + jsonData + ")");
	},

	connectSQL: function() {
		var columnDefs = {
		PLAYS: { id: { type: "Number" },
			n: { type: "String" },
			an: { type: "String" },
			aid: { type: "Number" },
			ln: { type: "String" },
			lid: { type: "Number" },
			d: { type: "Number" },
			x: { type: "String" },
			o: { type: "Number" },
			gid: { type: "Number" } }
		};
	    // First we precompile the query language object with the schema...
	    RPqueryLang = TrimPath.makeQueryLang(columnDefs);
	},

	getRecentTracks: function(disp,ret,append,term) {
			// get tracks	
			var statement = RPqueryLang.parseSQL(
			"SELECT PLAYS.* " +
			"FROM PLAYS" 
			); 
			var recent = statement.filter(RPgetTableData);
			if(recent.length > 0) {
			loadContent("http://home.gb.napster.com/info/fragments/last_played.html", "content_head");
			var intCount = 0;
			var objDate = new Date();
			var startTime = objDate.getTime();
			var self = this; 
			var resultData = new Array();
			var initialReturn = 0;
			var objInterval = setInterval( function(){
			var trackData = new Object();
			trackData['artist_name'] = recent[intCount]['an'];
			trackData['artist_name_sort'] = trackData['artist_name'];
			trackData['artist_id'] = recent[intCount]['aid'];
			trackData['album'] = recent[intCount]['ln'];
			trackData['album_sort'] = trackData['album'];
			trackData['album_id'] = recent[intCount]['lid'];
			trackData['genre_id'] = recent[intCount]['gid'];
			trackData['track'] = recent[intCount]['n'];
			trackData['track_sort'] = trackData['track'];
			trackData['track_id'] = recent[intCount]['id'];
			trackData['track_number'] = recent[intCount]['o'];
			trackData['duration'] = recent[intCount]['d'];
			trackData['explicit'] = recent[intCount]['x'];
					resultData[resultData.length] = trackData;
					intCount++;
					if(resultData.length >= disp) {
							var data = resultData;
							//empty out result data
							resultData = new Array();
							if(initialReturn < 1) {
								eval(ret);
								initialReturn++;
							}
							else {
								eval(append);
							}
					}
					if( intCount >= recent.length ){
						// do this to pick up remainder
						var data = resultData;

						//empty out result data
						resultData = new Array();
						if(data.length > 0) {
							if(initialReturn < 1) {
									eval(ret);
									initialReturn++;
							}
							else {
									eval(append);
							}
						}
						clearInterval( objInterval );
						eval(term);
					}
			}, 1 );
			}
			else {
			var data = '0';
				eval(ret);
				eval(term);
			}
	}
};


function rpToSource(obj) {
	if(!obj.toSource) {
		obj.toSource=function(){
			if (this instanceof String){
				return '(new String("'+this.replace(/"/g, '\\"')+'"))';
			}
			var str=(this instanceof Array) ? '[' : (this instanceof Object) ? '{' : '(';
			EACH: for (var i in this){
					if (typeof this[i] == 'function') {
						continue;
					}
					if (this instanceof Array == false) {
						str+=(i.match(/\W/)) ? '"'+i.replace('"', '\\"')+'":' : i+':';
					}
					if (typeof this[i] == 'string'){
						str+='"'+this[i].replace(/\"/g, '\\"') + '"';
					}
					else if (this[i] instanceof Date){
						str+='new Date("'+this[i].toGMTString()+'")';
					}
					else if (this[i] instanceof Array || this[i] instanceof Object){
						//str+=this[i].toSource();
						str+=rpToSource(this[i]);
					}
					else {
						str+=this[i];
					}
					str+=', ';
			};
			// length exception to account for empty arrays
			str=str.substring(0, ( (str.length > 1 && (str.lastIndexOf(",") == (str.length - 2) ) ) ? str.length-2 : str.length) )+( (this instanceof Array) ? ']' : (this instanceof Object) ? '}' : ')');
		return str;
		}
	}
	return obj.toSource();
}



/*

if (!Object.prototype.toSource){
    Object.prototype.toSource=function(){
        if (this instanceof String){
            return '(new String("'+this.replace(/"/g, '\\"')+'"))';
        }
        var str=(this instanceof Array) ? '[' : (this instanceof Object) ? '{' : '(';
        SRC: for (var i in this){
            if (this[i] != Object.prototype.toSource) {
				if(typeof this[i] == 'function') {
					continue SRC;
				}
                if (this instanceof Array == false) {
                    str+=(i.match(/\W/)) ? '"'+i.replace('"', '\\"')+'":' : i+':';
                }
                if (typeof this[i] == 'string'){
                    str+='"'+this[i].replace(/\"/g, '\\"') + '"';
                }
                else if (this[i] instanceof Date){
                    str+='new Date("'+this[i].toGMTString()+'")';
                }
                else if (this[i] instanceof Array || this[i] instanceof Object){
                    str+=this[i].toSource();
                }
                else {
                    str+=this[i];
                }
                str+=', ';
            }
        };
        // length exception to account for empty arrays
        str=str.substring(0, ( (str.length > 1 && (str.lastIndexOf(",") == (str.length - 2) ) ) ? str.length-2 : str.length) )+( (this instanceof Array) ? ']' : (this instanceof Object) ? '}' : ')');
    return str;
    }
}
*/
