// BUILD DATABASE ----------------------------------------------

var db;

try {
    if (window.openDatabase) {
        db = openDatabase("Checklist", "1.0", "HTML5 Database API", 200000);
        if (!db)
            alert("Failed to open the database on disk.  This is probably because the version was bad or there is not enough space left in this domain's quota");
        else
			var highestId = 0;
			var hideDelete = true;
    } else
        alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
} catch(err) { 

}



// BUILD TABLE -------------------------------------------------

function loaded()
{
    db.transaction(function(tx) {
        tx.executeSql("SELECT COUNT(*) FROM ToDos", [], function(result) {
            BuidList();
            //alert("loaded database");
        }, function(tx, error) {
            tx.executeSql("CREATE TABLE ToDos (id REAL UNIQUE, description TEXT, status REAL)", [], function(result) { 
                BuidList(); 
            });
        });
    });
}



// NEW ----------------------------------------------------------

function newToDo(){  

	if(document.getElementById('description').value != ""){
	highestId ++;
	var description = document.getElementById('description').value;
	var status = 0;
	
	db.transaction(function (tx)  {
        tx.executeSql("INSERT INTO ToDos (id , description, status) VALUES ("+ highestId +", '"+ description +"', " + status + " )", [],
            function(result){ 
   				document.getElementById('description').value = "";
    			BuidList(); 
    		} , function(tx, error) {
    			alert(error);
    		}
        );
    });
    
    }
	
}


// DELETE ----------------------------------------------------------

function deleteToDo(id){  
	
	db.transaction(function (tx)  {
        tx.executeSql("DELETE FROM ToDos WHERE id = " + id + ";", [],
            function(result){ 
    			document.getElementById(id).style.display = "none";
    		} , function(tx, error) {
    			alert(error);
    		}
        );
    });
	
}


// CHANGE STATUS ----------------------------------------------------------

function updateToDo(id, status){  

	if (status == '1') { 
		status = '0';
	} else { 
		status = '1'; 
	}
	
	db.transaction(function (tx)  {
        tx.executeSql("UPDATE ToDos SET status = " + status + " WHERE id = " + id + " ;", [],
            function(result){
				if (status == '1') { 
					document.getElementById(id+"box").removeAttribute("onclick");
					
					var newfunction = document.createAttribute("onclick");
   					newfunction.nodeValue = "updateToDo(" + id + ", " + status + ")";
					document.getElementById(id+"box").setAttributeNode(newfunction);
					
					document.getElementById(id).style.opacity = '0.2';
				} 
				if (status == '0') { 
					document.getElementById(id+"box").removeAttribute("onclick");
					
					var newfunction = document.createAttribute("onclick");
   					newfunction.nodeValue = "updateToDo(" + id + ", " + status + ")";
					document.getElementById(id+"box").setAttributeNode(newfunction);
					
					document.getElementById(id).style.opacity = '1';
				} 
    		} , function(tx, error) {
    			alert(error);
    		}
        );
    });
	
}


// BUILD LIST ---------------------------------------------------

function BuidList(){
	
	document.getElementById('container').innerHTML = "";
	
    db.transaction(function(tx) {
        tx.executeSql("SELECT id, description, status FROM ToDos", [], function(tx, result) {
            for (var i = 0; i < result.rows.length; ++i) {
                var row = result.rows.item(i);
                
                ToDo(row['id'], row['description'], row['status']);
                
                if (row['id'] > highestId)
                    highestId = row['id'];
            }

            // if (!result.rows.length)
            
        }, function(tx, error) {
            alert('Failed to retrieve notes from database - ' + error.message);
            return;
        });
    });
}



// TODO ---------------------------------------------------------

function ToDo(id, description, status){

    var ToDoItem = "<div id='" + id + "' class='part ";
    if(status == 1) {
    	ToDoItem += " done"; 
    }
    ToDoItem += "'><img src='images/delete.png' class='deletebtn ";
    if(hideDelete == true) {
    	ToDoItem += "hidden "; 
    } else {
    	ToDoItem += "show "; 
    }
	ToDoItem += "' onclick='getDbtn(this,\"Dbtn" + id + "\")' alt=''/> <input type='checkbox'";
    if(status == 1) {
    	ToDoItem += "checked='checked'"; 
    }
   	ToDoItem += " onclick='updateToDo(" + id + ", " + status + ")' id='" + id + "box' class='checked' />";
    ToDoItem +="<span>" + description + "</span>";
   	ToDoItem +="<input type='button' value='Delete' onclick='deleteToDo(" + id + ")' class='dbtn' id='Dbtn" + id + "'/></div> ";
    
    document.getElementById('container').innerHTML = document.getElementById('container').innerHTML + ToDoItem;
}



// TOGGLE HIDDEN ------------------------------------------------------

function toggleHidden(){
	if(hideDelete == true){
		hideDelete = false;
		document.getElementById('Edit').value = "Done";
	} else {
		hideDelete = true;
		document.getElementById('Edit').value = "Edit";
	}
	BuidList();
}


// LOADALL ------------------------------------------------------

addEventListener('load', loaded, false);

