<?
	$ENTspace = array("&nbsp;", "&nbsp"); // Замена неразрывных пробелов
	
	/* Добавление быстрой задачи */
	if( isset( $_POST['QTaskAdd'] ) ) {
		$formTaskId 		= newID('tasks','tasks','task');
		$formTaskName 		= $_POST["inputName"];
		$formTaskType 		= '';
		$formTaskComment 	= '';
		$formTaskDeal 		= '';
		$formTaskUser 		= '';
		$formTaskDateStart 	= date("Y-m-d");
		$formTaskDateEnd 	= '';
		$formTaskPriority 	= '';
		$formTaskLink 		= '';
		$formTaskStatus 	= 'inwork';
		$formTaskPercent 	= '0';
		
		$dom = new DOMDocument; 
		$dom->load($baseT);
		$xpath = new DOMXPath($dom);
		$tasks=$xpath->query('/tasks')->item(0);
		$task = $dom->createElement('task');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("status");
		$attribute3 = $dom->createAttribute("deligated");
		$attribute4 = $dom->createAttribute("deal");
		$attribute5 = $dom->createAttribute("priority");
		$attribute6 = $dom->createAttribute("percent");
		$attribute7 = $dom->createAttribute("type");
		$attribute1->value = $formTaskId;
		$task->appendChild($attribute1);
		$attribute2->value = $formTaskStatus;
		$task->appendChild($attribute2);
		$attribute3->value = $formTaskUser;
		$task->appendChild($attribute3);
		$attribute4->value = $formTaskDeal;
		$task->appendChild($attribute4);
		$attribute5->value = $formTaskPriority;
		$task->appendChild($attribute5);
		$attribute6->value = $formTaskPercent;
		$task->appendChild($attribute6);
		$attribute7->value = $formTaskType;
		$task->appendChild($attribute7);
		$task->appendChild($dom->createElement('taskname', $formTaskName));
		$task->appendChild($dom->createElement('supervisor', ''));
		$task->appendChild($dom->createElement('comment', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $formTaskComment)), 0, 50, 'UTF-8') . '...'));
		$task->appendChild($dom->createElement('datestart', $formTaskDateStart));
		$task->appendChild($dom->createElement('dateend', $formTaskDateEnd));
		$task->appendChild($dom->createElement('link', $formTaskLink));
		$task->appendChild($dom->createElement('timeinwork', ''));
		$task->appendChild($dom->createElement('uip', $sessionIP));
		$tasks->appendChild($task);
		$dom->save($baseT);
		
		// Добавление файла с комментарием
		$taskDir = ROOT . 'crmdata/upload/tasks_'.$formTaskId;
		$taskFile = $taskDir . '/page_description.xml';
		if (!is_dir($taskDir)){
			mkdir($taskDir);
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		if (file_exists($taskFile)){
			$dom = new DOMDocument; 
			$dom->load($taskFile);
			$xpath = new DOMXPath($dom);
			$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $formTaskComment);
			$dom->save($taskFile);
		}
		
		// Добавление лога
		new_log("Добавление задачи: $formTaskName");

		$notices[] = 'Задача успешно добавлена';
	}
	
	/* Добавление задачи */
	if( isset( $_POST['TaskAdd'] ) ) {
		$formTaskId 		= newID('tasks','tasks','task');
		$formTaskName 		= $_POST["inputName"];
		$formTaskType 		= $_POST["selectType"];
		$formTaskComment 	= $_POST["inputComment"];
		$formTaskDeal 		= $_POST["selectDeal"];
		$formTaskUser 		= $_POST["selectUser"];
		if($_POST["selectUser"] == $LoginCheck){
			$formTaskUserS 		= '';
		} else {
			$formTaskUserS 		= $LoginCheck;
		}
		$formTaskDateStart 	= $_POST["inputDateStart"];
		$formTaskDateEnd 	= $_POST["inputDateEnd"];
		$formTaskPriority 	= $_POST["selectPriority"];
		$formTaskLink 		= $_POST["inputLink"];
		$formTaskStatus 	= 'inwork';
		$formTaskPercent 	= '0';
		
		if(isset($_POST["NewTempl"])){
			
			new_templ($formTaskName, $formTaskComment);
			$notices[] = 'Шаблон успешно создан';
			new_log("Создан шаблон: $formTaskName");
			
		} else {
			
			$dom = new DOMDocument; 
			$dom->load($baseT);
			$xpath = new DOMXPath($dom);
			$tasks=$xpath->query('/tasks')->item(0);
			$task = $dom->createElement('task');
			$attribute1 = $dom->createAttribute("id");
			$attribute2 = $dom->createAttribute("status");
			$attribute3 = $dom->createAttribute("deligated");
			$attribute4 = $dom->createAttribute("deal");
			$attribute5 = $dom->createAttribute("priority");
			$attribute6 = $dom->createAttribute("percent");
			$attribute7 = $dom->createAttribute("type");
			$attribute1->value = $formTaskId;
			$task->appendChild($attribute1);
			$attribute2->value = $formTaskStatus;
			$task->appendChild($attribute2);
			$attribute3->value = $formTaskUser;
			$task->appendChild($attribute3);
			$attribute4->value = $formTaskDeal;
			$task->appendChild($attribute4);
			$attribute5->value = $formTaskPriority;
			$task->appendChild($attribute5);
			$attribute6->value = $formTaskPercent;
			$task->appendChild($attribute6);
			$attribute7->value = $formTaskType;
			$task->appendChild($attribute7);
			$task->appendChild($dom->createElement('taskname', $formTaskName));
			$task->appendChild($dom->createElement('supervisor', $formTaskUserS));
			$task->appendChild($dom->createElement('comment', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $formTaskComment)), 0, 50, 'UTF-8') . '...'));
			$task->appendChild($dom->createElement('datestart', $formTaskDateStart));
			$task->appendChild($dom->createElement('dateend', $formTaskDateEnd));
			$task->appendChild($dom->createElement('link', $formTaskLink));
			$task->appendChild($dom->createElement('timeinwork', ''));
			$task->appendChild($dom->createElement('uip', $sessionIP));
			$tasks->appendChild($task);
			$dom->save($baseT);
			
			// Добавление файла с комментарием
			$taskDir = ROOT . 'crmdata/upload/tasks_'.$formTaskId;
			$taskFile = $taskDir . '/page_description.xml';
			if (!is_dir($taskDir)){
				mkdir($taskDir);
				file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			} else {
				file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			}
			if (file_exists($taskFile)){
				$dom = new DOMDocument; 
				$dom->load($taskFile);
				$xpath = new DOMXPath($dom);
				$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $formTaskComment);
				$dom->save($taskFile);
			}
			
			// Добавление лога
			new_log("Добавление задачи: $formTaskName");
			
			if( $_POST["selectUser"] != '' and $auth->getLogin() != $_POST["selectUser"]) {
				# Отправка уведомления о новой задаче #
				/*
				$doc = new DOMDocument;
				$doc->load($baseU);
				$xpath = new DOMXPath($doc);
				$UserEmail = $xpath->query('/users/user[@login="'. $formTaskUser .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
				$UserName = $xpath->query('/users/user[@login="'. $formTaskUser .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
				
				if (file_exists($baseD) and file_exists($fileD)) {
					$doc = new DOMDocument;
					$doc->load($baseD);
					$xpath = new DOMXPath($doc);
					$deals = $xpath->query('/deals/deal[@id="'. $formTaskDeal .'"]');
					for ($i = 0; $i < $deals->length; $i++) {
						$formTaskDealN = $xpath->query('/deals/deal[@id="'. $formTaskDeal .'"]')->item($i)->getElementsByTagName("dealnumber")->item(0)->nodeValue;
					}
				}
				if($formTaskDeal != ''){$taskDeal = $formTaskDealN;} else {$taskDeal = '- не указана -';}
				if($formTaskDateEnd != ''){$taskDateEnd = 'до ' . $formTaskDateEnd;} else {$taskDateEnd = '- не указан -';}
				if($formTaskPriority == 'none'){$taskPriority = 'отсутствует';}  elseif($formTaskPriority == 'low'){$taskPriority = 'низкая';} elseif($formTaskPriority == 'medium'){$taskPriority = 'средняя';} else {$taskPriority = 'высокая';}
				$subject 	= "CRM система. Вам делегирована задача";
				$message 	= '
					<h2>Здравствуйте, '. $UserName .'!</h2>
					<p>Вам делегирована задача "<b>'. $formTaskName .'</b>" (важность: <b>'. $taskPriority .'</b>)</p>
					<p>Срок выполнения: <b>'. $taskDateEnd .'</b>. Подробная информация доступна по <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/tasks/?view=' . $formTaskId . '" target="_blank">ссылке</a></p>
					<p><b>Описание:</b></p>'. $formTaskComment .'<br/>
					<p>CRM система <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/" target="_blank">'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/</a></p>
					<br/>
					<p>Хорошего дня и отличного настроения!</p>
				';
				send_email($UserEmail, "CRM система", $subject, $message);
				*/
				send_letter(get_user_id_login($formTaskUser), 'Вам делегирована задача', 'Уважаемый пользователь!<br/><br/>Вам делегирована новая задача', 'high', $formTaskId, '', '', '');
			}
			$notices[] = 'Задача успешно добавлена';
			
		}
	}
	
	/* Редактирование задачи */
	if( isset( $_POST['TaskEdit'] ) ) {
		$oldTaskId 			= $_POST["inputId"];
		
		$newTaskId 			= $_POST["inputId"];
		$newTaskName 		= $_POST["inputName"];
		$newTaskType 		= $_POST["selectType"];
		$newTaskComment 	= $_POST["inputComment"];
		$newTaskDeal 		= $_POST["selectDeal"];
		$newTaskUser 		= $_POST["selectUser"];
		$newTaskUserS 		= $_POST["inputUserS"];
		$newTaskDateStart 	= $_POST["inputDateStart"];
		$newTaskDateEnd 	= $_POST["inputDateEnd"];
		$newTaskPriority 	= $_POST["selectPriority"];
		$newTaskStatus 		= $_POST["selectStatus"];
		$newTaskPercent 	= $_POST["selectPercent"];
		$newTaskLink 		= $_POST["inputLink"];
		$newTaskTimeInWork	= $_POST["inputTimeInWork"];
		
		if(isset($_POST["NewTempl"])){
			new_templ($newTaskName, $newTaskComment);
			$notices[] = 'Шаблон успешно создан';
			new_log("Создан шаблон: $newTaskName");
		} else {
			$parent = new DomDocument;
			$parent_node = $parent->createElement('task');
			$attribute1 = $parent->createAttribute("id");
			$attribute2 = $parent->createAttribute("status");
			$attribute3 = $parent->createAttribute("deligated");
			$attribute4 = $parent->createAttribute("deal");
			$attribute5 = $parent->createAttribute("priority");
			$attribute6 = $parent->createAttribute("percent");
			$attribute7 = $parent->createAttribute("type");
			$attribute1->value = $newTaskId;
			$parent_node->appendChild($attribute1);
			$attribute2->value = $newTaskStatus;
			$parent_node->appendChild($attribute2);
			$attribute3->value = $newTaskUser;
			$parent_node->appendChild($attribute3);
			$attribute4->value = $newTaskDeal;
			$parent_node->appendChild($attribute4);
			$attribute5->value = $newTaskPriority;
			$parent_node->appendChild($attribute5);
			$attribute6->value = $newTaskPercent;
			$parent_node->appendChild($attribute6);
			$attribute7->value = $newTaskType;
			$parent_node->appendChild($attribute7);
			$parent_node->appendChild($parent->createElement('taskname', $newTaskName));
			$parent_node->appendChild($parent->createElement('supervisor', $newTaskUserS));
			$parent_node->appendChild($parent->createElement('comment', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $newTaskComment)), 0, 50, 'UTF-8') . '...'));
			$parent_node->appendChild($parent->createElement('datestart', $newTaskDateStart));
			$parent_node->appendChild($parent->createElement('dateend', $newTaskDateEnd));
			$parent_node->appendChild($parent->createElement('link', $newTaskLink));
			$parent_node->appendChild($parent->createElement('timeinwork', $newTaskTimeInWork));
			$parent_node->appendChild($parent->createElement('uip', $sessionIP));
			$parent->appendChild($parent_node);
			$dom = new DomDocument;
			$dom->load($baseT);
			$xpath = new DOMXpath($dom);
			$nodelist = $xpath->query('/tasks/task[@id="'.$oldTaskId.'"]');
			$oldnode = $nodelist->item(0);
			$newnode = $dom->importNode($parent->documentElement, true);
			$oldnode->parentNode->replaceChild($newnode, $oldnode);
			$dom->save($baseT);	
			
			// Добавление файла с комментарием
			$taskDir = ROOT . 'crmdata/upload/tasks_'.$newTaskId;
			$taskFile = $taskDir . '/page_description.xml';
			if (!is_dir($taskDir)){
				mkdir($taskDir);
				file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			} else {
				file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			}
			if (file_exists($taskFile)){
				$dom = new DOMDocument; 
				$dom->load($taskFile);
				$xpath = new DOMXPath($dom);
				$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $newTaskComment);
				$dom->save($taskFile);
			}
			
			// Добавление лога
			new_log("Редактирование задачи: $newTaskName");
			
			if( $_POST["selectUser"] != '' and $auth->getLogin() != $_POST["selectUser"]) {
				send_letter(get_user_id_login($newTaskUser), 'Ваша задача изменена', 'Уважаемый пользователь!<br/><br/>Обратите внимание что ваша задача изменена', 'high', $newTaskId, '', '', '');
			}
			$notices[] = 'Задача успешно сохранена';
		}
	}
	
