/*
 * Copyright 2005 - 2009  Zarafa B.V.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3, 
 * as published by the Free Software Foundation with the following additional 
 * term according to sec. 7:
 *  
 * According to sec. 7 of the GNU Affero General Public License, version
 * 3, the terms of the AGPL are supplemented with the following terms:
 * 
 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
 * the Program under the AGPL does not imply a trademark license.
 * Therefore any rights, title and interest in our trademarks remain
 * entirely with us.
 * 
 * However, if you propagate an unmodified version of the Program you are
 * allowed to use the term "Zarafa" to indicate that you distribute the
 * Program. Furthermore you may use our trademarks where it is necessary
 * to indicate the intended purpose of a product or service provided you
 * use it in accordance with honest practices in industrial or commercial
 * matters.  If you want to propagate modified versions of the Program
 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
 * have a written permission by Zarafa B.V. (to acquire a permission
 * please contact Zarafa at trademark@zarafa.com).
 * 
 * The interactive user interface of the software displays an attribution
 * notice containing the term "Zarafa" and/or the logo of Zarafa.
 * Interactive user interfaces of unmodified and modified versions must
 * display Appropriate Legal Notices according to sec. 5 of the GNU
 * Affero General Public License, version 3, when you propagate
 * unmodified or modified versions of the Program. In accordance with
 * sec. 7 b) of the GNU Affero General Public License, version 3, these
 * Appropriate Legal Notices must retain the logo of Zarafa or display
 * the words "Initial Development by Zarafa" if the display of the logo
 * is not reasonably feasible for technical reasons. The use of the logo
 * of Zarafa in Legal Notices is allowed for unmodified and modified
 * versions of the software.
 * 
 * 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 Affero General Public License for more details.
 *  
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

function initTask()
{
	// Status
	dhtml.setValue(dhtml.getElementById("select_status"), dhtml.getElementById("status").value);
	
	// Priority
	dhtml.setValue(dhtml.getElementById("select_priority"), dhtml.getElementById("importance").value);

	// Duedate
	dhtml.setDate(dhtml.getElementById("duedate"));
	
	// Startdate
	dhtml.setDate(dhtml.getElementById("startdate"));
	
	// Complete
	var complete = dhtml.getElementById("complete");
	if(complete && complete.value == "1") {
		dhtml.setValue(dhtml.getElementById("select_status"), 2);
	}
	
	// Percent Complete
	var percent_complete = dhtml.getElementById("percent_complete");
	if(percent_complete) {
		var text_percent_complete = dhtml.getElementById("text_percent_complete");
		
		if(text_percent_complete) {
			text_percent_complete.value = (percent_complete.value * 100) + "%";
		}
	}
	
	// Reminder
	var reminder = dhtml.getElementById("reminder");
	if(reminder) {
		if(reminder.value == "1") {
			dhtml.setValue(dhtml.getElementById("checkbox_reminder"), true);
			
			var text_reminderdate = dhtml.getElementById("text_reminderdate");
			text_reminderdate.disabled = false;
			text_reminderdate.style.background = "#FFFFFF";
			
			var text_reminderdate_time = dhtml.getElementById("text_reminderdate_time");
			text_reminderdate_time.disabled = false;
			text_reminderdate_time.style.background = "#FFFFFF";
		}
		
		dhtml.setDate(dhtml.getElementById("reminderdate"));
		dhtml.setTime(dhtml.getElementById("reminderdate"));
	}
	
	// Date Completed
	dhtml.setDate(dhtml.getElementById("datecompleted"));
	
	// Total Work
	var totalwork = dhtml.getElementById("totalwork");
	if(totalwork) {
		var text_totalwork = dhtml.getElementById("text_totalwork");
		
		if(text_totalwork) {
			totalwork.value /= 60;
			text_totalwork.value = totalwork.value + " " + ((totalwork.value==1) ? _("hour") : _("hours"));
		}
	}
	
	// Actual Work
	var actualwork = dhtml.getElementById("actualwork");
	if(actualwork) {
		var text_actualwork = dhtml.getElementById("text_actualwork");
		
		if(text_actualwork) {
			actualwork.value /= 60;
			text_actualwork.value = actualwork.value + " " + ((actualwork.value==1) ? _("hour") : _("hours"));
		}
	}
	
	// Private
	if(dhtml.getElementById("sensitivity").value == "2") {
		dhtml.setValue(dhtml.getElementById("checkbox_private"), true);
	}

}

function submitTask()
{
	// Status
	dhtml.getElementById("status").value = dhtml.getValue(dhtml.getElementById("select_status"));
	
	// Priority
	dhtml.getElementById("importance").value = dhtml.getValue(dhtml.getElementById("select_priority"));

	// Validate dates
	onChangeDate();
	
	// Duedate
    var duedate = Date.parseDate(dhtml.getElementById("text_duedate").value, _("%d-%m-%Y"), true, true);

    if(duedate) {
        dhtml.getElementById("duedate").value = duedate.getTime()/1000;
        dhtml.getElementById("commonend").value = duedate.getTime()/1000;
    } else {
        dhtml.getElementById("duedate").value = "";
        dhtml.getElementById("commonend").value = "";
    }

	// Startdate
    var startdate = Date.parseDate(dhtml.getElementById("text_startdate").value, _("%d-%m-%Y"), true, true);
    
    if(startdate) {
        dhtml.getElementById("startdate").value = startdate.getTime()/1000;
        dhtml.getElementById("commonstart").value = startdate.getTime()/1000;
    } else {
        dhtml.getElementById("startdate").value = "";
        dhtml.getElementById("commonstart").value = "";
    }
	
	// regular date expression to check whether entered value is date or not.
	var dateRegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
	
	//duedate validation
	if(dhtml.getElementById("text_duedate").value.toLowerCase() != _("None").toLowerCase() && !dateRegExPattern.test(Date.parseDate(dhtml.getElementById("text_duedate").value, _("%d-%m-%Y"), true).toDate())){
		alert(_("Please enter correct date"));
		dhtml.getElementById("text_duedate").focus();
		return false;
	}
	//startdate validation
	if(dhtml.getElementById("text_startdate").value.toLowerCase() != _("None").toLowerCase() && !dateRegExPattern.test(Date.parseDate(dhtml.getElementById("text_startdate").value, _("%d-%m-%Y"), true).toDate())){
		alert(_("Please enter correct date"));
		dhtml.getElementById("text_startdate").focus();
		return false;
	}

	// Complete
	if(dhtml.getElementById("status").value == "2") {
		dhtml.getElementById("complete").value = "1";
	} else {
		dhtml.getElementById("complete").value = "-1";
	}
	
	// Percent Complete
	var text_percent_complete = dhtml.getElementById("text_percent_complete");
	if(text_percent_complete) {
		var percent = text_percent_complete.value;
		if(percent.indexOf("%") >= 0) {
			percent = percent.substring(0, percent.indexOf("%"));
		}
		
		percent = parseInt(percent);
		
		if(percent >= 0) {
			dhtml.getElementById("percent_complete").value = percent / 100;
		}
	}
	
	// Reminder
	var reminderset = dhtml.getValue(dhtml.getElementById("checkbox_reminder"));
	if(reminderset) {
		dhtml.getElementById("reminder").value = "1";
	} else {
		dhtml.getElementById("reminder").value = "-1";
	}
	
	// Reminder Date
	if (dhtml.getElementById("text_reminderdate").value != "" && dhtml.getElementById("text_reminderdate").value.toLowerCase() != _("None").toLowerCase()){
		dhtml.getElementById("reminderdate").value =  Date.parseDate(dhtml.getElementById("text_reminderdate").value + " " + dhtml.getElementById("text_reminderdate_time").value, _("%d-%m-%Y") + " " + _("%H:%M")).getTime()/1000;
		// set flagdueby value at first time only
		if(dhtml.getElementById("flagdueby").value == "") {
			dhtml.getElementById("flagdueby").value = dhtml.getElementById("reminderdate").value;		// flagdueby property used in reminders
		}
	}

	// Date Completed
	if (dhtml.getElementById("text_datecompleted").value != "" && dhtml.getElementById("text_datecompleted").value.toLowerCase() != _("None").toLowerCase()){
		dhtml.getElementById("datecompleted").value = Date.parseDate(dhtml.getElementById("text_datecompleted").value, _("%d-%m-%Y"), true).getTime()/1000;
	}
	
	// Total Work
	var text_totalwork = dhtml.getElementById("text_totalwork");
	if(text_totalwork) {
		var totalwork = parseInt(text_totalwork.value);
		
		if(totalwork >= 0) {
			dhtml.getElementById("totalwork").value = totalwork * 60;
		}
	}

	// Actual Work
	var text_actualwork = dhtml.getElementById("text_actualwork");
	if(text_actualwork) {
		var actualwork = parseInt(text_actualwork.value);
		
		if(actualwork >= 0) {
			dhtml.getElementById("actualwork").value = actualwork * 60;
		}
	}
	
	// Private
	var checkbox_private = dhtml.getElementById("checkbox_private");
	if(checkbox_private.checked) {
		dhtml.getElementById("sensitivity").value = "2";
		dhtml.getElementById("private").value = "1";
	} else {
		dhtml.getElementById("sensitivity").value = "0";
		dhtml.getElementById("private").value = "-1";
	}
	
	// Contacts
	dhtml.getElementById("contacts_string").value = dhtml.getElementById("contacts").value;
	
	submit_task();
}

function onChangeStatus()
{
	var select_status = dhtml.getElementById("select_status");
	if(select_status) {
		var selected = select_status.options[select_status.selectedIndex].value;
		
		if(selected == "2") {
			dhtml.getElementById("text_percent_complete").value = "100%";
			//check reminder and turn it off
			setReminderOnComplete();
		} else {
			dhtml.getElementById("text_percent_complete").value = (dhtml.getElementById("percent_complete").value * 100) + "%";
			//check reminder and turn it on
			setReminderOnComplete(true);
		}
		
		dhtml.getElementById("status").value = selected;
	}
}

function completeSpinnerUp()
{
	var text_percent_complete = dhtml.getElementById("text_percent_complete");
	if(text_percent_complete) {
		var percent = text_percent_complete.value;
		
		if(percent.indexOf("%") >= 0) {
			percent = percent.substring(0, percent.indexOf("%"));
		}
		
		percent = parseInt(percent);
		if(percent >= 0) {
			if(percent >= 0 && percent <= 24) {
				percent = 25;
			} else if(percent >= 25 && percent <= 49) {
				percent = 50;
			} else if(percent >= 50 && percent <= 74) {
				percent = 75;
			} else if(percent >= 75 && percent <= 100) {
				percent = 100;
			} else {
				percent = dhtml.getElementById("percent_complete").value * 100;
			}
			
			dhtml.getElementById("percent_complete").value = (percent / 100);
		} else {
			percent = dhtml.getElementById("percent_complete").value * 100;
		}
		
		text_percent_complete.value = percent + "%";
		
		if(percent == 100) {
			dhtml.setValue(dhtml.getElementById("select_status"), 2);
			//check reminder and turn it off
			setReminderOnComplete();
		} else if(percent < 100) {
			if(dhtml.getValue(dhtml.getElementById("select_status")) == "0" || 
			   dhtml.getValue(dhtml.getElementById("select_status")) == "2") {
				dhtml.setValue(dhtml.getElementById("select_status"), 1);
			}
		}
	}
}

function completeSpinnerDown()
{
	var text_percent_complete = dhtml.getElementById("text_percent_complete");
	if(text_percent_complete) {
		var percent = text_percent_complete.value;
		
		if(percent.indexOf("%") >= 0) {
			percent = percent.substring(0, percent.indexOf("%"));
		}
		
		percent = parseInt(percent);
		if(percent >= 0) {
			if(percent >= 0 && percent <= 25) {
				percent = 0;
			} else if(percent >= 26 && percent <= 50) {
				percent = 25;
			} else if(percent >= 51 && percent <= 75) {
				percent = 50;
			} else if(percent >= 76 && percent <= 100) {
				percent = 75;
			} else {
				percent = dhtml.getElementById("percent_complete").value * 100;
			}
			
			text_percent_complete.value = percent + "%";
			dhtml.getElementById("percent_complete").value = (percent / 100);
		} else {
			percent = dhtml.getElementById("percent_complete").value * 100;			
		}
		
		text_percent_complete.value = percent + "%";
		
		if(percent < 100) {
			dhtml.setValue(dhtml.getElementById("select_status"), 1);
			//check reminder and turn it on
			setReminderOnComplete(true);
		}
	}
}

function onChangeReminder()
{
	var checkbox_reminder = dhtml.getElementById("checkbox_reminder");
	
	if(checkbox_reminder) {
		var reminder = dhtml.getElementById("reminder");
		var text_reminderdate = dhtml.getElementById("text_reminderdate");
		var text_reminderdate_time = dhtml.getElementById("text_reminderdate_time");
		
		if(checkbox_reminder.checked) {
			text_reminderdate.disabled = false;
			text_reminderdate.style.background = "#FFFFFF";
			
			if(text_reminderdate.value == _("None") || text_reminderdate.value == "") {
				var date = new Date();
				
				var unixtime = Date.parseDate(dhtml.getElementById("text_duedate").value, _("%d-%m-%Y"), true).getTime()/1000;
				if(unixtime) {
					date = new Date(unixtime * 1000);
				}
				
				text_reminderdate.value = (date.getDate() < 10?"0" + date.getDate():date.getDate()) + "-" + (date.getMonth() + 1 < 10?"0" + (date.getMonth() + 1):(date.getMonth() + 1)) + "-" + date.getFullYear();
			}
			
			text_reminderdate_time.disabled = false;
			text_reminderdate_time.style.background = "#FFFFFF";
			
			if(text_reminderdate_time.value == _("None") || text_reminderdate_time.value == "") {
				text_reminderdate_time.value = "09:00";
			}
			
			reminder.value = "1";
		} else {
			text_reminderdate.disabled = true;
			text_reminderdate.style.background = "#DFDFDF";
			
			text_reminderdate_time.disabled = true;
			text_reminderdate_time.style.background = "#DFDFDF";
			
			reminder.value = "-1";
		}
	}
}

function assignTask()
{
	var taskrequest_recipient = dhtml.getElementById("taskrequest_recipient");
	var taskrequest_settings = dhtml.getElementById("taskrequest_settings");
	var sendbutton = dhtml.getElementById("send");
	var assigntaskbutton = dhtml.getElementById("assigntask");
	var taskcompletebutton = dhtml.getElementById("taskcomplete");
	var cancelassigntaskbutton = dhtml.getElementById("cancelassigntask");
	var remindervalues = dhtml.getElementById("remindervalues");
	
	if(taskrequest_recipient) {
		if(taskrequest_recipient.style.display == "block") {
			taskrequest_recipient.style.display = "none";
			taskrequest_settings.style.display = "none";
			sendbutton.style.display = "none";
			cancelassigntaskbutton.style.display = "none";
			
			assigntaskbutton.style.display = "block";
			taskcompletebutton.style.display = "block";
			remindervalues.style.display = "block";
		} else {
			taskrequest_recipient.style.display = "block";
			taskrequest_settings.style.display = "block";
			sendbutton.style.display = "block";
			cancelassigntaskbutton.style.display = "block";
			
			assigntaskbutton.style.display = "none";
			taskcompletebutton.style.display = "none";
			remindervalues.style.display = "none";
		}
	}
	
	resizeBody();
}

function onChangeDateCompleted()
{
	var text_datecompleted = dhtml.getElementById("text_datecompleted");
	
	if(text_datecompleted) {
		var unixtime = Date.parseDate(text_datecompleted.value, _("%d-%m-%Y"), true).getTime()/1000;
		
		if(unixtime && unixtime > 0) {
			dhtml.setValue(dhtml.getElementById("select_status"), "2");
			dhtml.getElementById("text_percent_complete").value = "100%";
		} else {
			dhtml.setValue(dhtml.getElementById("select_status"), dhtml.getElementById("select_status").value);
			dhtml.getElementById("text_percent_complete").value = (dhtml.getElementById("percent_complete").value * 100) + "%";
		}
	}
}

function setTaskCompleted()
{
	dhtml.setValue(dhtml.getElementById("select_status"), "2");
	dhtml.getElementById("text_percent_complete").value = "100%";

	// check reminder and turn it off.
	setReminderOnComplete();
	submitTask();
}

/**
 * Function which turn off/on the reminde on basis of percentage of task completion.
 * 100% task complete means the reminder should be turn off else check if that was on then turn on.
 * @params boolean forceFlag boolean which forcefully turns on the reminder, used when somebody 
									 is playing via task completion (percentage)
 */
