// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see .
wn.provide('erpnext.todo');
erpnext.todo.refresh = function() {
	wn.call({
		method: 'utilities.page.todo.todo.get',
		callback: function(r,rt) {
			var todo_list = $('#todo-list div.todo-content');
			var assigned_todo_list = $('#assigned-todo-list div.todo-content');
			todo_list.empty();
			assigned_todo_list.empty();
			
			var nothing_to_do = function() {
				$('#todo-list div.todo-content')
					.html('
Nothing to do :)
');
			}
			
			var nothing_delegated = function() {
				$('#assigned-todo-list div.todo-content')
					.html('Nothing assigned to other users. \
							Use "Assign To" in a form to delegate work.
');
			}
			
			if(r.message) {
				for(var i in r.message) {
					new erpnext.todo.ToDoItem(r.message[i]);
				}
				if (!todo_list.html()) { nothing_to_do(); }
				if (!assigned_todo_list.html()) { nothing_delegated(); }
			} else {
				nothing_to_do();
				nothing_delegated();				
			}
		}
	});
}
erpnext.todo.ToDoItem = Class.extend({
	init: function(todo) {
		label_map = {
			'High': 'label-important',
			'Medium': 'label-info',
			'Low':''
		}
		todo.labelclass = label_map[todo.priority];
		todo.userdate = dateutil.str_to_user(todo.date) || '';
		
		todo.fullname = '';
		if(todo.assigned_by) {
			var assigned_by = wn.boot.user_info[todo.assigned_by]
			todo.fullname = repl("[By %(fullname)s]  ", {
				fullname: (assigned_by ? assigned_by.fullname : todo.assigned_by),
			});
		}
		
		var parent_list = "#todo-list";
		if(todo.owner !== user) {
			parent_list = "#assigned-todo-list";
			var owner = wn.boot.user_info[todo.owner];
			todo.fullname = repl("[To %(fullname)s]  ", {
				fullname: (owner ? owner.fullname : todo.owner),
			});
		}
		parent_list += " div.todo-content";
		
		if(todo.reference_name && todo.reference_type) {
			todo.link = repl('\
						%(reference_type)s: %(reference_name)s', todo);
		} else if(todo.reference_type) {
			todo.link = repl('\
						%(reference_type)s', todo);
		} else {
			todo.link = '';
		}
		if(!todo.description) todo.description = '';
		
		todo.desc = todo.description.replace(/\n/g, "
");
		
		$(parent_list).append(repl('\
			\
				
%(priority)s\
				
\
					\
					
\
					%(link)s\
				\
				
×\