/* Сохранение заметки */
	if( isset( $_POST['SaveDescription'] ) ) {
		$dom 	= new DomDocument;
		$dom	->load($baseT);
		$xpath 	= new DOMXpath($dom);
		$taskslist 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]');
		$tasks_name 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("taskname")->item(0)->nodeValue;
		$tasks_user 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('deligated');
		$tasks_descr 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("comment")->item(0)->nodeValue= mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $_POST["inputComment"])), 0, 50, 'UTF-8') . '...';
		$dom	->save($baseT);
		
		$taskDir = ROOT . 'crmdata/upload/tasks_'.$_GET["view"];
		$taskFile = $taskDir . '/page_description.xml';
		if (!is_dir($taskDir)){
			mkdir($taskDir);
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		if (file_exists($taskFile)){
			$dom = new DOMDocument; 
			$dom->load($taskFile);
			$xpath = new DOMXPath($dom);
			$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $_POST["inputComment"]);
			$dom->save($taskFile);
		}
		
		// Добавление лога
		new_log("Редактирование задачи $tasks_name");
		if( $auth->getLogin() != $tasks_user) {
			send_letter(get_user_id_login($tasks_user), 'Ваша задача изменена', 'Уважаемый пользователь!<br/><br/>Обратите внимание что описание вашей задачи изменено', 'high', $_GET["view"], '', '', '');
		}
		$notices[] = 'Описание успешно сохранено';
	}
	
