function deleteGuestList() {
	alert ('DELETING');
	db.transaction(
				   function (transaction) {
					   transaction.executeSql('DROP TABLE IF EXISTS guests;');
				   }
				   );
}

function deleteTable() {
	db.transaction(
				   function (transaction) {
					   transaction.executeSql('DROP TABLE IF EXISTS people;');
				   }
				   );
}

function deleteNote(deleteId) {
	db.transaction(
				   function (transaction) {
					   transaction.executeSql('DELETE FROM people WHERE id="'+ deleteId +'";');
				   }
				   );
	listAllNotes();
	
}

function deleteGuest(deleteId) {
	db.transaction(
				   function (transaction) {
					   transaction.executeSql('DELETE FROM guests WHERE id="'+ deleteId +'";');
				   }
				   );
	listAllGuests();
	
}

function initdb(){

var mydb;
try {
    if (window.openDatabase) {
        db = openDatabase("MyNotes", "1.0", "iBride - Notes", 200000);
        if (!db)
            alert("Failed to open the database.  This is probably because the version was bad or there is not enough space left in this domain's quota");
    } else
        alert("Couldn't open the database.");
} catch(err) { }

createTablePeople(db);
createTableChecklist(db);
createTableGuests(db);
createTableUrl(db)
}
 
function errorHandler(transaction, error) 
{ 
    // Error is a human-readable string. 
    alert('Error: '+error.message+' (Code '+error.code+')'); 
  	errorMessage = error.message;
    // Handle errors here 
    var we_think_this_error_is_fatal = true; 
    if (we_think_this_error_is_fatal) return true; 
    return false; 
} 
  
function dataHandler(transaction, results) 
{ 
    // Handle the results 
	var queryResult = "";
	string ="";
    for (var i=0; i<results.rows.length; i++) { 
        // Each row is a standard JavaScript array indexed by 
        // column names. 
        var row = results.rows.item(i); 
		queryResult = queryResult + row['noteName'];
        string = string + row['noteName'] + " (ID "+row['id']+")\n"; 
		noteName = row['noteName'];
		noteCategory = row['noteCategory'];
		notePhone = row['notePhone'];
		noteContact = row['noteContact'];
		noteCost = row['noteCost'];
		noteDeposit = row['noteDeposit'];
		noteDate = row['noteDate'];
		noteBalance = row['noteBalance'];
		noteDue = row['noteDue'];
		noteDescription = row['noteDescription'];
    } 
	if ( queryResult == "" ) { clientStatus="NEW"; return; }
	clientStatus="EXISTING";
	document.getElementById('noteCategory').value = noteCategory;
	document.getElementById('noteName').value = noteName;
	document.getElementById('notePhone').value = notePhone;
	document.getElementById('noteContact').value = noteContact;
	document.getElementById('noteCost').value = noteCost;
	document.getElementById('noteDeposit').value = noteDeposit;
	document.getElementById('noteDate').value = noteDate;
	document.getElementById('noteBalance').value = noteBalance;
	document.getElementById('noteDue').value = noteDue;
	document.getElementById('noteDescription').value = noteDescription;
} 

function listAllNotes() {
	initdb();
	var search_query = 'SELECT * from people';
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            listHandler, errorHandler);
    } 
); 	
}

function listHandler(transaction, results) 
{ 
	var queryResult = "";
	var htmlResults = "";
	var string ="";
    for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		rowNoteName = row['noteName'];
		rowNoteId = row['id'];
		queryResult = queryResult + row['noteName'] + "\n";
		htmlResults = htmlResults + '<a href="javascript:deleteNote(\'' + rowNoteId + '\');" onclick="javascript:return confirm(\'Are you sure you want to delete this note?\')"><img src="../images/iphone/delete-icon.png" width="31" height="40" /></a><div id="listing-notes" onclick=\'noteFadeOn(); queryId("'+ rowNoteId + '");\'><p>' + rowNoteName + '<span class="arrow"></span></p></div>';
    } 
	htmlResults = htmlResults + '<img src="../images/iphone/delete-icon.png" width="31" height="40" style="opacity: 0;" />';
	document.getElementById('listing').innerHTML = htmlResults;
	if ( queryResult == "" ) { alert('Unable to find any saved notes.');return; }
} 

function checkNotes(category){
	initdb();
	var search_query = 'SELECT * from people where noteCategory='+'"'+category+'"'+";";
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            noteHandler, errorHandler);
    } 
); 
	
}

function noteHandler(transaction, results) 
{ 
    // Handle the results 
	var queryResult = "";
	var string ="";
    for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		queryResult = queryResult + row['noteName'] + "\n";
		if ( row['noteName'] == "" ) { return;}
		else {
				var img = row['noteName'];
				document.getElementById(img).style.visibility = "visible"; }
    } 
	if ( queryResult == "" ) { return; }
} 

