/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Dirk Hartmann <dirk.hartmann@open-xchange.com>
 * 
 */

var taskobject = new Object();
var json = new JSON();
var activefolder;
var taskDetailId = 0;
var lastTimestamp = (corewindow.taskTimestamp > 0) ? corewindow.taskTimestamp : 1;
var modulPopup = "new";
var c = 0;
var bCreated = false;
var aContextMenu = new Array();
var disableOther=true;
var ta_object;
var comboStatusTask;
var gridatt;
var taskTreeLoaded = false;
var session;
var config;
var configContainsKey = corewindow.configContainsKey;
var configGetKey = corewindow.configGetKey;
var configSetKey = corewindow.configSetKey;	
var internalCache;
var newFolderName = "";
var treeVisible = false;
var miniStartVisible = false;
var miniEndVisible = false;
var miniReminderVisible = false;
var bAttachmentGridCreated = false, bParticipantGridCreated = false, treeLoaded = false;
var tmp_attachment, tmp_participant, newTaskFolderTree;
var miniRemindVisible = false, task_categories = "", allOk = 0;
var checkTaskNumberFormat = 0, taskCloseBit = false, savePending = false;
var globalseries, externalParticipants = null, externalCounter = 0;
var triggerReady = jQuery.noop;
var messageOnCancel = false;
var messageCloseWindow = _("Do you really want to discard your changes and close the window?");

// modal dialog
function setModalBusy(state){
    if (state == true){
        ox.api.setModal(true);
        jQuery("#modal-dialog-decorator").addClass("busy");
    }else{
        ox.api.setModal(false);
        jQuery("#modal-dialog-decorator").removeClass("busy");
    }
}

function initNewTaskLoaded() {
}

function fn_changeTimstamp(newTStamp) {
	lastTimestamp = newTStamp;
}

function setNumberOfAttNewTask(nCountParam) {
	$("tasks_number_of_attachments").firstChild.data = nCountParam;
}

register("Loaded", function () {
	globalseries = new SeriesView();
	globalseries.initView();
	addOnClose($('series_window'), function () { 
		globalseries.hideView(); 
	});
	
	triggerReady = function () {
	    ox.gui.initToolBarNewWindowTask();
        var metaData = {
            module: "tasks",
            activemodule: activemodule,
            handle: url.guid,
            id: (url.id != undefined) ? url.id : null,
            folder_id: url.folder,
            title: window.document.title
        };
        ox.api.window.core.triggerEvent("OX_Window_Ready", metaData, window);
    };
    
	newTaskOnload();
    
    triggerEvent("OX_menu_Change_Height",true);
});

register("OX_Timestamp_Changed_By_Attach", fn_changeTimstamp);
registerView("task_new", null, null, null, null);