/* Дублирование задачи */
	if( isset( $_POST['TaskCoppy'] ) ) {
		$dom = new DomDocument;
		$dom->load($baseT);
		$xpath = new DOMXpath($dom);
		
		$Id 			= $_GET["view"];
		$newId			= newID('tasks','tasks','task');
		
		$TaskName 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("taskname")->item(0)->nodeValue;
		$TaskStatus 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('status');
		$TaskType 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('type');
		$TaskPriority 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('priority');
		$TaskPercent 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('percent');
		$TaskUser 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('deligated');
		$TaskDeal 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getAttribute('deal');
		$TaskUserS 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("supervisor")->item(0)->nodeValue;
		$TaskComment 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("comment")->item(0)->nodeValue;
		$TaskLink 		= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("link")->item(0)->nodeValue;
		$TaskDateStart 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("datestart")->item(0)->nodeValue;
		$TaskDateEnd 	= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("dateend")->item(0)->nodeValue;
		$TaskTimeInWork = $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("timeinwork")->item(0)->nodeValue;
		$UIP 			= $xpath->query('/tasks/task[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("uip")->item(0)->nodeValue;
		
		$tasks=$xpath->query('/tasks')->item(0);
		$task = $dom->createElement('task');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("status");
		$attribute3 = $dom->createAttribute("deligated");
		$attribute4 = $dom->createAttribute("deal");
		$attribute5 = $dom->createAttribute("priority");
		$attribute6 = $dom->createAttribute("percent");
		$attribute7 = $dom->createAttribute("type");
		$attribute1->value = $newId;
		$task->appendChild($attribute1);
		$attribute2->value = $TaskStatus;
		$task->appendChild($attribute2);
		$attribute3->value = $TaskUser;
		$task->appendChild($attribute3);
		$attribute4->value = $TaskDeal;
		$task->appendChild($attribute4);
		$attribute5->value = $TaskPriority;
		$task->appendChild($attribute5);
		$attribute6->value = $TaskPercent;
		$task->appendChild($attribute6);
		$attribute7->value = $TaskType;
		$task->appendChild($attribute7);
		$task->appendChild($dom->createElement('taskname', $TaskName . '_копия'));
		$task->appendChild($dom->createElement('supervisor', $TaskUserS));
		$task->appendChild($dom->createElement('comment', $TaskComment));
		$task->appendChild($dom->createElement('datestart', $TaskDateStart));
		$task->appendChild($dom->createElement('dateend', $TaskDateEnd));
		$task->appendChild($dom->createElement('link', $TaskLink));
		$task->appendChild($dom->createElement('timeinwork', $TaskTimeInWork));
		$task->appendChild($dom->createElement('uip', $UIP));
		$tasks->appendChild($task);
		$dom->save($baseT);
		
		$taskCommentFile = ROOT . 'crmdata/upload/tasks_' . $Id . '/page_description.xml';
		$doz 	= new DOMDocument;
		$doz	->load($taskCommentFile);
		$xpathz = new DOMXPath($doz);
		$newTaskComment = $xpathz->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue;
		
		// Добавление файла с комментарием
		$taskDir = ROOT . 'crmdata/upload/tasks_'.$newId;
		$taskFile = $taskDir . '/page_description.xml';
		if (!is_dir($taskDir)){
			mkdir($taskDir);
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		if (file_exists($taskFile)){
			$dom = new DOMDocument; 
			$dom->load($taskFile);
			$xpath = new DOMXPath($dom);
			$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $newTaskComment);
			$dom->save($taskFile);
		}
		
		// Добавление лога
		new_log("Дублирование задачи: $TaskName");

		$notices[] = 'Задача успешно дублирована';
	}
	
	/* Удаление задачи */
	if( isset( $_POST['TaskDelete'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseT);
		$xpath = new DOMXPath($dom); 
		
		$id = $_POST["TaskDelId"];
		$TaskName 		= $xpath->query('/tasks/task[@id="'. $id .'"]')->item(0)->getElementsByTagName("taskname")->item(0)->nodeValue;
		$TaskUser 		= $xpath->query('/tasks/task[@id="'. $id .'"]')->item(0)->getAttribute('deligated');
		
		$tasks = $xpath->query('/tasks/task[@id="'.$id.'"]');
		$el = $tasks->item(0);
		$el->parentNode->removeChild($el);
		$dom->save($baseT);
		
		// Удаление Загрузок
		$dir 	= 	ROOT . 'crmdata/upload/tasks_'.$id;
		if (is_dir($dir)) {
			$files = glob($dir."/*");
			foreach ($files as $file) {      
				if (file_exists($file)) {
					unlink($file);
				}   
			}
			rmdir($dir);
		}

		// Добавление лога
		new_log("Удаление задачи: $TaskName");
		
		$LetterDescr 	= 'Уважаемый пользователь!<br/><br/>Обратите внимание что ваша задача "'.$TaskName.'" удалена';
		
		send_letter(get_user_id_login($TaskUser), 'Ваша задача удалена', $LetterDescr, 'high', '', '', '', '');

		$notices[] = 'Задача успешно удалена';
	}
	
	/* Завершение задачи */
	if( isset( $_POST['TaskDone'] ) ) {
		$TaskDoneId 	= $_POST["TaskDoneId"];
		$TaskNewUser 	= $LoginCheck;
		
		$doc = new DOMDocument;
		$doc->load($baseT);
		$xpath = new DOMXPath($doc);
		
		$TaskName 	= $xpath->query('/tasks/task[@id="'. $TaskDoneId .'"]')->item(0)->getElementsByTagName("taskname")->item(0)->nodeValue;
		$TaskUserS 	= $xpath->query('/tasks/task[@id="'. $TaskDoneId .'"]')->item(0)->getElementsByTagName("supervisor")->item(0)->nodeValue;
		$TaskDateE 	= $xpath->query('/tasks/task[@id="'. $TaskDoneId .'"]')->item(0)->getElementsByTagName("dateend")->item(0)->nodeValue;
		$date			= date("Y-m-d");
		$datetimeTaskDone	= DateTime::createFromFormat( 'Y-m-d', $date );
		$datetimeTaskStart 	= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->getElementsByTagName("datestart")->item(0)->nodeValue;
		$datetimeTaskStart2 = DateTime::createFromFormat( 'Y-m-d', $datetimeTaskStart );
		$datetimeTaskWork	= $datetimeTaskDone->diff( $datetimeTaskStart2 )->format( '%a' );
		
		$tasks 			= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]');
		$TaskStatus		= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->setAttribute('status', 'done');
		$TaskPercent	= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->setAttribute('percent', '100');
		
		if($TaskDateE == ''){
			$TaskDateEnew	= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->getElementsByTagName("dateend")->item(0)->nodeValue=$date;
		}
		/*
		if($GroupCheck != 'admin' OR $GroupCheck != 'manager'){
			$TaskUser		= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->setAttribute('deligated', $TaskNewUser);
		}
		*/
		$TaskDateInWork	= $xpath->query('/tasks/task[@id="'.$TaskDoneId.'"]')->item(0)->getElementsByTagName("timeinwork")->item(0)->nodeValue=$datetimeTaskWork+1;
		$doc->save($baseT);
		
		if($TaskUserS != '') {
			# Отправка уведомления о новой задаче #
			/*
			$doc = new DOMDocument;
			$doc->load($baseU);
			$xpath = new DOMXPath($doc);
			$UserSEmail 	= $xpath->query('/users/user[@login="'. $TaskUserS .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
			$UserSName 	= $xpath->query('/users/user[@login="'. $TaskUserS .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
			
			$subject 	= "CRM система. Задача завершена";
			$message 	= '
				<h2>Здравствуйте, '. $UserSName .'!</h2>
				<p>Задача "<b>'. $TaskName .'</b>" успешно завершена.</p>
				<br/>
				<p>CRM система <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/" target="_blank">'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/</a></p>
				<br/>
				<p>Хорошего дня и отличного настроения!</p>
			';
			send_email($UserEmail, "CRM система", $subject, $message);
			*/
			send_letter(get_user_id_login($TaskUserS), 'Задача завершена', 'Уважаемый пользователь!<br/><br/>Завершена задача, по которой вы назначены ответственным', 'high', $TaskDoneId, '', '', '');
		}
		
		// Добавление лога
		new_log("Завершение задачи: $TaskName");

		$notices[] = 'Задача завершена';
	}
	
	/* Возобновление задачи */
	if( isset( $_POST['TaskRestore'] ) ) {
		$TaskRestoreId 	= $_POST["TaskRestoreId"];
		
		$doc = new DOMDocument;
		$doc->load($baseT);
		$xpath = new DOMXPath($doc);
		
		$TaskName = $xpath->query('/tasks/task[@id="'. $TaskRestoreId .'"]')->item(0)->getElementsByTagName("taskname")->item(0)->nodeValue;
		$tasks 			= $xpath->query('/tasks/task[@id="'.$TaskRestoreId.'"]');
		$TaskUser 		= $xpath->query('/tasks/task[@id="'. $TaskRestoreId .'"]')->item(0)->getAttribute('deligated');
		$TaskStatus		= $xpath->query('/tasks/task[@id="'.$TaskRestoreId.'"]')->item(0)->setAttribute('status', 'inwork');
		$TaskPercent	= $xpath->query('/tasks/task[@id="'.$TaskRestoreId.'"]')->item(0)->setAttribute('percent', '0');
		$doc->save($baseT);
		
		// Добавление лога
		new_log("Возобновление задачи: $TaskName");
		
		send_letter(get_user_id_login($TaskUser), 'Задача возобновлена', 'Уважаемый пользователь!<br/><br/>Возобновлена задача, по которой вы назначены исполнителем', 'high', $TaskRestoreId, '', '', '');

		$notices[] = 'Задача успешно возобновлена';
	}
	/* Изменение важности */
	if( isset( $_POST['TaskChangePrior'] ) ) {
		$dom = new DOMDocument;
		$dom->load($baseT);
		$xpath = new DOMXPath($dom);
		if(isset($_GET['view']) AND $_GET['view'] != ''){
			$tasks = $xpath->query('/tasks/task[@id="'.$_GET['view'].'"]');
		} elseif(isset($_GET['edit']) AND $_GET['edit'] != ''){
			$tasks = $xpath->query('/tasks/task[@id="'.$_GET['edit'].'"]');
		}
		if($_POST['TaskChangePrior'] == '3'){
			$TaskNewPriorTxt = 'high';
		} elseif($_POST['TaskChangePrior'] == '2'){
			$TaskNewPriorTxt = 'medium';
		} elseif($_POST['TaskChangePrior'] == '1'){
			$TaskNewPriorTxt = 'low';
		} elseif($_POST['TaskChangePrior'] == '0'){
			$TaskNewPriorTxt = 'none';
		}

		$TaskNewPrior	= $tasks->item(0)->setAttribute('priority', $TaskNewPriorTxt);
		
		$dom->save($baseT);

		$notices[] = 'Важность изменена';
		
	}
	/* Напоминание о задаче */
	if( isset( $_POST['TaskRemind'] ) ) {
		$dom = new DOMDocument;
		$dom->load($baseT);
		$xpath = new DOMXPath($dom);
		if(isset($_GET['view']) AND $_GET['view'] != ''){
			$tasks = $xpath->query('/tasks/task[@id="'.$_GET['view'].'"]');
		} elseif(isset($_GET['edit']) AND $_GET['edit'] != ''){
			$tasks = $xpath->query('/tasks/task[@id="'.$_GET['edit'].'"]');
		}
		foreach ($tasks as $task) {
			$TaskId 		= $task->getAttribute('id');
			$TaskName 		= $task->getElementsByTagName("taskname")->item(0)->nodeValue;
			$TaskStatus 	= $task->getAttribute('status');
			$TaskType 		= $task->getAttribute('type');
			$TaskPriority 	= $task->getAttribute('priority');
			$TaskPercent 	= $task->getAttribute('percent');
			$TaskUser 		= $task->getAttribute('deligated');
			$TaskDeal 		= $task->getAttribute('deal');
			$TaskComment 	= $task->getElementsByTagName("comment")->item(0)->nodeValue;
			$TaskLink 		= $task->getElementsByTagName("link")->item(0)->nodeValue;
			$TaskDateStart 	= $task->getElementsByTagName("datestart")->item(0)->nodeValue;
			$TaskDateEnd 	= $task->getElementsByTagName("dateend")->item(0)->nodeValue;
			$TaskTimeInWork = $task->getElementsByTagName("timeinwork")->item(0)->nodeValue;
			$UIP 			= $task->getElementsByTagName("uip")->item(0)->nodeValue;
		}
		if( isset($_GET['view']) and $_GET['view'] != '' ) {
			$doc = new DOMDocument;
			$doc->load($baseD);
			$xpathc = new DOMXPath($doc);
			$deals = $xpathc->query('/deals/deal[@id="'.$TaskDeal.'"]');
			foreach ($deals as $deal) {
				$DealId 		= $deal->getAttribute('id');
				$DealNumber 	= $deal->getElementsByTagName("dealnumber")->item(0)->nodeValue;
				$DealClient 	= $deal->getAttribute('client');
				$doс = new DOMDocument;
				$doс->load(ROOT . '/crmdata/database/clients.xml');
				$xpathc = new DOMXPath($doс);
				$clients = $xpathc->query('/clients/client[@id="'. $DealClient .'"]');
				foreach ($clients as $client) {
					$ClientName 	= $client->getElementsByTagName("clientname")->item(0)->nodeValue;
				}
			}
			$dom = new DOMDocument;
			$dom->load($baseU);
			$xpath = new DOMXPath($dom);
			$users = $xpath->query('/users/user[@login="'.$TaskUser.'"]');
			foreach ($users as $user) {
				$UserSurName 	= $user->getElementsByTagName("usersurname")->item(0)->nodeValue;
				$UserName 		= $user->getElementsByTagName("username")->item(0)->nodeValue;
			}
		}
		
		if( $TaskUser != '' and $auth->getLogin() != $TaskUser) {
			# Отправка уведомления о новой задаче #
			/*
			$doc = new DOMDocument;
			$doc->load($baseU);
			$xpath = new DOMXPath($doc);
			$UserEmail = $xpath->query('/users/user[@login="'. $TaskUser .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
			$UserName = $xpath->query('/users/user[@login="'. $TaskUser .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
			
			if($TaskDeal != ''){$taskDeal = $formTaskDealN;} else {$taskDeal = '- не указана -';}
			if($TaskDateEnd != ''){$taskDateEnd = 'до ' . $TaskDateEnd;} else {$taskDateEnd = '- не указан -';}
			if($TaskPriority == 'none'){$taskPriority = 'отсутствует';}  elseif($TaskPriority == 'low'){$taskPriority = 'низкая';} elseif($TaskPriority == 'medium'){$taskPriority = 'средняя';} else {$taskPriority = 'высокая';}
			
			$subject 	= "CRM система. Напоминание об активной задаче";
			$message 	= '
				<h2>Здравствуйте, '. $UserName .'!</h2>
				<p>Напоминаем, что Вам делегирована задача "<b>'. $TaskName .'</b>" (важность: <b>'. $taskPriority .'</b>)</p>
				<p>Срок выполнения: <b>'. $taskDateEnd .'</b>. Подробная информация доступна по <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/tasks/?view=' . $TaskId . '" target="_blank">ссылке</a></p>
				<p><b>Описание:</b></p>'. $TaskComment .'<br/>
				<p>CRM система <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/" target="_blank">'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/</a></p>
				<br/>
				<p>Хорошего дня и отличного настроения!</p>
			';
			send_email($UserEmail, 'CRM система', $subject, $message);
			*/
			send_letter(get_user_id_login($TaskUser), 'Напоминание о задаче', 'Уважаемый пользователь!<br/><br/>Напоминаем вам о задаче', 'high', $TaskId, '', '', '');
			$notices[] = 'Напоминание успешно отправлено';
		} else {
			$notices_er[] = 'Напоминание не отправлено';
		}
	}
	
	function set_task_percent($taskID){
		global $baseT;
		if( isset( $_POST['SetPerTask'] ) ) {
			$dom = new DOMDocument;
			$dom->load($baseT);
			$xpath = new DOMXPath($dom);
			$taskPercent 	= $xpath->query('/tasks/task[@id="'.$taskID.'"]')->item(0)->setAttribute('percent', $_POST['NewPersent']);
			if($_POST['NewPersent'] == '100'){
				$taskStatus	= $xpath->query('/tasks/task[@id="'.$taskID.'"]')->item(0)->setAttribute('status', 'done');
			}
			$dom->save($baseT);
			$notices[] = 'Успешно изменено';
		}
		return '
			<div class="row">
				<div class="col-lg-8" style="height:auto;">
					<div class="progress_left">0%</div>
					<div id="progress"></div>
					<div class="progress_right">100%</div>
				</div>
				<div class="col-lg-4" style="text-align:right;">
					<form method="POST">
						<input type="hidden" class="hidden" name="NewPersent" value="" />
						<button type="submit" name="SetPerTask" class="btn btn-xs btn-default" style="padding:1px 7px;">Сохранить прогресс</button>
					</form>
				</div>
			</div>
		';
	}
	
?>