function queryId(noteId){
	setTimeout('document.getElementById("listing").style.display = "none";',800);
	var search_query = 'SELECT * from people where id='+'"'+noteId+'"'+";";
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            dataHandler, errorHandler); 
    } 
); 
}

function query(noteName){
	var search_query = 'SELECT * from people where noteName='+'"'+noteName+'"'+";";
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            dataHandler, errorHandler); 
    } 
); 
}

function update(){
	
	tempCategory = document.getElementById('noteCategory').value;
	tempName = document.getElementById('noteName').value;
	tempPhone = document.getElementById('notePhone').value;
	tempContact = document.getElementById('noteContact').value;
	tempCost = document.getElementById('noteCost').value;
	tempDeposit = document.getElementById('noteDeposit').value;
	tempDate = document.getElementById('noteDate').value;
	tempBalance = document.getElementById('noteBalance').value;
	tempDue = document.getElementById('noteDue').value;
	tempDescription = document.getElementById('noteDescription').value;
	
	if ( clientStatus=="NEW" ) {
		db.transaction( 
        function (transaction) { 
		var transactionValues = 'INSERT into people (noteName, noteCategory, notePhone, noteContact, noteCost, noteDeposit, noteDate, noteBalance, noteDue, noteDescription) VALUES ("'+tempName+'", "'+tempCategory+'", "'+tempPhone+'", "'+tempContact+'", "'+tempCost+'", "'+tempDeposit+'", "'+tempDate+'", "'+tempBalance+'", "'+tempDue+'", "'+tempDescription+'");';
		transaction.executeSql(transactionValues, [], nullDataHandler, errorHandler); 
		}
		);
		alert('Your note has been saved.');
		return;
	}
	
	var update_table = 'UPDATE people set noteContact='+'"'+tempContact+'", noteCost='+'"'+tempCost+'"'+', noteDeposit='+'"'+tempDeposit+'"'+', noteDate='+'"'+tempDate+'", noteBalance='+'"'+tempBalance+'", noteDue='+'"'+tempDue+'", noteDescription='+'"'+tempDescription+'" where noteName='+'"'+tempName+'"'+';';
	
db.transaction( 
    function (transaction) { transaction.executeSql(update_table), myTransactionErrorCallback, myTransactionSuccessCallback }
); 
alert('Your note has been updated.');
}



function myTransactionErrorCallback(error) 
{ 
    alert('Error was '+error.message+' (Code '+error.code+')'); 
} 
  
function myTransactionSuccessCallback() 
{ 
    alert('OK'); 
} 
  

function nullDataHandler(transaction, results) { } 
  
function createTablePeople(db) 
{ 
    db.transaction( 
        function (transaction) { 
  
            /* The first query causes the transaction to (intentionally) fail if the table exists. */ 
            transaction.executeSql('CREATE TABLE IF NOT EXISTS people(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, noteName TEXT NOT NULL DEFAULT "John Doe", noteCategory TEXT NOT NULL DEFAULT "Category", notePhone TEXT NOT NULL DEFAULT " ", noteContact TEXT NOT NULL DEFAULT " ", noteCost TEXT NOT NULL DEFAULT " ", noteDeposit TEXT NOT NULL DEFAULT " ", noteDate TEXT NOT NULL DEFAULT " ", noteBalance TEXT NOT NULL DEFAULT " ", noteDue TEXT NOT NULL DEFAULT " ", noteDescription TEXT NOT NULL DEFAULT " ");', [], nullDataHandler, errorHandler); 
       } 
    ); 	
} 


function createTableChecklist(db)
{ 
    db.transaction( 
        function (transaction) { 
  
            /* The first query causes the transaction to (intentionally) fail if the table exists. */ 
            transaction.executeSql('CREATE TABLE IF NOT EXISTS checklist(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, listStatus TEXT NOT NULL DEFAULT " ");', [], nullDataHandler, errorHandler); 	
       } 
    ); 	
} 

function dataCheckHandler(transaction, results) 
{ 
    for (var i=0; i<results.rows.length; i++) { 
        // Each row is a standard JavaScript array indexed by 
        // column names. 
        var row = results.rows.item(i); 
		queryResult = queryResult + row['listStatus'];
	}
}

function createInitialChecklist() {
	db.transaction( 
        function (transaction) { for (var i=1; i<64; i++) { transaction.executeSql('insert into checklist (listStatus) VALUES ("no");', [], nullDataHandler, errorHandler); };     	
       } 
    ); 	
}

function statusChecklist() {
	initdb();
	var search_query = 'SELECT * from checklist';
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            checklistHandler, errorHandler);
    } 
); 	
}