registerView("task_new/task",
	function() { 
		$("tab1").style.display="block";
		$("panel1").className="tabPanelFirstHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
	function () {
		try {
			setTimeout(function() {	$("title").focus();	}, 0);
		} catch (e) { }		
	}, 
	null,
	function() {
		$("tab1").style.display="none";
		$("panel1").className="tabPanelFirst tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	},
	function () {
		try {
			setTimeout(function() {	$("title").focus();	}, 0);
		} catch (e) { }
	}
);

registerView("task_new/detail",
	function() { 
		$("tab2").style.display="block";
		$("panel2").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
	function () {
		setTimeout(function() {	$("target_duration").focus(); }, 0);
	}, 
	null,
	function() {
		$("tab2").style.display="none";
		$("panel2").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	},
	function () {
		setTimeout(function() {	$("target_duration").focus(); }, 0);
	}
);

registerView("task_new/participant",
	function() { 
		$("tab3").style.display="block";
		$("panel3").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
	function() {
		if (!bParticipantGridCreated) {
			var nId = url.id || false;
			bParticipantGridCreated = true;
			tmp_participant.getParticipants();
			tmp_participant.enableTheGrid();
		} else {
			tmp_participant.enableTheGrid();
		}
		/* external participants */
		if (externalParticipants == null) {
            function on_ok(parts) {
                if (!bParticipantGridCreated || !tmp_participant.participantsGridBig) {
                    return;
                }                
                var extStorage = tmp_participant.participantsGridBig.storage;
                for (var i in parts) {
                    var found = new Array();
                    for (var j in extStorage.data.data) {
                        if (extStorage.data.data[j][5] === parts[i].email) {
                            found.push(parts[i].email);                          
                        }
                    }
                    if (found.length) {
                        //#, c-format
                        newAlert(_("Info"), format(_("The following addresses are already on the list of participants and therefore not been added: %s"), found.join(",")));
                    } else {
                        extStorage.append(
                            [[ "contact_ext_" + externalCounter++, 0, 
                               parts[i].displayName, _("not sent"), "", parts[i].email, 
                               "contact", null ]]
                        );
                    }
                }
            }
            externalParticipants = new ParticipantsExternal(null, on_ok);
        }
	}, 
	function() {
		tmp_participant.disableTheGrid();
		try {
			if (tmp_participant.getParticipants().length > 0) {
				ce();
			}
		} catch (e) { }
	},
	function() {
		$("tab3").style.display = "none";
		$("panel3").className = "tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	}
);

registerView("task_new/attachment",
	function() { 
		$("tab4").style.display="block";
		$("panel4").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
	function() {
		if(!bAttachmentGridCreated)
		{
			initAttachmentsGrid();
			bAttachmentGridCreated = true;
			tmp_attachment.getAttachments();
		}
		else {
			if(bAttachmentGridCreated)
				tmp_attachment.enableGrid();
		}		
		register("OX_Attachments_Changed_InGrid",setNumberOfAttNewTask);
	}, 
	function() {
		//TODO: throw an error
		unregister("OX_Attachments_Changed_InGrid",setNumberOfAttNewTask);		
		tmp_attachment.disableGrid();
	},
	function() {
		$("tab4").style.display="none";
		$("panel4").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	}
);

function initAttachmentsGrid() {
	tmp_attachment = new attachmentGrid("attachmentsNewTaskGrid", (url.id || false), 
			(url.folder || corewindow.configGetKey("folder.tasks")), 
			4, tmp_attachmentDialog);	
}

function initParticipantsGrid() {
	var nId = url.id || false;
	if (nId == false) {
		tmp_participant = new Participants("participantsNewTask",
							function(cb){
								$("partCounterTasksNew").firstChild.data = 
								tmp_participant.getParticipants().length;
							}, true, true, false, true, "Select Participants", /*i18n*/
							false); /*i18n*/
	} else {
		tmp_participant = new Participants("participantsNewTask", function(cb){
								$("partCounterTasksNew").firstChild.data = 
								tmp_participant.getParticipants().length;
							}, true, true, false, true, "Select Participants", /*i18n*/
							false); 
	}
}

function setBeforeUnload(on) {
    messageOnCancel = on;
}

function newTaskOnload() {
	loadingComplete();
	
	// extend url object
	url = jQuery.extend((url || {}), ox.api.window.getData(url.guid));
	
	// fixed extended fu.ck3l, don't use german vars
	url.module = url.modul || "new";
	
	session = corewindow.session;
	config = corewindow.config;
	internalCache = corewindow.internalCache;
	check0GroupDisplayName = corewindow.check0GroupDisplayName;
	initParticipantsGrid();
	activefolder = url.folder || corewindow.configGetKey("folder.tasks");
	
	var btnClose = $("hider");
	register("OX_SAVE_OBJECT", saveTask);
	register("OX_Task_Add_Sequence", openSequenceWindow);
	register("OX_Cancel_Object", canselProcessTaskWindow);
	register("doneModifyEvent", function(param) {
		doneModifyDown(param);
	});
	internalCache = corewindow.internalCache;

	setTabLists(tabsList, panelsList, eventList);
	function callMeOnOK(parameter) {
		tmp_attachment.updateGrid(parameter);
	}
	tmp_attachmentDialog = new attachmentDialog(0,callMeOnOK); 
	triggerEvent("OX_Switch_View",'task_new/task');
	fillSelectBoxes();
	createMiniCalendar();
	setModulPopup();
	$("taskSequence").value = globalseries.getSeriesString();
	setBeforeUnload(taskCloseBit);
	register("OX_Series_Data_Init",function() {
		$("taskSequence").value=globalseries.getSeriesString();
	});
	register("LanguageChanged",function() {
		$("taskSequence").value=globalseries.getSeriesString();
	});

	register("OX_Series_Data_Changed",function () {
		$("taskSequence").value=globalseries.getSeriesString();
		var mydate=parseDateString($("newtask_begins_date").value,"date");
		if(mydate == null) {
			$("newtask_begins_date").value=formatDate(new Date(globalseries.sequenceStart.selectedTime),"date");
			$("newtask_ends_date").value=formatDate(new Date(globalseries.sequenceStart.selectedTime),"date");
		}
		var tmpstart=parseDateString($("newtask_begins_date").value,"date");
		var tmpend=parseDateString($("newtask_ends_date").value,"date");
		if(tmpend==null) {
			tmpend=new Date(tmpstart.getTime());
		}
		var changes=globalseries.sequenceStart.selectedTime-tmpstart.getTime();
		tmpend.setTime(tmpend.getTime()+changes);
		$("newtask_begins_date").value=formatDate(globalseries.getStartDate(),"date");
		$("newtask_ends_date").value=formatDate(tmpend,"date");	
	});
	
	initTaskCategories();
	initParticipantContent();
	
	initTaskTree();
}

function initTaskCategories() {
	// add click on categories button
	addDOMEvent($("newtask_categories_button"), "click", function(e) {
		openTaskCategoriesDialog();
	});
	
	// handle dbl click which attachs an inplace input field to div
	addDOMEvent($("newtask_categories_list"), "dblclick", function(e) {
		ox.categories.ui.attachInplaceInput($("newtask_categories_list"),
			function(value) {				
				// handle value
				var list = clone(ox.categories.getByString(task_categories, ox.categories.match.ALL, true));
				// add only if not empty!
				if (value && trimStr(value).length && !ox.categories.utils.existsInObject(trimStr(value), list)) {
					var category = { name: value, color: 0 };
					list.push(category);
					task_categories = ox.categories.utils.paramToString(list, "name");				
				}
				ox.categories.ui.drawCategoriesList(
						ox.categories.getByString(task_categories), 
						$("newtask_categories_list"));
			}
		);		
	});		
}

function openTaskCategoriesDialog() {
	ox.categories.ui.open((task_categories || ""), function(list, str) {
		task_categories = str;
		ox.categories.ui.drawCategoriesList(ox.categories.getByString(task_categories), 
				$("newtask_categories_list"));
	});
}

function setModulPopup() {
	modulPopup = url.module || "new";
	taskDetailId = url.id;
	activefolder = url.folder;
	session = url.session;
	currentView = url.currentView;
		
	if (modulPopup != "new") {
		fillTaskFieldsById(taskDetailId);
	} else {
		fillTaskFields(url);
		// disable loading screen
        $("loading_data_bg").style.display="none";
        triggerReady();
	}
}

function initNewTask() {
    
    // add default theme (should be in browser cache)
    var themeStyle = corewindow.oxThemeStyle || { name: "Default", path: "default" };
    ox.gui.themePath = getFullImgSrc("");
    removeCSSFilesForNewWindow(themeStyle.path);
    
	activemodule = "task_new";
	initContents(activemodule);
	initAll();
	
	window.setTimeout(function() {
		initNewTaskLoaded();
	}, 0);
}

function nt_ends_date_changed() {
	var value=$("newtask_ends_date").value;
	if(value != "") {
		var date=parseDateString(value,"date");
		if(!date) {
			triggerEvent("OX_New_Error",4,_("Illegal date in due date"));
			return;
		}
		endCalendar.setSelectedByDate(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate());
	}
	
}
function nt_begins_date_changed() {
	var value=$("newtask_begins_date").value;
	if (value) {
		var date=parseDateString(value,"date");
		if(!date) {
			triggerEvent("OX_New_Error",4,_("Illegal Date in start date"));
			return;
		}
		beginCalendar.setSelectedByDate(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate());
	}
}
function nt_remind_date_changed() {
	var value=$("newtask_reminder_date").value;
	if (value) {
		var date=parseDateString(value,"date");
		if(!date) {
			triggerEvent("OX_New_Error",4,_("Illegal Date in remind date"));
			return;
		}
		remindCalendar.setSelectedByDate(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate());
	}
}
function nt_remind_hour_changed() {
	var value=$("newtask_reminder_hour").value;
	if (value) {
		var time=parseDateString(value,"time");
		if(!time) {
			triggerEvent("OX_New_Error",4,_("Illegal entry in reminder hour field"));
			return;
		}
	}
}

function fillTaskFieldsById(id) {
	var duration_type_sel = 0;
	var ta = $("newTaskForm");
	var sf = document.sequenceForm;
	json.get(AjaxRoot + "/tasks?action=get&folder=" + activefolder + "&session=" + session + "&id=" + id, null, 
		function(reply) {
			if (reply) {
				if (reply.error) {
					newServerError(reply);
				} else {
					lastTimestamp = reply.timestamp;
					taskobject = reply.data;
					if (url.module == "edit") {
						tmp_participant.initalFillBigGrid(reply.data);
					} else if (url.module == "duplicate") {
						taskobject.number_of_attachments = 0;
						taskobject.participants = [];
					}					
					fillTaskFields(taskobject);
				}
			} else {
				triggerEvent("OX_New_Error", 4, _("No server connection"));
			}
			// disable loading screen
            $("loading_data_bg").style.display="none";
            // ready
            triggerReady();
		}
	);
}

function fillTaskFields(taskobject) {
    
    // set title
    var title = taskobject.title || "";
    $("title").value = title;
    document.title = (url.module === "edit" ? _("Change Task") : _("New Task")) + (title  ? ": " : "") + title;
    
	if (taskobject.color_label) $("color_label").value = taskobject.color_label;
	
	if (taskobject.status === null || isNaN(taskobject.status)) {
        // set default status if it's not a number
	    taskobject.status = 1;
        // if percent complete greater then 0 its in progress
        if ((taskobject.percent_completed || 0) > 0) {
            taskobject.status = 2;
        }
    }
	
    comboStatusTask.setKey(parseInt(taskobject.status) - 1);
    
	if (taskobject.start_date) {
		var mydatestart=new Date(taskobject.start_date);
		$("newtask_begins_date").value=formatDate(taskobject.start_date,"date");
		nt_begins_date_changed();
	}
	if (taskobject.end_date) {
		var mydateend=new Date(taskobject.end_date);
		$("newtask_ends_date").value=formatDate(taskobject.end_date,"date");
		nt_ends_date_changed();
	}
	
	if(taskobject.private_flag && taskobject.private_flag == true) {
		$("newtask_personal").checked = "checked";					
	}
	if (taskobject.participants && taskobject.participants.length) $("partCounterTasksNew").firstChild.data = taskobject.participants.length;
	if (taskobject.priority) comboPriorityTask.setKey(parseInt(taskobject.priority) - 1);
	if (taskobject.percent_completed) $("percent_completed").value = taskobject.percent_completed;
	if (taskobject.alarm) {
		$("newtask_reminder_date").value = formatDate(new Date(taskobject.alarm),"date");
		$("newtask_reminder_hour").value = formatDate(new Date(taskobject.alarm),"time");
	}
	if (taskobject.note) $("note").value = taskobject.note;
	if (taskobject.categories) {
		task_categories = taskobject.categories;
		// draw list
		if ($("newtask_categories_list")) {
			ox.categories.ui.drawCategoriesList(ox.categories.getByString(task_categories), 
					$("newtask_categories_list"));
		}
	}	
	if (taskobject.actual_duration) $("actual_duration").value = taskobject.actual_duration;
	if (taskobject.target_duration) $("target_duration").value = taskobject.target_duration;

	if (taskobject.currency) comboCostsTask.setKey(taskobject.currency);					
	if (taskobject.target_costs) $("target_costs").value = round(taskobject.target_costs);
	if (taskobject.actual_costs) $("actual_costs").value = round(taskobject.actual_costs);
	if (taskobject.billing_information) $("billing_information").value = taskobject.billing_information;
	if (taskobject.companies) $("companies").value = taskobject.companies;
	if (taskobject.number_of_attachments){
		setNumberOfAttNewTask(taskobject.number_of_attachments);
	}								
	globalseries.setParameters(taskobject);
	$("taskSequence").value = globalseries.getSeriesString();
	if (taskobject.trip_meter) $("trip_meter").value = taskobject.trip_meter;
}

function canselProcessTaskWindow() {
	function cbyes() {
	    ctrl.close(true);
	}
	if (taskCloseBit) {
		newConfirm(_("Close Window"), messageCloseWindow, AlertPopup.YESNO,
		    null, null, cbyes, null);		
	} else {
		cbyes();
	}
}

function closeTaskWindow() {	
	taskCloseBit = false;
	setBeforeUnload(taskCloseBit);
	window.setTimeout(
		function() {
		    ctrl.close(true);
		},50
	);
}

function saveTask() {
	if(savePending) return;
	else savePending = true;
	
	if (modulPopup == "new" || modulPopup == "duplicate") {
		writeNewTask();
	} else if (modulPopup == "edit") {
		updateTask();
	}
}
function readTaskFields() {
	var duration_type_sel = 0;
	var ta_object = { };
	
	var ta = $("newTaskForm");
	allOk=0;
	var error_msg;
	if ($("newtask_begins_date").value) {
		if (!parseDateString($("newtask_begins_date").value,"date")) allOk = 2;
	} else allOk = 0;
	
	if ($("newtask_ends_date").value && parseDateString($("newtask_ends_date").value,"date") == null) {
		allOk = 1;
	} else {
		allOk = 0;
	}
	if (($("newtask_ends_date").value != "" && !parseDateString($("newtask_ends_date").value,"date")) 
			|| ($("newtask_begins_date").value != "" && !parseDateString($("newtask_begins_date").value,"date"))
			|| ($("newtask_reminder_date").value != "" && !parseDateString($("newtask_reminder_date").value,"date"))) {
		allOk = 2;
	}
	try {
		if (($("newtask_ends_date").value != "" && $("newtask_begins_date").value != "") && (parseDateString($("newtask_ends_date").value,"date").getTime()
				< parseDateString($("newtask_begins_date").value,"date").getTime())) {
			allOk = 3;
		}
	} catch (e) { }
	
	var tmpval = trimStr($("target_costs").value);
	if (tmpval.length != 0 && tmpval > 130000 || tmpval < -130000) {
	    //#. %s is a field name (estimated costs or current costs).
	    //#, c-format
		error_msg = format(_("The entered value for %s is not within the allowed range. Please use a value from -130000 to 130000."), _("estimated costs"));
		allOk = 4;
	} else if (tmpval != taskobject.target_costs || taskobject.target_costs != ta_object.target_costs) {
		ta_object.target_costs = tmpval.length != 0 ? tmpval : null;
	}
	var tmpval = trimStr($("actual_costs").value);
    if (tmpval.length != 0 && tmpval > 130000 || tmpval < -130000) {
        //#. %s is a field name (estimated costs or current costs).
        //#, c-format
        error_msg = format(_("The entered value for %s is not within the allowed range. Please use a value from -130000 to 130000."), _("current costs"));
        allOk = 4;
    } else if (tmpval != taskobject.actual_costs || taskobject.actual_costs != ta_object.actual_costs) {
		ta_object.actual_costs = tmpval.length != 0 ? tmpval : null;
	}
        
    switch (allOk) {
		case 1: error_msg = _("Mandatory Field(s) missing!");
		case 2: error_msg = _("Incorrect input.");
		case 3: error_msg = _("End date is before start date.");
		case 4:  
			setTimeout(function() { 
				triggerEvent("OX_New_Error", 4, error_msg); 
			}, 0);
			break;
    }  
	
	if($("newtask_personal").checked && ($("newtask_personal_tr").style.visibility == "visible" || $("newtask_personal_tr").style.visibility == "")) {
		ta_object.private_flag = true;
	} else {
		ta_object.private_flag = false;
	}
	try {
		if ($("newtask_begins_date").value != "") {
			ta_object.start_date = parseDateString($("newtask_begins_date").value,"date").getTime();
		} else if (taskobject.start_date) {
			ta_object.start_date = null;
		}
	} catch (e) { }
	try {
		if ($("newtask_ends_date").value != "") {
			ta_object.end_date = parseDateString($("newtask_ends_date").value,"date").getTime();
		} else if (taskobject.end_date) {
			ta_object.end_date = null;
		}
	} catch (e) { }
	
	if (tmp_participant != undefined) {
		ta_object.participants = tmp_participant.getParticipants();
	} 
	
	var percComp = $("percent_completed").value;
	if (percComp > 0) {
		if (percComp == 100) {
			ta_object.percent_completed = $("percent_completed").value;
			if (comboStatusTask.getKey() < 3) {
				ta_object.status = 3;
			} else {
				ta_object.status = parseInt(comboStatusTask.getKey()) + 1;
			}
		} else if (percComp < 100) {
			ta_object.percent_completed = $("percent_completed").value;
			if (comboStatusTask.getKey() < 3) {
				ta_object.status = 2;
			} else {
				ta_object.status = parseInt(comboStatusTask.getKey()) + 1;
			}
		}
	} else {
		ta_object.percent_completed = 0;
		if (comboStatusTask.getKey() < 3) {
			ta_object.status = 1;
		} else {
			ta_object.status = parseInt(comboStatusTask.getKey()) + 1;
		}
	}
	
	ta_object.folder_id = (newFolderName && newFolderName != "") ? newFolderName : activefolder;
	ta_object.notification = $("notification").checked;
	
	if ($("target_costs").value || $("actual_costs").value) {
		ta_object.currency = comboCostsTask.getKey();
	}
	
	if (typeof(task_categories) != 'undefined') {
		ta_object.categories = task_categories;
	}
		
	if ($("newtask_reminder_date").value) {
		var ta1 = 0;
		var ta2 = 0;
		// make this multi languageable
		if ($("newtask_reminder_date").value) ta1 = parseDateString($("newtask_reminder_date").value, "date");
		if (!ta1) {
			triggerEvent("OX_New_Error", 4, _("Invalid date."));
			return;
		}
		if (comboRemindTask.getKey()) {
			if ($("newtask_reminder_hour").value) ta2 = parseDateString($("newtask_reminder_hour").value, "time");
			if (!ta2) {
				triggerEvent("OX_New_Error", 4, _("Invalid time."));
				return;
			}
		}
		ta_object.alarm = ta1.getTime() + ta2.getTime();
	} else if (taskobject.alarm) {
		ta_object.alarm = null;
	}
	
	if (comboPriorityTask.getKey()) {
		ta_object.priority = parseInt(comboPriorityTask.getKey()) + 1;
	}
	
	// a list of fields which will be checked on empty fields. we have to set an explicit null
	// otherwise it got removed from the object send to the server
    var fields2null = ["actual_duration","target_duration","trip_meter","billing_information","companies","note"];
    for (var aa in fields2null) {
    	var tmpval = trimStr($(fields2null[aa]).value);
    	if (tmpval != taskobject[fields2null[aa]] || taskobject[fields2null[aa]] != ta_object[fields2null[aa]]) {
    		ta_object[fields2null[aa]] = tmpval.length != 0 ? tmpval : null;
    	}
    }
	
	for (var i=0; i<ta.elements.length; i++) {
		var elementName = ta.elements[i].name;
		var value = ta.elements[i].value;
		if (elementName.match(/newtask/) || value == "") continue;
		switch (elementName) {
		      case "notification":
		      case "percent_completed":
		      case "note":
		          break;
		      default: 
		          if (elementName != "") {
		          	ta_object[elementName] = ta.elements[i].value;
		          }
		          break;
		}			
	}
	return ta_object;
}

function updateTask() {
	ta_object = readTaskFields();	
	var oldObject=clone(taskobject);
	var newObject=clone(ta_object);
	checkModified(taskobject, ta_object);
		
	if (ta_object==null) {
		savePending = false;
		return;
	} 
	
   if (globalseries != null) {
        ta_object=globalseries.getParameters(ta_object,modulPopup);        
        if (globalseries.seriesobject.recurrence_type == 0) {
            ta_object.recurrence_type = 0;
        }        
    }
	
	if (allOk == 0 && checkTaskNumberFormat == 0) {
	    setModalBusy(true);
		json.put(AjaxRoot + "/tasks?action=update&folder=" + activefolder + "&session=" +
			session + "&id=" + taskDetailId + "&timestamp=" + lastTimestamp,
			ta_object,
			null,
			// success handler
			function(reply) {
				function finalFunction () {
					function fn_cb(){
						if (!reply.error) {
							closeTaskWindow();
						}
					}
					// TODO: review bug fix 17278
                    corewindow.OXCache.newRequest(null, "tasks", {
                        columns: null,
                        objects: [corewindow.OXTaskMapping.createKeyFromObject({
                            module: "tasks", folder_id: activefolder, // ta_object does not contain folder_id
                            id: taskDetailId
                        })] }, null, emptyFunction, true);
                    if (activefolder != ta_object.folder_id) {
                        corewindow.OXTaskMapping.deleteObjectsInternal(
                            [corewindow.OXTaskMapping.createKeyFromObject({
                                module: "tasks", folder_id: activefolder,
                                id: taskDetailId
                            })]);
                    }
					if (tmp_attachmentDialog.attach_changed()) {
						corewindow.triggerEvent("OX_Quota_Update");
					}
                    ox.api.window.core.triggerEvent("OX_NEW_TASK_SAVE_SUCCESS", 
                       reply, url.guid);

                    fn_cb();
				}
				if (tmp_attachmentDialog.attach_changed()) {
                    newObject.number_of_attachments = 
                        tmp_attachmentDialog.file_storage.ids.length;
					var obj = new Object();
					obj['attached'] = taskDetailId;
					obj['module'] = 4; 				
					obj['folder'] = activefolder;
					// update attachments
					tmp_attachmentDialog.do_post(
					    // data
					    obj,
					    // success
					    finalFunction, null, null, 
					    // error
					    function (response) {
					        newServerError(response);
					        setModalBusy(false);
					    }
					);
				}
				else {
					finalFunction();
				}
			},
			// error handler
			setModalBusy
		); 
	} else {
		savePending = false;
		checkTaskNumberFormat = 0;
	}
}

function writeNewTask() {
	ta_object = readTaskFields();
	var newObject=clone(ta_object);
	
	if (ta_object==null) {
		savePending = false;
		return;
	}
	
   if (globalseries != null) {
        ta_object=globalseries.getParameters(ta_object,modulPopup);        
        if (globalseries.seriesobject.recurrence_type == 0) {
            ta_object.recurrence_type = 0;
        }        
    }
	
	if (allOk == 0 && checkTaskNumberFormat == 0) {
	    setModalBusy(true);
		json.put(AjaxRoot + "/tasks?action=new&folder=" + activefolder + "&session=" + session,
			ta_object,
			null,
			// success
			function(reply) {
				function finalFunction() {
					function fn_cb(){
						if (!reply.error) {					
							closeTaskWindow();
						}
					}
                    ox.api.window.core.triggerEvent("OX_NEW_TASK_SAVE_SUCCESS", reply, url.guid);
					corewindow.OXTaskMapping.createObject(newObject);
					if (tmp_attachmentDialog.attach_changed()) {
						corewindow.triggerEvent("OX_Quota_Update");
					}
                    fn_cb();
				}
				if (tmp_attachmentDialog.attach_changed()) {
                    var obj = new Object();
					obj['attached'] = reply.data.id;
					obj['module'] = 4; 				
					obj['folder'] = activefolder;
					tmp_attachmentDialog.do_post(obj,finalFunction);
				}
				else {
					finalFunction();
				}
			},
			// error
			setModalBusy
		);
	} else {
		checkTaskNumberFormat = 0;
		savePending = false;
	}
}

function openSequenceWindow(){
	$("sequenceWindow").style.display = "block";
}

/**
 * functions to modify the "percent_complete" value
 */

function doneModify(wh) {
	var done = $("percent_completed").value;
	var dv = 0, statVal = 0;
	
	if (!isNaN(done)) {
		dv = parseInt(done, 10) + wh;
	}
	if (dv <= 0) {
		dv=0; 
		statVal=0;
	} else if (dv < 100) {
		statVal=1;
	} else if (dv >= 100) {
		dv=100;
		statVal=2;
	}
	comboStatusTask.setKey(statVal);
	$("percent_completed").value = dv;
}

function doneModifyDown(field) {
	var ta = $('newTaskForm');
	var oldvalue = $("percent_completed").value;
	var newvalue;
	if (field < 3) {
		if (oldvalue > 0 && field == 1) newvalue = oldvalue;
		if (oldvalue == 0 && field == 1) newvalue = 25;
		if (oldvalue == 100 && field == 1) newvalue = 75;
		if (field == 2) newvalue = 100;
		if (field == 0) newvalue = 0;
		if (oldvalue != newvalue) $("percent_completed").value = newvalue;
	} else if (oldvalue == 100) {
		$("percent_completed").value = 75;
	} 
}

function changeSequenceView(what) {
	for (a = 0; a < adiv.length; a++) {
		$(adiv[a]).style.display="none";
	}
	$(what).style.display="block";
}

function reselectView() {
	for (a = 0; a < document.getElementsByName("dso").length; a++) {
		if (document.getElementsByName("dso")[a].checked == true) {
			changeSequenceView(document.getElementsByName("dso")[a].value);
		}
	}
}
register("OX_Task_New_Switch",function(param) { menuswitchTaskNew(param); });
var tabsList = new Array('tab1','tab2', 'tab3', 'tab4');
var panelsList = new Array('panel1','panel2', 'panel3', 'panel4');
var eventList = new Array(
					['OX_Task_New_Switch','task'],
					['OX_Task_New_Switch','detail'],
					['OX_Task_New_Switch','participant'],
					['OX_Task_New_Switch','attachment']
				);

function fillSelectBoxes() {
	// The status box
	
	comboStatusTask = new ComboBox3(window,"statusSelectBox","10em",0,true,"doneModifyEvent",null);
	comboStatusTask.addElement(_("Not started"),"0");
	comboStatusTask.addElement(_("In progress"),"1");
	comboStatusTask.addElement(_("Done"),"2");
	comboStatusTask.addElement(_("Waiting"),"3");	
	comboStatusTask.addElement(_("Deferred"),"4");	
	comboStatusTask.getDomNode();

	// The priority box	
	comboPriorityTask=new ComboBox3(window,"prioritySelectBox","10em",1,true,null,null);
	comboPriorityTask.addElement(_("Low"),"0");
	comboPriorityTask.addElement(_("Normal"),"1");
	comboPriorityTask.addElement(_("High"),"2");
	comboPriorityTask.getDomNode();

/*	// The duration type box	
	comboDurationTask=new ComboBox3(window,"durationSelectBox","7em",1,true,null,null);
	comboDurationTask.addElement(_("hours"),"0");
	comboDurationTask.addElement(_("days"),"1");
	comboDurationTask.addElement(_("weeks"),"2");
	comboDurationTask.addElement(_("months"),"3");
	comboDurationTask.getDomNode();
	*/
	
	//The Remind me by mail box
	comboRemindTask=new ComboBox3(window,"remindmeSelectBox","8em",16,true,"changeRemindTime",4);
	register("changeRemindTime", changeRemindTimeFunction);
	iv=60;
	if(corewindow.configContainsKey("gui.tasks.interval")) {
		iv = corewindow.configGetKey("gui.tasks.interval");
	}
	interv = 60 / iv;
	for (var i = 0; i < 24; i++) {
		for	(var j = 0; j < interv; j++) {
			hour = i;
			minute = iv * j;
			var displayValue = new String(new String(hour) + ":" + (minute));
			keyValue = new String(new String(hour) + (minute));
			var timeString = new Date(Date.UTC(1970,0,1,parseInt(hour),parseInt(minute),0));
			comboRemindTask.addElement(formatDate(timeString,"time"), new Date(timeString));
		}
	}
	comboRemindTask.getDomNode();

	// The costs type box	
    comboCostsTask=new ComboBox3(window,"costsSelectBox","5em",0,true,null,null);
	var isoLang = corewindow.config.language.split("_")[1];
	function currencyLanguageMatch(cur) {
		for (var i=0; i<cur.isoLangCodes.length; i++) {
			if (isoLang == cur.isoLangCodes[i]) return true;
		}
		return false;		  
	}
	var index=0;
	for (var i in corewindow.currencies) {
		var cur = corewindow.currencies[i];
		comboCostsTask.addElement(noI18n(cur.iso), cur.iso);
		if (currencyLanguageMatch(cur)) comboCostsTask.selected = index;
		index++;	
	}
	comboCostsTask.getDomNode();
}

function changeRemindTimeFunction() {
	$("newtask_reminder_hour").value = formatDate(comboRemindTask.getKey(), "time");
}

function showMiniStart(){
	var tmp = $("mini_start");
	$("mini_end").style.display = "none";
	tmp.style.display = "block";
	tmp.style.left = 210 + "px";
	tmp.style.top = 120 + "px";
	tmp.style.height = 210 + "px";
}

function showMiniEnd(){
	var tmp = $("mini_end");
	$("mini_start").style.display = "none";	
	tmp.style.display = "block";
	tmp.style.left = 210 + "px";
	tmp.style.top = 120 + "px";
	tmp.style.height = 210 + "px";
}

function toggleMiniStart(){
	var tmp = $("mini_start");
	if(!miniStartVisible){
		$("mini_end").style.display = "none";
		tmp.style.display = "block";
		tmp.style.left = 210 + "px";
		tmp.style.top = 120 + "px";
		tmp.style.height = 210 + "px";
		miniStartVisible = true;
		miniEndVisible = false;
	} else {
		tmp.style.display = "none";
		miniStartVisible = false;
	}
}

function toggleMiniEnd(){
	var tmp = $("mini_end");
	if(!miniEndVisible){
		$("mini_start").style.display = "none";
		tmp.style.display = "block";
		tmp.style.left = 210 + "px";
		tmp.style.top = 120 + "px";
		tmp.style.height = 210 + "px";
		miniEndVisible = true;
		miniStartVisible = false;
	} else {
		tmp.style.display = "none";
		miniEndVisible = false;
	}
}

function toggleMiniReminder(param) {
	if (param != "off") {
		$("mini_reminder").style.display = "block";
	} else {
		$("mini_reminder").style.display = "none";
	}
}

function showMiniReminder() {
		var tmp = $("mini_reminder");
		if (!miniRemindVisible) {
			$("mini_start").style.display = "none";
			$("mini_end").style.display = "none";
			if (!$("newtask_reminder_date").data || $("newtask_reminder_date").data == "" ) {
				tmp.style.display = "block";
			}
			tmp.left = 0;
			tmp.top = "1.6em";
			miniEndVisible = false;
			miniRemindVisible = true;
			miniStartVisible = false;
		} else {
			tmp.style.display = "none";
			miniRemindVisible = false;
		}
	}

function createMiniCalendar(){
	beginCalendar = new cMiniCalendar(	$("begin_header"),
										$("begin_container"), 
										setStartDate,
										false,
										"beginCalendar",
										$("begin_header_month"),
										$("begin_header_year")										
										);
										
	endCalendar = new cMiniCalendar(	$("end_header"),
										$("end_container"), 
										setEndDate,
										false,
										"endCalendar",
										$("end_header_month"),
										$("end_header_year"));
										
	remindCalendar = new cMiniCalendar(	$("remind_header"), 
							 			$("remind_container"), 
										setReminderDate,
										false,
										"remindCalendar",
										$("remind_header_month"),
										$("remind_header_year"));
}

function setStartDate() {
	beginCalendar.setSelected(this.id);
	var mydate=Date.UTC(beginCalendar.selectedYear,beginCalendar.selectedMonth,beginCalendar.selectedDate,0,0,0);
	$("newtask_begins_date").value = formatDate(mydate,"date");
	$("mini_start").style.display = "none";
}

function setEndDate(){
	endCalendar.setSelected(this.id);
	var mydate=Date.UTC(endCalendar.selectedYear,endCalendar.selectedMonth,endCalendar.selectedDate,0,0,0);
	$("newtask_ends_date").value = formatDate(mydate,"date");
	$("mini_end").style.display = "none";
}

function setReminderDate(){
	remindCalendar.setSelected(this.id);
	var mydate=Date.UTC(remindCalendar.selectedYear,remindCalendar.selectedMonth,remindCalendar.selectedDate,0,0,0);
	$("newtask_reminder_date").value = formatDate(mydate,"date");
	$("newtask_reminder_hour").value = comboRemindTask.getValue();
	$("mini_reminder").style.display = "none";
}

function setSequenceStartDate() {
	var tmp = $("sequenceForm");
	beginCalendar.setSelected(this.id);
	var startmonth = beginCalendar.selectedMonth+1;
	if(startmonth < 10 ) {
		startmonth = "0" + startmonth;
	}
	tmp.sequence_start_date.value = startmonth + "/" + beginCalendar.selectedDate + "/" + beginCalendar.selectedYear;	
	$("mini_start_sequence").style.display = "none";
}

function setSequenceEndDate(){
	var tmp = $("sequenceForm");
	endCalendar.setSelected(this.id);
	endmonth = endCalendar.selectedMonth+1;
	if(endmonth < 10 ){
		endmonth = "0" + endmonth;
	}
	tmp.sequence_end_date.value = endmonth + "/" + endCalendar.selectedDate + "/" + endCalendar.selectedYear;	
	$("mini_end_sequence").style.display = "none";
}

function getMonthName(id) {
	var outString2;
	switch(id) {
		case "0":
			outString2 = _("January");
			break;
		case "1":
			outString2 = _("February");
			break;
		case "2":
			outString2 = _("March");
			break;
		case "3":
			outString2 = _("April");
			break;
		case "4":
			outString2 = _("May");
			break;
		case "5":
			outString2 = _("June");
			break;
		case "6":
			outString2 = _("July");
			break;
		case "7":
			outString2 = _("August");
			break;
		case "8":
			outString2 = _("September");
			break;
		case "9":
			outString2 = _("October");
			break;
		case "10":
			outString2 = _("November");
			break;
		case "11":
			outString2 = _("December");
			break;
		default:
			break;
	}
	return outString2;
}

function getDayName(id) {
	var outString;
	switch(id) {
		case "1":
			outString = _("Sunday");
			break;
		case "2":
			outString = _("Monday");
			break;
		case "3":
			outString = _("Tuesday");
			break;
		case "4":
			outString = _("Wednesday");
			break;
		case "5":
			outString = _("Thursday");
			break;
		case "6":
			outString = _("Friday");
			break;
		case "7":
			outString = _("Saturday");
			break;
		default:
			break;
	}
	return outString;
}

function radioValue(rObj) {
	for (var i=0; i<rObj.length; i++) if (rObj[i].checked) return rObj[i].value;
	return false;
}

function checkboxValue(rObj) {
	var daysByteValue = 0;
	for (var i=0; i<rObj.length; i++) {
		if (rObj[i].checked)
		daysByteValue = parseInt(parseInt(rObj[i].value) + parseInt(daysByteValue));
	}
	return daysByteValue;
}

function getUnixTime(val) {
	if (val != "") {
		var d = new Date();
		var dString = new Array();
		var ra=/^(\d{1,2})[-.\/](\d{1,2})[-.\/](\d{2,4})$/;
		var fi = ra.exec(val);
		if ( fi == null )
			error=true;
		month = RegExp.$1;
		day = RegExp.$2;
		year = RegExp.$3;
		dString[0] = parseInt(day) + 1;
		dString[1] = month;
		dString[2] = year;
		return Date.parse(dString[1] + "/" + dString[0] + "/" + dString[2]);
	} else {
		return 0;
	}
}

function showTreeTasks(){
	toggleTreeTasks();
}

function hideTree(){
	toggleTreeTasks();	
}

function toggleTreeTasks(){
	if(newTaskFolderTree == undefined)		
		initTaskTree();
	if(!treeVisible) {
		centerPopupWindow($("TreeDialogTask"));
		$("TreeDialogTask").style.display = "block";
		$("TreeDialogTask").style.top = "120px";
		$("TreeDialogTask").style.left = "170px";
		treeVisible = true;
		if(!taskTreeLoaded) {
//			newTaskFolderTree.load();
			taskTreeLoaded = true;
			}
	}
	else{
		$("TreeDialogTask").style.display = "none";
		treeVisible = false;
	}
}

function initTaskTree() {		

	ox.api.folder.getPathString({
	    folder: url.folder,
		success: function (sPath) {
			document.getElementsByName('newtask_folder')[0].value = sPath;
		}
	});
		
	var folderViewSettingsNewTask = new Object();
	//Disable Email... 
	folderViewSettingsNewTask["mail"] = 4;
	folderViewSettingsNewTask["tasks"] = 8;
	if(!treeLoaded){
		ox.api.ui.selectFolder({
	    	type: "tasks",
	    	id: "select-folder-popup-tasks",
	    	callback: folderTasksAction,
	    	node: $('folder_tree_info')
	    });				
		treeLoaded = true;
	}							
}

function folderTasksAction(data) {

	toggleTree();
	newFolderName = data.id;

	function cb_getpath(sPath) {
		document.getElementsByName('newtask_folder')[0].value = sPath;
		if(data.type != 1){
			$("newtask_personal_tr").style.visibility = "hidden";
		} else {
			$("newtask_personal_tr").style.visibility = "visible";
		}		
	}	
	
	ox.api.folder.getPathString({
	    folder: newFolderName,
	    success: cb_getpath
	});
}

function toggleTree(){
	if(!treeVisible){
		centerPopupWindow($("TreeDialogTask"));
		$("TreeDialogTask").style.display = "block";
		$("TreeDialogTask").style.top = "120px";
		$("TreeDialogTask").style.left = "170px";
		treeVisible = true;

	}
	else{
		$("TreeDialogTask").style.display = "none";
		treeVisible = false;
	}
}

function checkCorrectInput(param, id) {
	return;
	if(isNaN($(id).value)) {
		triggerEvent("OX_New_Error", 4, _("Incorrect input, only numbers are allowed."));
		$(id).value = "";
		checkTaskNumberFormat = -1;
	}
}

function ce() {
	taskCloseBit = true;
	setBeforeUnload(taskCloseBit);
}

//init window controller

var ctrl = windowController = new WindowController();

ctrl.set("beforeunload", function () {
    if (messageOnCancel) {
        return messageCloseWindow + "";
    }
});