function setReminderOnComplete(forceFlag){
	var reminderCheck = dhtml.getElementById("checkbox_reminder");
	if(reminderCheck.checked && !forceFlag){
		dhtml.executeEvent(reminderCheck, "click");
		reminderCheck.checked = false;
	}else if(!reminderCheck.checked && forceFlag){
		if(dhtml.getElementById("previousReminderValue").value != "0"){
		// called from completion box
			dhtml.executeEvent(reminderCheck, "click");
			reminderCheck.checked = true;
		}
	}
	
}

function categoriesCallBack(categories)
{
	moduleObject = webclient.getModulesByName("taskitemmodule")[0];
	moduleObject.filtercategories(dhtml.getElementById("categories"), categories);
}

function abCallBack(recipients)
{
	dhtml.getElementById("contacts").value = recipients['contacts'].value;
}

function onChangeComplete()
{
	var text_percent_complete = dhtml.getElementById("text_percent_complete");
	if(text_percent_complete) {
		var percent = text_percent_complete.value;
		
		// Parse the number the best we can (remove trailing % sign)
		if(percent.indexOf("%") >= 0) {
			percent = percent.substring(0, percent.indexOf("%"));
		}
		
		// Set status to complete if completion level is 100% or more
		if(parseInt(percent) >= 100) {
			dhtml.setValue(dhtml.getElementById("select_status"), 2);
			// check reminder and turn it off
			setReminderOnComplete();
        } else if(parseInt(percent) <= 0) {
			dhtml.setValue(dhtml.getElementById("select_status"), 0);
        } else {
			dhtml.setValue(dhtml.getElementById("select_status"), 1);
        }
	}
}
/**
 * Keycontrol function which saves task.
 */
function eventTaskListKeyCtrlSave(moduleObject, element, event, keys)
{
	switch(event.keyCombination)
	{
		case keys["save"]:
			submitTask();
			break;
	}
}
