var hasDB = (window.openDatabase) ? true : false;

// executeSql(sqlStatement, arguments, callback, errorCallback);
$(function() {
	// Opens database and verifies RITI_Favorites table
	if(hasDB) var db; loadDatabase();
});


function loadDatabase() {
	try {
		if (window.openDatabase) {
			db = openDatabase("riti_fav", "1.0", "RITI Favorites", 200000);
			if (!db) {
				//alert("Failed to open the database on disk.");
				return false;
			}
		} else {
			//alert("Your browser does not support this feature.");
			return false;
		}
	} catch(err) {
		alert("Error: "+err);
		return false;
	}
	// See if table exists, create one if it doesn't.
	db.transaction(function(tx) {
        tx.executeSql("SELECT COUNT(*) FROM RITI_Favorites", [], function(tx, result) {
			//alert("Table already exists. Contains "+result.rows.length+" rows.");
        }, function(tx, error) {
			//alert("Table does not exist. Attempting to create a new one.");
            tx.executeSql("CREATE TABLE RITI_Favorites (id REAL UNIQUE, title TEXT)", [], function(tx, result) {
				//alert("Table creation successful.");
            }, function(tx, error) {
				//alert("Table creation failed.");
			});
        });
    });
}

function getFavorites() {
	if(!hasDB) {
		$("<p />").addClass("message").text("Your browser does not support this feature.").insertAfter("#favoritesList");
		return null;
	}
	db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM RITI_Favorites ORDER BY title ASC", [], function(tx, result) {
			if(result.rows.length) {
				var numRows = result.rows.length;
				if(numRows > 1) {
					var rnd = Math.floor(Math.random()*numRows);
					var row = result.rows.item(rnd);
					var thisItem = $("<li />").data("changePanelArgs", {gameid:row["id"], sig:"\"Favorites\", \"right\", {}"});
					thisItem.addClass('listViewItem separated borderPink').text("Random Game").appendTo("#favoritesList").prepend("<span class='text-right randomCount'>"+numRows+"</span>");
				}
				
				for (var i=0; i<numRows; i++) {
					var row = result.rows.item(i);
					var thisItem = $("<li />").data("changePanelArgs", {gameid:row['id'], sig:"\"Favorites\", \"right\", {}"});
					thisItem.addClass('listViewItem arrow-right borderPink').text(row['title']).appendTo("#favoritesList");
				}
				$("#favoritesList .listViewItem").each(function() {
					var changePanelArgs = $(this).data("changePanelArgs");
					$(this).bind("click", function() { changePanel("Game", "left", changePanelArgs); });
				});
			} else {
				$("<p />").addClass("message").text("You have no favorites yet.").insertAfter("#favoritesList");
			}
        }, function(tx, error) {
			$("<p />").addClass("message").text("You have no favorites yet.").insertAfter("#favoritesList");
        });
    });
}

function checkIfFavorite(aID) {
	db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM RITI_Favorites WHERE id = ?", [aID], function(tx, result) {
            if (result.rows.length) {
				flipFavButton(true);
			} else {
				flipFavButton(false);
			}
        }, function(tx, error) {
			flipFavButton(false);
        });
    },
	function(error) {
		flipFavButton(false);
	});
}

function addFavorite(id, title) {
	db.transaction(function(tx) {
		tx.executeSql("INSERT INTO RITI_Favorites (id, title) VALUES (?, ?)", [id, title], function(tx, result) {
			//alert("Added "+title+" (id "+id+") to local database.");
			flipFavButton(true);
		}, function(tx, error) {
			//alert("Failed to add "+title+" (id "+id+") to local database.");   
		});
	}); 
}

function removeFavorite(id) {
	db.transaction(function (tx) {
		tx.executeSql("DELETE FROM RITI_Favorites WHERE id = ?", [id], function(tx, result) {
			//alert("Removed "+title+" (id "+id+") from local database.");
			flipFavButton(false);
		}, function(tx, error) {
			//alert("Failed to remove "+title+" (id "+id+") from local database.");   
		});
	}); 
}

function clearFavorites() {
	var answer = confirm ("Are you sure you want to clear your favorites?")
	if(answer && hasDB) {
		db.transaction(function (tx) {
			tx.executeSql("DELETE FROM RITI_Favorites", [], function(tx, result) {
				$("#favoritesList .listViewItem").fadeTo("normal", 0, function () { $(this).remove(); });
				$("<p />").addClass("message").text("You have no favorites yet.").insertAfter("#favoritesList");
				//alert("Local database cleared.");
			}, function(tx, error) {
				//alert("Failed to clear local database.");   
			});
		}); 
	}
	togglePrefs();
}

function createFavButton() {
	if(hasDB) {
		var favBtn = $("<p />").attr("id", "favButton").insertAfter(".gameTitle");
		checkIfFavorite(currentGameID);
	}
}

function flipFavButton(isFav) {
	$("#favButton").empty().unbind("click");
	if(isFav) {
		$("#favButton").append('<img src="images/star_fav.png" alt="" width="22" height="20" />').append("<span>This is a favorite</span>").bind("click",
		function() {
			removeFavorite(currentGameID);
		});
	} else {
		$("#favButton").append('<img src="images/star_nofav.png" alt="" width="22" height="20" />').append("<span>Add to favorites</span>").bind("click",
		function() {
			addFavorite(currentGameID, currentGameTitle);
		});
	}
}