function checklistHandler(transaction, results) 
{ 
	var queryResult = "";
    for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		rowListStatus = row['listStatus'];
		rowNoteId = row['id'];
		queryResult = queryResult + rowNoteId + " " + rowListStatus +"\n";
		if ( rowListStatus == "on" ) { document.getElementById(rowNoteId).checked = "checked" };
    } 
	if ( queryResult == "" ) { createInitialChecklist(); return; }
} 

function updateChecklist(number){
	
	var status = document.getElementById(number).value;
	if (status != "on") { status="no"; }
	var update_table = 'UPDATE checklist set listStatus="'+status+'" where id="'+number+'";';
	db.transaction( 
    function (transaction) { transaction.executeSql(update_table), myTransactionErrorCallback, myTransactionSuccessCallback }
);
}

function createTableGuests(db) 
{ 
    db.transaction( 
        function (transaction) { 
            transaction.executeSql('CREATE TABLE IF NOT EXISTS guests(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, noteGuests TEXT NOT NULL DEFAULT " ", noteAddress1 TEXT NOT NULL DEFAULT " ", noteAddress2 TEXT NOT NULL DEFAULT " ", noteEmail TEXT NOT NULL DEFAULT " ", notePhone TEXT NOT NULL DEFAULT " ", notePhoneWork TEXT NOT NULL DEFAULT " ", noteNotes TEXT NOT NULL DEFAULT " ", noteNoAdults TEXT NOT NULL DEFAULT " ", noteNoChildren TEXT NOT NULL DEFAULT " ", noteRSVP TEXT NOT NULL DEFAULT "no", noteThankYou TEXT NOT NULL DEFAULT "no");', [], nullDataHandler, errorHandler); 
       } 
    ); 	
}   

function listAllGuests() {
	initdb();
	var search_query = 'SELECT * from guests';
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            guestListHandler, errorHandler);
    } 
); 	
}

function guestListHandler(transaction, results) 
{ 
	var queryResult = "";
	var htmlResults = "";
	var string ="";
    for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		rowNoteName = row['noteGuests'];
		rowNoteId = row['id'];
		queryResult = queryResult + row['noteGuests'] + "\n";
		htmlResults = htmlResults + '<a href="javascript:deleteGuest(\'' + rowNoteId + '\');" onclick="javascript:return confirm(\'Are you sure you want to delete this note?\')"><img src="../images/iphone/delete-icon.png" width="31" height="40" /></a><div id="listing-notes" onclick=\'noteFadeOn(); queryGuests("'+ rowNoteId + '");\'><p>' + rowNoteName + '<span class="arrow"></span></p></div>';
    } 
	document.getElementById('listing').innerHTML = htmlResults;
	if ( queryResult == "" ) { alert('Your guests list is empty.');return; }
} 

function updateGuests(){
	
	tempGuests = document.getElementById('noteGuests').value;
	tempAddress1 = document.getElementById('noteAddress1').value;
	tempAddress2 = document.getElementById('noteAddress2').value;
	tempEmail = document.getElementById('noteEmail').value;
	tempPhone = document.getElementById('notePhone').value;
	tempPhoneWork = document.getElementById('notePhoneWork').value;
	tempNotes = document.getElementById('noteNotes').value;
	tempNoAdults = document.getElementById('noteNoAdults').value;
	tempNoChildren = document.getElementById('noteNoChildren').value;
	tempRSVP = document.getElementById('noteRSVP').value;
	tempThankYou = document.getElementById('noteThankYou').value;
	
	if ( guestStatus=="NEW" ) {
		db.transaction( 
        function (transaction) { 
		var transactionValues = 'INSERT into guests (noteGuests, noteAddress1, noteAddress2, noteEmail, notePhone, notePhoneWork, noteNotes, noteNoAdults, noteNoChildren, noteRSVP, noteThankYou) VALUES ("'+tempGuests+'", "'+tempAddress1+'", "'+tempAddress2+'", "'+tempEmail+'", "'+tempPhone+'", "'+tempPhoneWork+'", "'+tempNotes+'", "'+tempNoAdults+'", "'+tempNoChildren+'", "'+tempRSVP+'", "'+tempThankYou+'");'
		transaction.executeSql(transactionValues, [], nullDataHandler, errorHandler); 
		}
		);
		alert('Your guest list has been saved.');
		return;
	}
	
	var update_table = 'UPDATE guests set noteGuests='+'"'+tempGuests+'", noteAddress1='+'"'+tempAddress1+'"'+', noteAddress2='+'"'+tempAddress2+'"'+', noteEmail='+'"'+tempEmail+'", notePhone='+'"'+tempPhone+'", notePhoneWork='+'"'+tempPhoneWork+'", noteNotes='+'"'+tempNotes+'", noteNoAdults='+'"'+tempNoAdults+'", noteNoChildren='+'"'+tempNoChildren+'", noteRSVP='+'"'+tempRSVP+'", noteThankYou='+'"'+tempThankYou+'" where id='+'"'+noteId+'"'+';';
	
db.transaction( 
    function (transaction) { transaction.executeSql(update_table), myTransactionErrorCallback, myTransactionSuccessCallback }
); 
alert('Your guest list has been updated.');
}

