// DB オブジェクト
var db;

// DB 初期化（テーブルが無ければ作成する）
function init() {
	if(window.openDatabase) {
		db = openDatabase('test_db', '1.0', 'Tasks');
		db.transaction(
			function(tx) {
				tx.executeSql('SELECT COUNT(*) FROM tasks', [],
					function(tx, rs) {},
					function(tx, error) {
						tx.executeSql('CREATE TABLE tasks (id INTEGER PRIMARY KEY, body TEXT, cmp_f BOOLEAN, priority INTEGER)', [],
							function() {},
							function(error) {
								alert('Database does not created. : ' + error.message);
							}
						);
					}
				);
			}
		);
	} else {
		alert('Sorry, this browser does not supported.');
	}
}

/*
before
function init() {
	if(window.openDatabase) {
		db = openDatabase('test_db', '1.0', 'Tasks');
		db.transaction(
			function(tx) {
				tx.executeSql('CREATE TABLE tasks (id INTEGER PRIMARY KEY, body TEXT, cmp_f BOOLEAN, priority INTEGER)');
			}
		);
	} else {
		alert('Sorry, this browser does not supported.');
	}
}
*/

// タスク一覧を表示する
function show() {
	var incmp = document.getElementById('incomplete_list');
	var cmp = document.getElementById('completed_list');
	if(!(incmp && cmp)) return;
	
	// 現在表示しているタスクをクリアする
	while(incmp.hasChildNodes()) {
		incmp.removeChild(incmp.firstChild);
	}
	while(cmp.hasChildNodes()) {
		cmp.removeChild(cmp.firstChild);
	}
	var ul = document.createElement('ul');
	incmp.appendChild(ul);
	var ul = document.createElement('ul');
	cmp.appendChild(ul);
	
	// タスク一覧を取得して表示する
	db.transaction(
		function(tx) {
			tx.executeSql('SELECT * FROM tasks ORDER BY priority', [], function(tx, rs) {
				for(var i = 0; i < rs.rows.length; i++) {
					var row = rs.rows.item(i);
					var list = (row.cmp_f == 't') ? cmp : incmp;
					appendItem(list.firstChild, 'edit.html?id=' + row.id, 'arrow', row.body, row.priority);
				}
				
				// タスク件数が 0 件の場合
				if(incmp.firstChild.childNodes.length == 0) {
					appendItem(incmp.firstChild, '#', null, '(No Item)', null);
				}
				if(cmp.firstChild.childNodes.length == 0) {
					appendItem(cmp.firstChild, '#', null, '(No Item)', null);
				}
			});
		},
		function(error) {
			alert('Task data does not get. : ' + error.message);
		},
		function() {}
	);
}

// リストを追加する
function appendItem(prt, hrf, cl, val, pri) {
	if(!prt) return;
	var li = document.createElement('li');
	li.className = 'pri' + pri;
	prt.appendChild(li);
	var a = document.createElement('a');
	a.href = hrf;
	if(cl) a.className = cl;
	li.appendChild(a);
	var t = document.createTextNode(val);
	a.appendChild(t);
}

// タスクを新規作成する
function add() {
	var b = document.getElementById('body');
	if(!b) return;
	var body = b.value;
	var p = document.getElementById('priority');
	if(!p) return;
	var idx = p.selectedIndex;
	var priority = p.options[idx].value;
	db.transaction(
		function(tx) {
			tx.executeSql('INSERT INTO tasks VALUES(NULL, ?, ?, ?)', [body, 'f', priority]);
		},
		function(error) {
			alert('Task does not create. : ' + error.message);
		},
		function() {
			location.href = 'index.html';
		}
	);
}

// タスクを削除する
function del() {
	var id = getIdValue();
	if(!id) return;
	if(window.confirm('Delete this task ?')) {
		db.transaction(
			function(tx) {
				tx.executeSql('DELETE FROM tasks WHERE id = ?', [id]);
			},
			function(error) {
				alert(error.message);
			},
			function() {
				location.href = 'index.html';
			}
		);
	}
}

// タスクを完了/未完了にする
function cmp(f) {
	var id = getIdValue();
	if(!id) return;
	db.transaction(
		function(tx) {
			tx.executeSql('UPDATE tasks SET cmp_f = ? where id = ?', [(f) ? 't' : 'f', id]);
		},
		function(error) {
			alert(error.message);
		},
		function() {
			location.href = 'index.html';
		}
	);
}

// 1 つのタスクを表示する（edit.html で使用）
function showOne() {
	var id = getIdValue();
	if(!id) return;
	db.transaction(
		function(tx) {
			tx.executeSql('SELECT * FROM tasks WHERE id = ?', [id], function(tx, rs) {
				if(rs.rows.length > 0) {
 	 				var row = rs.rows.item(0);
					var body = document.getElementById('body');
					if(!body) return;
					body.value = row.body;
					var p = document.getElementById('priority');
					if(!p) return;
					p.value = row.priority;
					if(row.cmp_f == 't') {
						var elm = document.getElementById('cmp');
					} else {
						var elm = document.getElementById('uncmp');
					}
					elm.style.display = 'none';
				} else {
					alert('Task does not exist.');	
				}
			});
		},
		function(error) {
			alert(error.message);
		},
		function() {}
	);
}

// タスクを更新する
function update() {
	var b = document.getElementById('body');
	if(!b) return;
	var body = b.value;
	if(body.length > 0) {
		var id = getIdValue();
		if(!id) return;
		var p = document.getElementById('priority');
		if(!p) return;
		var priority = p.value;
		db.transaction(
			function(tx) {
				tx.executeSql('UPDATE tasks SET body = ?, priority = ? WHERE id = ?', [body, priority, id]);
			},
			function(error) {
				alert('Task update failed. : ' + error.message);
			},
			function() {
				location.href = 'index.html';
			}
		);
	} else {
		alert('Please input body.');
	}
}


// QueryString から ID 値を取得する
function getIdValue() {
	if(location.search.length > 0) {
		var arr = location.search.substr(1).split('&');
		for(idx in arr) {
			var k = arr[idx].split('=');
			if(k[0] == 'id') return k[1];
		}
	} else {
		return null;
	}
}