function queryGuests(guestId){
	var search_query = 'SELECT * from guests where id='+'"'+guestId+'"'+";";
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(search_query, 
            [], // array of values for the ? placeholders 
            guestListDataHandler, errorHandler); 
    } 
); 
}

function guestListDataHandler(transaction, results) 
{ 
	var queryResult = "";
    for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		queryResult = queryResult + row['noteGuests'];
		noteId = row['id'];
		noteGuests = row['noteGuests'];
		noteAddress1 = row['noteAddress1'];
		noteAddress2 = row['noteAddress2'];
		noteEmail = row['noteEmail'];
		notePhone = row['notePhone'];
		notePhoneWork = row['notePhoneWork'];
		noteNotes = row['noteNotes'];
		noteNoAdults = row['noteNoAdults'];
		noteNoChildren = row['noteNoChildren'];
		noteRSVP = row['noteRSVP'];
		if (noteRSVP != "on") { noteRSVP ="no"; }
		noteThankYou = row['noteThankYou'];
		if (noteThankYou != "on") { noteThankYou ="no"; }
    } 
	if ( queryResult == "" ) { guestStatus="NEW"; return; }
	guestStatus="EXISTING";
	document.getElementById('noteRSVP').checked = false;
	document.getElementById('noteThankYou').checked = false;
	document.getElementById('noteGuests').value = noteGuests;
	document.getElementById('noteAddress1').value = noteAddress1;
	document.getElementById('noteAddress2').value = noteAddress2;
	document.getElementById('noteEmail').value = noteEmail;
	document.getElementById('notePhone').value = notePhone;
	document.getElementById('notePhoneWork').value = notePhoneWork;
	document.getElementById('noteNotes').value = noteNotes;
	document.getElementById('noteNoAdults').value = noteNoAdults;
	document.getElementById('noteNoChildren').value = noteNoChildren;
	if (noteRSVP == "on") { noteRSVP = "checked"; document.getElementById('noteRSVP').checked = noteRSVP;}
	if (noteThankYou == "on") { noteThankYou = "checked"; document.getElementById('noteThankYou').checked = noteThankYou;}
} 

function initialGuestList() {
	document.getElementById('noteGuests').value = "";
	document.getElementById('noteAddress1').value = "";
	document.getElementById('noteAddress2').value = "";
	document.getElementById('noteEmail').value = "";
	document.getElementById('notePhone').value = "";
	document.getElementById('notePhoneWork').value = "";
	document.getElementById('noteNotes').value = "";
	document.getElementById('noteNoAdults').value = "";
	document.getElementById('noteNoChildren').value = "";
	document.getElementById('noteRSVP').checked = false;
	document.getElementById('noteThankYou').checked = false;
	guestStatus="NEW";
	noteFadeOn();
}

function createTableUrl(db) 
{ 
    db.transaction( 
        function (transaction) { 
            transaction.executeSql('CREATE TABLE IF NOT EXISTS url(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, urlValue TEXT NOT NULL DEFAULT "/iphone/index.html");', [], nullDataHandler, errorHandler); 
			transaction.executeSql('INSERT INTO url (urlValue) VALUES ("");', [], nullDataHandler, errorHandler);
       } 
    ); 	
}   

function updateTableUrl(){
	initdb();
	var url = document.location.href;
	urlId=1;
	var update_table = 'UPDATE url set urlValue='+'"'+url+'" where id='+'"'+urlId+'"'+";";
db.transaction( 
    function (transaction) { transaction.executeSql(update_table), myTransactionErrorCallback, myTransactionSuccessCallback }
); 
}

function readTableUrl() {
	initdb();
	var urlId=1;
	var url = 'SELECT * from url where id='+'"'+urlId+'"'+";";
	db.transaction( 
    	function (transaction) { 
        	transaction.executeSql(url, 
            [], 
            urlHandler, errorHandler);
    } 
); 	
}

function urlHandler(transaction, results) 
{ 
	for (var i=0; i<results.rows.length; i++) { 
        var row = results.rows.item(i); 
		var redirectBACK = row['urlValue'];}
		if ( redirectBACK == "" ) {mainInit(); return;}
		resetTableUrl();
		document.location.href=redirectBACK;
} 

function resetTableUrl(){
	initdb();
	var url = "";
	urlId=1;
	var update_table = 'UPDATE url set urlValue='+'"'+url+'" where id='+'"'+urlId+'"'+";";
db.transaction( 
    function (transaction) { transaction.executeSql(update_table), myTransactionErrorCallback, myTransactionSuccessCallback }
); 
}