<?php
/**
 * ###############################################
 *
 * SWIFT Framework
 * _______________________________________________
 *
 * @author		Varun Shoor
 *
 * @package		SWIFT
 * @copyright	Copyright (c) 2001-2012, Kayako
 * @license		http://www.kayako.com/license
 * @link		http://www.kayako.com
 *
 * ###############################################
 */

/**
 * The Ticket Display View
 *
 * @author Varun Shoor
 */
class View_Ticket extends SWIFT_View {
	const TYPE_DEPARTMENT = 1;
	const TYPE_OWNER = 2;
	const TYPE_STATUS = 3;
	const TYPE_TYPE = 4;
	const TYPE_PRIORITY = 5;
	const TYPE_FLAG = 6;

	const TAB_REPLY = 1;
	const TAB_FORWARD = 2;
	const TAB_NEWTICKET_EMAIL = 3;
	const TAB_NEWTICKET_USER = 4;

	/**
	 * Constructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __construct() {
		parent::__construct();

		return true;
	}

	/**
	 * Destructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __destruct() {
		parent::__destruct();

		return true;
	}

	/**
	 * Render the Ticket
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer (Only for EDIT Mode)
	 * @param mixed $_SWIFT_UserObject The SWIFT_User Object Pointer
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderTicket(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject, $_listType, $_departmentID, $_ticketStatusID, $_ticketTypeID,
			$_ticketLimitOffset, $_variableContainer, $_activeTab = false) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		extract($_variableContainer);

		$_isGeneralTabSelected = true;
		$_isReplyTabSelected = $_isForwardTabSelected = $_isFollowUpTabSelected = $_isBillingTabSelected = $_isReleaseTabSelected = false;

		if (empty($_activeTab)) {

		} else if ($_activeTab == 'reply') {
			$_isGeneralTabSelected = false;
			$_isReplyTabSelected = true;
		} else if ($_activeTab == 'forward') {
			$_isGeneralTabSelected = false;
			$_isForwardTabSelected = true;
		} else if ($_activeTab == 'followup') {
			$_isGeneralTabSelected = false;
			$_isFollowUpTabSelected = true;
		} else if ($_activeTab == 'billing') {
			$_isGeneralTabSelected = false;
			$_isBillingTabSelected = true;
		} else if ($_activeTab == 'release') {
			$_isGeneralTabSelected = false;
			$_isReleaseTabSelected = true;
		}

		$_departmentCache = $this->Cache->Get('departmentcache');
		$_departmentMap = SWIFT_Department::GetDepartmentMap(APP_TICKETS);
		$_assignedDepartmentIDList = $_SWIFT->Staff->GetAssignedDepartments();

		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');
		$_staffCache = $this->Cache->Get('staffcache');
		$_ticketTypeCache = $this->Cache->Get('tickettypecache');
		$_ticketLinkTypeCache = $this->Cache->Get('ticketlinktypecache');
		$_slaPlanCache = $this->Cache->Get('slaplancache');
		$_emailQueueCache = $this->Cache->Get('queuecache');

		/**
		 * ---------------------------------------------
		 * BEGIN PROPERTIES
		 * ---------------------------------------------
		 */

		$_ticketURLSuffix = SWIFT::Get('ticketurlsuffix');
		$_ticketURL = SWIFT::Get('basename') . '/Tickets/Ticket/View/' . intval($_SWIFT_TicketObject->GetTicketID()) . '/' . $_ticketURLSuffix;

		// Ratings
		$_ratingContainer = SWIFT_Rating::Retrieve(array(SWIFT_Rating::TYPE_TICKETPOST), $_SWIFT->Staff, false, $_SWIFT_TicketObject->GetProperty('departmentid'));
		$_ratingIDList = array_keys($_ratingContainer);

		$_ticketReplyContents = '';
		$_userProfileImageObjectContainer = $_staffProfileImageObjectContainer = array();

		$_ticketStatusTitle = $_ticketPriorityTitle = $_ticketTypeTitle = $_ticketOwnerTitle = '';

		$_SWIFT_TicketLockObject = SWIFT_TicketLock::RetrieveOnTicket($_SWIFT_TicketObject);

		$_ticketDepartmentContainer = false;
		$_departmentTitle = $this->Language->Get('na');
		if ($_SWIFT_TicketObject->GetProperty('departmentid') == '0') {
			$_departmentTitle = $this->Language->Get('trash');
		} else if (isset($_departmentCache[$_SWIFT_TicketObject->GetProperty('departmentid')])) {
			$_departmentTitle = $_departmentCache[$_SWIFT_TicketObject->GetProperty('departmentid')]['title'];
			$_ticketDepartmentContainer = $_departmentCache[$_SWIFT_TicketObject->GetProperty('departmentid')];
		}


		$_ticketStatusContainer = false;
		if (isset($_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')])) {
			$_ticketStatusContainer = $_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')];
			$_ticketStatusTitle = $_ticketStatusContainer['title'];
		} else {
			$_ticketStatusTitle = $this->Language->Get('na');
		}


		$_ticketPriorityContainer = false;
		if (isset($_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')])) {
			$_ticketPriorityContainer = $_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')];
			$_ticketPriorityTitle = $_ticketPriorityContainer['title'];
		} else {
			$_ticketPriorityTitle = $this->Language->Get('na');
		}


		$_ticketTypeContainer = false;
		if (isset($_ticketTypeCache[$_SWIFT_TicketObject->GetProperty('tickettypeid')])) {
			$_ticketTypeContainer = $_ticketTypeCache[$_SWIFT_TicketObject->GetProperty('tickettypeid')];
			$_ticketTypeTitle = $_ticketTypeContainer['title'];
		} else {
			$_ticketTypeTitle = $this->Language->Get('na');
		}

		$_ticketOwnerContainer = false;
		if (isset($_staffCache[$_SWIFT_TicketObject->GetProperty('ownerstaffid')])) {
			$_ticketOwnerContainer = $_staffCache[$_SWIFT_TicketObject->GetProperty('ownerstaffid')];
			$_ticketOwnerTitle = $_ticketOwnerContainer['fullname'];
		} else if ($_SWIFT_TicketObject->GetProperty('ownerstaffid') == '0') {
			$_ticketOwnerTitle = $this->Language->Get('unassigned2');
		} else {
			/*
			 * BUG FIX - Mansi Wason
			 *
			 * SWIFT-1139 Name of a deleted staff member still appears in assigned tickets in the Manage Ticket List.
			 *
			 */
			$_ticketOwnerTitle = $this->Language->Get('na');
		}


		$_titleBackgroundColor = '#626262';
		if ($_ticketStatusContainer) {
			$_titleBackgroundColor = $_ticketStatusContainer['statusbgcolor'];
		}

		$_priorityBackgroundColor = false;
		if ($_ticketPriorityContainer && isset($_ticketPriorityContainer['bgcolorcode']) && !empty($_ticketPriorityContainer['bgcolorcode'])) {
			$_priorityBackgroundColor = $_ticketPriorityContainer['bgcolorcode'];
		}

		$_ticketWatchContainer = SWIFT_TicketWatcher::RetrieveOnTicket($_SWIFT_TicketObject);

		$_ticketTagContainer = SWIFT_Tag::GetTagList(SWIFT_TagLink::TYPE_TICKET, $_SWIFT_TicketObject->GetTicketID());
		$this->UserInterface->Start(get_class($this), '/Tickets/Ticket/GeneralSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterface::MODE_EDIT, false, true);

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif');

		/**
		 * ---------------------------------------------
		 * CREATE TABS
		 * ---------------------------------------------
		 */
		$_GeneralTabObject = $this->UserInterface->AddTab($this->Language->Get('tabgeneral'), 'icon_ticket.png', 'general', $_isGeneralTabSelected, false, 0);

		/*
		 * BUG FIX - Madhur Tandon
		 *
		 * SWIFT-3307: Dialog boxes need resizing with respect to new UI changes
		 *
		 * Comments: Increase the height for the UICreateWindow
		 */
		if ($_SWIFT->Staff->GetPermission('staff_tcaninsertticketnote') != '0') {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('addnote'), 'icon_note.png', "UICreateWindow('" . SWIFT::Get('basename') . '/Tickets/Ticket/AddNote/' . $_SWIFT_TicketObject->GetTicketID() . "', 'addnote', '". $_SWIFT->Language->Get('addnote') ."', '". $_SWIFT->Language->Get('loadingwindow') ."', 650, 480, true, this);", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);
		}

		if ($_SWIFT->Staff->GetPermission('staff_tcanupdateticket') != '0' && $_SWIFT_TicketObject->GetProperty('departmentid') != '0') {
			if ($_SWIFT_TicketObject->GetProperty('ownerstaffid') == $_SWIFT->Staff->GetStaffID()) {
				$this->UserInterface->Toolbar->AddButton($this->Language->Get('surrender'), 'icon_surrender.png', '/Tickets/Ticket/Surrender/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_VIEWPORT);
			} else {
				$this->UserInterface->Toolbar->AddButton($this->Language->Get('take'), 'icon_take.png', '/Tickets/Ticket/Take/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_VIEWPORT);
			}

			$this->UserInterface->Toolbar->AddButton($this->Language->Get('dispatch'), 'icon_dispatch.png', "UICreateWindow('" . SWIFT::Get('basename') . '/Tickets/Ticket/Dispatch/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . "', 'dispatch', '". $_SWIFT->Language->Get('dispatchticket') ."', '". $_SWIFT->Language->Get('loadingwindow') ."', 650, 550, true, this);", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('print'), 'icon_print.gif', 'PrintTicket(\'' . intval($_SWIFT_TicketObject->GetTicketID()) . '\');', SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);

			if ($_SWIFT->Staff->GetPermission('staff_tcansplitticket') != '0') {
				// Split button only if more than 1 posts
				if ($_SWIFT_TicketObject->GetTicketPostCount() > 1) {
					$this->UserInterface->Toolbar->AddButton($_SWIFT->Language->Get('split'), 'icon_splitticket.png', "UICreateWindow('" . SWIFT::Get('basename') . "/Tickets/Ticket/SplitTicket/" . $_SWIFT_TicketObject->GetTicketID() . "', 'dosplit', '" . $_SWIFT->Language->Get('splitticket') . "', '" . $_SWIFT->Language->Get('loadingwindow') . "', 650, 490, true, this);\"", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);
				}
			}

			if ($_SWIFT->Staff->GetPermission('staff_tcanduplicateticket') != '0') {
				$this->UserInterface->Toolbar->AddButton($_SWIFT->Language->Get('duplicate'), 'icon_copy.gif', "UICreateWindow('" . SWIFT::Get('basename') . "/Tickets/Ticket/DuplicateTicket/" . $_SWIFT_TicketObject->GetTicketID() . "', 'dosplit', '" . $_SWIFT->Language->Get('duplicateticket') . "', '" . $_SWIFT->Language->Get('loadingwindow') . "', 650, 455, true, this);\"", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);
			}

			// Already watching?
			if (isset($_ticketWatchContainer[$_SWIFT->Staff->GetStaffID()])) {
				$this->UserInterface->Toolbar->AddButton($this->Language->Get('stopwatching'), 'icon_ticketunwatch.png', '/Tickets/Ticket/UnWatch/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_VIEWPORT);
			} else {
				$this->UserInterface->Toolbar->AddButton($this->Language->Get('watch'), 'icon_ticketwatch.png', '/Tickets/Ticket/Watch/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_VIEWPORT);
			}
		}

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('flag') . ' <img src="'. SWIFT::Get('themepath') .'images/menudropgray.gif" align="absmiddle" border="0" />', 'icon_flag.png', 'UIDropDown(\'ticketflagmenu\', event, \'ticketFlag\', \'tabtoolbartable\');', SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, 'ticketFlag', '', '', false);

		$this->UserInterface->Toolbar->AddButton('');
		if ($_SWIFT->Staff->GetPermission('staff_tcanmarkasspam') != '0' && $_SWIFT_TicketObject->GetProperty('departmentid') != '0') {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('spam'), 'icon_email2spam.png', '/Tickets/Manage/Spam/' .
					$_SWIFT_TicketObject->GetTicketID(), SWIFT_UserInterfaceToolbar::LINK_CONFIRM, '', '', false);
		}

		/**
		 * BUG Fix: Parminder Singh
		 *
		 * SWIFT-1562: Issue while moving a ticket to Trash
		 *
		 * Comments: Sending ticket url suffix with link
		 */
		if ($_SWIFT->Staff->GetPermission('staff_tcantrashticket') != '0' && $_SWIFT_TicketObject->GetProperty('departmentid') != '0') {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('trash'), 'icon_delete.gif', '/Tickets/Manage/Trash/' .
					$_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_CONFIRM, '', '', false);
		} else if ($_SWIFT->Staff->GetPermission('staff_tcantrashticket') != '0' && $_SWIFT_TicketObject->GetProperty('departmentid') == '0') {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('putback'), 'icon_undo.png', '/Tickets/Manage/PutBack/' .
					$_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_CONFIRM, '', '', false);
		}

		// Begin Hook: staff_ticket_generaltoolbar
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_generaltoolbar')) ? eval($_hookCode) : false;
		// End Hook

		//$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		/*
		 * ###############################################
		 * BEGIN GENERAL TAB
		 * ###############################################
		*/
		if (isset($_ticketDepartmentContainer['parentdepartmentid']) && isset($_departmentCache[$_ticketDepartmentContainer['parentdepartmentid']])) {
			$_parentDepartmentContainer = $_departmentCache[$_ticketDepartmentContainer['parentdepartmentid']];
			$_generalDepartmentTitle = '<a class="tickettitlelink" href="' . SWIFT::Get('basename') . '/Tickets/Manage/Filter/' . $_parentDepartmentContainer['departmentid'] . '/-1/-1/' . '" viewport="1">' . htmlspecialchars($_parentDepartmentContainer['title']) . '</a>' .
					' &raquo; <a class="tickettitlelink" href="' . SWIFT::Get('basename') . '/Tickets/Manage/Filter/' . $_ticketDepartmentContainer['departmentid'] . '/-1/-1/' . '" viewport="1">' . htmlspecialchars($_departmentTitle) . '</a>';
		} else {
			$_generalDepartmentTitle = '<a class="tickettitlelink" href="' . SWIFT::Get('basename') . '/Tickets/Manage/Filter/' . $_ticketDepartmentContainer['departmentid'] . '/-1/-1/' . '" viewport="1">' . htmlspecialchars($_departmentTitle) . '</a>';
		}

		$_renderHTML = '<tr><td><div class="ticketgeneralcontainer">';

		// Begin Top Bar
		$_renderHTML .= '<div class="ticketgeneraltitlecontainer">';
		// $_renderHTML .= '<div class="ticketgeneraldepartment">' . $_generalDepartmentTitle . '</div>';
		$_renderHTML .= '<div class="ticketgeneraltitle">' . htmlspecialchars($_SWIFT_TicketObject->GetProperty('subject')) . '</div>';

		// Process the links
		$_linkContainer = $_SWIFT_TicketObject->GetLinks();
		foreach ($_linkContainer as $_ticketLinkTypeID => $_ticketObjectContainer) {
			if (!isset($_ticketLinkTypeCache[$_ticketLinkTypeID])) {
				continue;
			}

			$_ticketLinkTypeContainer = $_ticketLinkTypeCache[$_ticketLinkTypeID];
			$_renderHTML .= '<div class="ticketgenerallink">' . htmlspecialchars($_ticketLinkTypeContainer['linktypetitle']) . '</div>';

			foreach ($_ticketObjectContainer as $_linkTicketID => $_LinkedTicketObject) {
				if (!$_LinkedTicketObject instanceof SWIFT_Ticket || !$_LinkedTicketObject->GetIsClassLoaded()) {
					continue;
				}

				$_linkTitlePrefix = '';
				$_linkDepartmentTitle = $_linkTicketStatusTitle = $this->Language->Get('na');

				if (!$_LinkedTicketObject->CanAccess($_SWIFT->Staff)) {
					$_linkTitlePrefix = '<img src="' . SWIFT::Get('themepathimages') . 'icon_lock.gif" align="absmiddle" border="0" /> ';
				}

				if ($_LinkedTicketObject->GetProperty('departmentid') == '0') {
					$_linkDepartmentTitle = $this->Language->Get('trash');
				} else if (isset($_departmentCache[$_LinkedTicketObject->GetProperty('departmentid')])) {
					$_linkDepartmentTitle = htmlspecialchars($_departmentCache[$_LinkedTicketObject->GetProperty('departmentid')]['title']);
				}

				if (isset($_ticketStatusCache[$_LinkedTicketObject->GetProperty('ticketstatusid')])) {
					$_linkTicketStatusTitle = htmlspecialchars($_ticketStatusCache[$_LinkedTicketObject->GetProperty('ticketstatusid')]['title']);
				}

				$_renderHTML .= '<div class="ticketgenerallinkticket">' . $_linkTitlePrefix

					. '<b><a href="' . SWIFT::Get('basename') . '/Tickets/Ticket/View/' . $_LinkedTicketObject->GetTicketDisplayID() . '" target="_blank">#' . $_LinkedTicketObject->GetTicketDisplayID() . '</a>: </b>'
					. htmlspecialchars($_LinkedTicketObject->GetProperty('subject')) . ' (' . sprintf($this->Language->Get('ticketlinkinfo'), $_linkDepartmentTitle, $_linkTicketStatusTitle) . ')'
					. '<span style="margin-left:10px;"><a href="' . SWIFT::Get('basename') . '/Tickets/Ticket/Unlink/' . $_SWIFT_TicketObject->GetProperty('ticketid') . '/' . $_LinkedTicketObject->GetTicketDisplayID() . '/' . $_ticketLinkTypeID . '" onclick="return confirm(&#39;Are you sure you wish to continue?&#39;)">' . $this->Language->Get('ticketunlink') . '</a></span>'
					. '</div>';
			}
		}
		$_renderHTML .= '</div>';

		$_propertySeperatorHTML = '&nbsp;&nbsp;&nbsp;&nbsp;';


		/**
		 * ---------------------------------------------
		 * BEGIN ESCALATION PATH RENDERING
		 * ---------------------------------------------
		 */
		$_escalationPathDividerHTML = '<div class="ticketescalationpathpropertiesdivider"><img src="' . SWIFT::Get('themepathimages') . 'ticketpropertiesdivider2.png" align="middle" border="0" /></div>';

		if ($_SWIFT_TicketObject->GetProperty('isescalated') == '1') {
			$_escalationPathContainer = SWIFT_EscalationPath::RetrieveOnTicket($_SWIFT_TicketObject->GetTicketID());

			$_escalationPathCount = count($_escalationPathContainer);
			$_index = 1;

			$_escalationHistoryHTML = '';
			if ($_escalationPathCount > 1) {
				$_escalationHistoryHTML = '<div>' . sprintf($this->Language->Get('tescalationhistory'), $_escalationPathCount-1) . '</div>';
			}

			foreach ($_escalationPathContainer as $_escalationPath) {
				if ($_index != $_escalationPathCount) {
					$_renderHTML .= '<div style="display: none;" class="escalationpathhistory">';
				}

				$_renderHTML .= '<div class="ticketbillinginfocontainer">';
				if ($_index == $_escalationPathCount) {
					$_renderHTML .= '<span style="float: right;"><a href="javascript: void(0);" onclick="javascript: ShowEscalationPathHistory();" class="menulink">' . $_escalationHistoryHTML . '</a></span>';
				}

				$_renderHTML .= '<img src="' . SWIFT::Get('themepathimages') . 'icon_escalation2.png' . '" align="absmiddle" border="0" /> ';
				$_renderHTML .= $this->Language->Get('tepdate') . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_escalationPath['dateline']) . $_propertySeperatorHTML;
				$_renderHTML .= $this->Language->Get('tepslaplan') . htmlspecialchars($_escalationPath['slaplantitle']) . $_propertySeperatorHTML;
				$_renderHTML .= $this->Language->Get('tepescalationrule') . htmlspecialchars($_escalationPath['escalationruletitle']) . $_propertySeperatorHTML;
				$_renderHTML .= '</div>';


				$_escalationPathTitleBackgroundColor = '#626262';
				if (isset($_ticketStatusCache[$_escalationPath['ticketstatusid']])) {
					$_escalationPathTitleBackgroundColor = $_ticketStatusCache[$_escalationPath['ticketstatusid']]['statusbgcolor'];
				}

				$_renderHTML .= '<div class="ticketescalationpathproperties" style="background-color: ' . htmlspecialchars($_escalationPathTitleBackgroundColor) . ';">';

				// Departments
				$_renderHTML .= '<div class="ticketescalationpathpropertiesobject"><div class="ticketescalationpathpropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div><div class="ticketescalationpathpropertiescontent">' . StripName(htmlspecialchars($_escalationPath['departmenttitle']), 16) . '</div></div>';
				$_renderHTML .= $_escalationPathDividerHTML;

				// Owner
				$_renderHTML .= '<div class="ticketescalationpathpropertiesobject"><div class="ticketescalationpathpropertiestitle">' . $this->Language->Get('proptitleowner') . '</div><div class="ticketescalationpathpropertiescontent">' . StripName(htmlspecialchars($_escalationPath['ownerstaffname']), 16) . '</div></div>';
				$_renderHTML .= $_escalationPathDividerHTML;

				// Type
				$_renderHTML .= '<div class="ticketescalationpathpropertiesobject"><div class="ticketescalationpathpropertiestitle">' . $this->Language->Get('proptitletype') . '</div><div class="ticketescalationpathpropertiescontent">' . StripName(htmlspecialchars($_escalationPath['tickettypetitle']), 16) . '</div></div>';
				$_renderHTML .= $_escalationPathDividerHTML;

				// Status
				$_renderHTML .= '<div class="ticketescalationpathpropertiesobject"><div class="ticketescalationpathpropertiestitle">' . $this->Language->Get('proptitlestatus') . '</div><div class="ticketescalationpathpropertiescontent">' . StripName(htmlspecialchars($_escalationPath['ticketstatustitle']), 16) . '</div></div>';
				$_renderHTML .= $_escalationPathDividerHTML;

				// Priority
				$_escalationPathPriorityBackgroundColor = false;
				if (isset($_ticketPriorityCache[$_escalationPath['priorityid']])) {
					$_escalationPathPriorityBackgroundColor = $_ticketPriorityCache[$_escalationPath['priorityid']]['bgcolorcode'];
				}
				$_renderHTML .= '<div class="ticketescalationpathpropertiesobject"' . IIF(!empty($_escalationPathPriorityBackgroundColor), ' style="background-color: ' . htmlspecialchars($_escalationPathPriorityBackgroundColor) . ';"') . '><div class="ticketescalationpathpropertiestitle">' . $this->Language->Get('proptitlepriority') . '</div><div class="ticketescalationpathpropertiescontent">' . StripName(htmlspecialchars($_escalationPath['prioritytitle']), 16) . '</div></div>';
				$_renderHTML .= $_escalationPathDividerHTML;

				$_renderHTML .= '</div>';

				$_renderHTML .= '<div class="ticketescalationpatharrow"></div>';

				if ($_index != $_escalationPathCount) {
					$_renderHTML .= '</div>';
				}

				$_index++;
			}
		}






		/**
		 * ---------------------------------------------
		 * END ESCALATION PATH RENDERING
		 * ---------------------------------------------
		 */




		// Calculate background color for the properties band
		$_infoCSSStyle = '';
		if ($_SWIFT_TicketObject->GetProperty('duetime') != '0') {
			if ($_SWIFT_TicketObject->GetProperty('duetime') < DATENOW) {
				$_infoCSSStyle = 'background-color: ' . htmlspecialchars($_SWIFT->Settings->Get('t_overduecolor')) . ' !important;';
			}
		}

		if ($_SWIFT_TicketObject->GetProperty('resolutionduedateline') != '0') {
			if ($_SWIFT_TicketObject->GetProperty('resolutionduedateline') < DATENOW) {
				$_infoCSSStyle = 'background-color: ' . htmlspecialchars($_SWIFT->Settings->Get('t_overduecolor')) . ' !important;';
			}
		}

		// Render the properties band
		$_renderHTML .= '<div class="ticketgeneralinfocontainer" style="' . $_infoCSSStyle . '">';
//		$_renderHTML .= $this->Language->Get('tinfoticketid') . $_SWIFT_TicketObject->GetTicketDisplayID() . $_propertySeperatorHTML;

		if ($_SWIFT_TicketObject->GetProperty('duetime') != '0') {
			if ($_SWIFT_TicketObject->GetProperty('duetime') < DATENOW) {
				$_dueTimeline = '<font color="red"><b>' . $this->Language->Get('overdue') . '</b></font>';
				$_fieldContainer[':'] = 'background-color: ' . htmlspecialchars($_SWIFT->Settings->Get('t_overduecolor')) . ';';
			} else {
				$_dueTimeline = SWIFT_Date::ColorTime(($_SWIFT_TicketObject->GetProperty('duetime')-DATENOW), true);
			}
			$_renderHTML .= '<span id="labeldue">' . $this->Language->Get('tinfodue') . $_dueTimeline . '</span>' . $_propertySeperatorHTML;
		}

		if ($_SWIFT_TicketObject->GetProperty('resolutionduedateline') != '0') {
			if ($_SWIFT_TicketObject->GetProperty('resolutionduedateline') < DATENOW) {
				$_dueTimeline = '<font color="red"><b>' . $this->Language->Get('overdue') . '</b></font>';
			} else {
				$_dueTimeline = SWIFT_Date::ColorTime(($_SWIFT_TicketObject->GetProperty('resolutionduedateline')-DATENOW), true);
			}
			$_renderHTML .= '<span id="labelresolutiondue">' . $this->Language->Get('tinforesolutiondue') . $_dueTimeline . '</span>' . $_propertySeperatorHTML;
		}

		/*
		 * BUG FIX - Abhishek Mittal
		 *
		 * SWIFT-3913 SLA plan selected for a User Organization is overriding the SLA plan selected for a User account.
		 * SWIFT-2696 Not able to change the SLA plan on the ticket in Staff CP under Edit tab, if there is a SLA already specified in respective user account.
		 */
		if ($_SWIFT_TicketObject->Get('ticketslaplanid') != '0' && isset($_slaPlanCache[$_SWIFT_TicketObject->Get('ticketslaplanid')])) {
			$_renderHTML .= $this->Language->Get('tinfosla') . htmlspecialchars($_slaPlanCache[$_SWIFT_TicketObject->Get('ticketslaplanid')]['title']) . $_propertySeperatorHTML;
		} else if ($_SWIFT_TicketObject->Get('slaplanid') != '0' && isset($_slaPlanCache[$_SWIFT_TicketObject->Get('slaplanid')])) {
			$_renderHTML .= $this->Language->Get('tinfosla') . htmlspecialchars($_slaPlanCache[$_SWIFT_TicketObject->Get('slaplanid')]['title']) . $_propertySeperatorHTML;
		}

		$_renderHTML .= $this->Language->Get('tinfocreated') . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketObject->Get('dateline')) . $_propertySeperatorHTML;
		$_renderHTML .= $this->Language->Get('tinfoupdated') . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketObject->Get('lastactivity')) . $_propertySeperatorHTML;

		$_renderHTML .= '</div>';

		// Ticket Lock Processing
		$_lockThreshold = DATENOW -  $_SWIFT->Settings->Get('t_locktimeout');
		if ($_SWIFT_TicketLockObject instanceof SWIFT_TicketLock && $_SWIFT_TicketLockObject->GetIsClassLoaded() &&
				$_SWIFT_TicketLockObject->GetProperty('dateline') > $_lockThreshold &&
				$_SWIFT_TicketLockObject->GetProperty('staffid') != $_SWIFT->Staff->GetStaffID() &&
				isset($_staffCache[$_SWIFT_TicketLockObject->GetProperty('staffid')])) {
			$_renderHTML .= '<div class="ticketlockinfocontainer">';
			$_renderHTML .= '<img src="' . SWIFT::Get('themepathimages') . 'icon_lock.gif' . '" align="absmiddle" border="0" /> ' . sprintf($this->Language->Get('tlockinfo'), htmlspecialchars($_staffCache[$_SWIFT_TicketLockObject->GetProperty('staffid')]['fullname']), SWIFT_Date::ColorTime(DATENOW-$_SWIFT_TicketLockObject->GetProperty('dateline')));
			$_renderHTML .= '</div>';
		} else {
			// Create the ticket lock
			SWIFT_TicketLock::Create($_SWIFT_TicketObject, $_SWIFT->Staff);
		}

		// Billing Processing
		if ($_SWIFT_TicketObject->GetProperty('hasbilling') == '1' && $_SWIFT->Staff->GetPermission('staff_tcanviewbilling') != '0') {
			$_totalTimeSpent = $_SWIFT_TicketObject->GetProperty('timeworked');
			$_totalTimeBillable = $_SWIFT_TicketObject->GetProperty('timebilled');
			$_renderHTML .= '<div class="ticketbillinginfocontainer">';
			$_renderHTML .= '<img src="' . SWIFT::Get('themepathimages') . 'icon_clock.png' . '" align="absmiddle" border="0" /> ' .
					'<b>' . $this->Language->Get('billtotalworked') . '</b> ' . SWIFT_Date::ColorTime($_totalTimeSpent, false, true) .
					'&nbsp;&nbsp;&nbsp;&nbsp;' .
					'<b>' . $this->Language->Get('billtotalbillable') . '</b> ' . SWIFT_Date::ColorTime($_totalTimeBillable, false, true);
			$_renderHTML .= '</div>';
		}

		$_renderHTML .= '</div></td></tr>';
		$_GeneralTabObject->RowHTML($_renderHTML);

		// Begin Properties
		$_dividerHTML = '<div class="ticketgeneralpropertiesdivider"><img src="' . SWIFT::Get('themepathimages') . 'ticketpropertiesdivider.png" align="middle" border="0" /></div>';
		$_renderHTML = '<tr><td><div class="ticketgeneralcontainer">';
		$_renderHTML .= '<div class="ticketgeneralproperties" id="generalticketproperties" style="background-color: ' . htmlspecialchars($_titleBackgroundColor) . ';">';

		// Departments
		$_departmentSelectHTML = '<div class="ticketgeneralpropertiesselect"><select id="general_departmentid" name="gendepartmentid" style="width: 160px;" class="swiftselect" onchange="javascript: UpdateTicketStatusDiv(this, \'genticketstatusid\', false, false, \'generalticketproperties\'); UpdateTicketTypeDiv(this, \'gentickettypeid\', false, false); UpdateTicketOwnerDiv(this, \'genownerstaffid\', false, false);">';
		$_departmentSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_DEPARTMENT);
		$_departmentSelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketgeneralpropertiesobject"><div class="ticketgeneralpropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div><div class="ticketgeneralpropertiescontent">' . StripName(htmlspecialchars($_departmentTitle), 16) . '</div>' . $_departmentSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Owner
		$_ownerSelectHTML = '<div class="ticketgeneralpropertiesselect"><div id="genownerstaffid_container"><select id="selectgenownerstaffid" style="width: 160px;" name="genownerstaffid" class="swiftselect">';
		$_ownerSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_OWNER);
		$_ownerSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketgeneralpropertiesobject"><div class="ticketgeneralpropertiestitle">' . $this->Language->Get('proptitleowner') . '</div><div class="ticketgeneralpropertiescontent">' . StripName(htmlspecialchars($_ticketOwnerTitle), 16) . '</div>' . $_ownerSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Type
		$_ticketTypeSelectHTML = '<div class="ticketgeneralpropertiesselect"><div id="gentickettypeid_container"><select id="selectgentickettypeid" style="width: 160px;" name="gentickettypeid" class="swiftselect">';
		$_ticketTypeSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_TYPE);
		$_ticketTypeSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketgeneralpropertiesobject"><div class="ticketgeneralpropertiestitle">' . $this->Language->Get('proptitletype') . '</div><div class="ticketgeneralpropertiescontent">' . StripName(htmlspecialchars($_ticketTypeTitle), 16) . '</div>' . $_ticketTypeSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Status
		$_ticketStatusSelectHTML = '<div class="ticketgeneralpropertiesselect"><div id="genticketstatusid_container"><select id="selectgenticketstatusid" style="width: 160px;" name="genticketstatusid" onchange="javascript: ResetStatusParentColor(this, \'generalticketproperties\');" class="swiftselect">';
		$_ticketStatusSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_STATUS);
		$_ticketStatusSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketgeneralpropertiesobject"><div class="ticketgeneralpropertiestitle">' . $this->Language->Get('proptitlestatus') . '</div><div class="ticketgeneralpropertiescontent">' . StripName(htmlspecialchars($_ticketStatusTitle), 16) . '</div>' . $_ticketStatusSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Priority
		$_ticketPrioritySelectHTML = '<div class="ticketgeneralpropertiesselect"><select id="general_ticketpriorityid" name="genticketpriorityid" style="width: 160px;" class="swiftselect" onchange="javascript: ResetPriorityParentColor(this, \'generalpriorityproperties\');">';
		$_ticketPrioritySelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_PRIORITY);
		$_ticketPrioritySelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketgeneralpropertiesobject" id="generalpriorityproperties" ' . IIF(!empty($_priorityBackgroundColor), ' style="background-color: ' . htmlspecialchars($_priorityBackgroundColor) . ';"') . '><div class="ticketgeneralpropertiestitle">' . $this->Language->Get('proptitlepriority') . '</div><div class="ticketgeneralpropertiescontent">' . StripName(htmlspecialchars($_ticketPriorityTitle), 12) . '</div>' . $_ticketPrioritySelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Ticket Flag
		$_flagHTML = $_flagStyle = '';
		$_SWIFT_TicketFlagObject = new SWIFT_TicketFlag();
		$_flagList = $_SWIFT_TicketFlagObject->GetFlagContainer();
		if (isset($_flagList[$_SWIFT_TicketObject->GetProperty('flagtype')])) {
			$_flagHTML = '<a href="javascript: void(0);" onclick="javascript: ToggleFlag(\'' .
					$_SWIFT_TicketObject->GetTicketID() . '\', \'' . $_flagList[SWIFT_TicketFlag::FLAG_RED][1] . '\', \'' .
					$_flagList[SWIFT_TicketFlag::FLAG_RED][2] . '\', \'icon_flagblankwhite.gif\');"><img id="ticketflagimg_' . $_SWIFT_TicketObject->GetTicketID() .
					'" src="' . SWIFT::Get('themepathimages') . $_flagList[$_SWIFT_TicketObject->GetProperty('flagtype')][2] .
					'" align="absmiddle" border="0" /></a>';
			$_flagStyle = 'background-color: ' . $_flagList[$_SWIFT_TicketObject->GetProperty('flagtype')][1] . ' !important;';
		} else {
			$_flagHTML = '<a href="javascript: void(0);" onclick="javascript: ToggleFlag(\'' .
					$_SWIFT_TicketObject->GetTicketID() . '\', \'' . $_flagList[SWIFT_TicketFlag::FLAG_RED][1] . '\', \'' .
					$_flagList[SWIFT_TicketFlag::FLAG_RED][2] . '\', \'icon_flagblankwhite.gif\');"><img id="ticketflagimg_' . $_SWIFT_TicketObject->GetTicketID() .
					'" src="' . SWIFT::Get('themepathimages') . 'icon_flagblankwhite.gif' .
					'" align="absmiddle" border="0" /></a>';
		}
		$_renderHTML .= '<div class="ticketgeneralpropertiesflag" style="' . $_flagStyle . '">' . $_flagHTML . '</div>';
		$_renderHTML .= '</div>';

		$_renderHTML .= '</div></td></tr>';

		$_GeneralTabObject->RowHTML($_renderHTML);

		if ($_SWIFT->Staff->GetPermission('staff_canupdatetags') != '0') {
			$_GeneralTabObject->TextMultipleAutoComplete('tags', false, false, '/Base/Tags/QuickSearch', $_ticketTagContainer, 'icon_taginput.png', 'gridrow2', true, 2, false, true);
		}

		$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_STATIC, SWIFT_UserInterface::MODE_INSERT,
				array(SWIFT_CustomFieldGroup::GROUP_STAFFTICKET, SWIFT_CustomFieldGroup::GROUP_USERTICKET, SWIFT_CustomFieldGroup::GROUP_STAFFUSERTICKET), $_GeneralTabObject,
				$_SWIFT_TicketObject->GetTicketID(), $_SWIFT_TicketObject->GetProperty('departmentid'), true);

		// Check the ticket merge log, if there is any old custom field records
		$_mergeTicketIDList = SWIFT_TicketMergeLog::GetMergedTicketIDFromTicketID($_SWIFT_TicketObject->GetTicketID());
		if (_is_array($_mergeTicketIDList)) {
			foreach ($_mergeTicketIDList as $_mergedTicketID) {
				$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_STATIC, SWIFT_UserInterface::MODE_INSERT, array(SWIFT_CustomFieldGroup::GROUP_STAFFTICKET, SWIFT_CustomFieldGroup::GROUP_USERTICKET, SWIFT_CustomFieldGroup::GROUP_STAFFUSERTICKET), $_GeneralTabObject, $_mergedTicketID, $_SWIFT_TicketObject->GetProperty('departmentid'), true);
			}
		}

		if ($_SWIFT_TicketObject->GetProperty('userid') != '0') {
			$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_STATIC, SWIFT_UserInterface::MODE_INSERT, array(SWIFT_CustomFieldGroup::GROUP_USER), $_GeneralTabObject, $_SWIFT_TicketObject->GetProperty('userid'));

			$_SWIFT_UserOrganizationObject = $_SWIFT_TicketObject->GetUserOrganizationObject();
			if ($_SWIFT_UserOrganizationObject instanceof SWIFT_UserOrganization && $_SWIFT_UserOrganizationObject->GetIsClassLoaded()) {
				$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_STATIC, SWIFT_UserInterface::MODE_INSERT, array(SWIFT_CustomFieldGroup::GROUP_USERORGANIZATION), $_GeneralTabObject, $_SWIFT_UserOrganizationObject->GetUserOrganizationID());
			}
		}

		$_notesHTML = '';
		if ($_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
			$_notesHTML = $this->RenderNotes($_SWIFT_TicketObject, $_SWIFT_UserObject);
		} else {
			$_notesHTML = $this->RenderNotes($_SWIFT_TicketObject);
		}

		if (!empty($_notesHTML)) {
			$_GeneralTabObject->RowHTML('<tr class="gridrow3" id="ticketnotescontainerdivholder"><td colspan="2" align="left" valign="top class="gridrow3"><div id="ticketnotescontainerdiv">' . $_notesHTML . '</div></td></tr>');
		} else {
			$_GeneralTabObject->RowHTML('<tr class="gridrow3" style="display: none;" id="ticketnotescontainerdivholder"><td colspan="2" align="left" valign="top class="gridrow3"><div id="ticketnotescontainerdiv"></div></td></tr>');
		}

		// Begin Hook: staff_ticket_generaltab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_generaltab')) ? eval($_hookCode) : false;
		// End Hook

		/*
		 * ###############################################
		 * END GENERAL TAB
		 * ###############################################
		*/


















		/*
		 * ###############################################
		 * BEGIN REPLY TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetDepartmentPermission($_SWIFT_TicketObject->GetProperty('departmentid'), 'd_t_canreply') != '0' && $_SWIFT->Staff->GetPermission('staff_tcanreply') != '0') {
			$_ReplyTabObject = $this->UserInterface->AddTab($this->Language->Get('tabreply'), 'icon_ticketreply.png', 'reply', $_isReplyTabSelected, false, 0);
			$_ReplyTabObject->EventQueue('show', '$("#replycontents").focus(); StartTicketReplyLockTimer(\'' . $_SWIFT_TicketObject->GetTicketID() . '\');');
			$_ReplyTabObject->LoadToolbar();
			$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('dispatchsend'), 'icon_check.gif', '/Tickets/Ticket/ReplySubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);

			if ($_SWIFT->Staff->GetPermission('staff_tcansaveasdraft') != '0') {
				$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('dispatchsaveasdraft'), 'icon_savereload.gif', '/Tickets/Ticket/SaveAsDraft/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);
			}

			if ($_SWIFT->Staff->GetPermission('staff_tcaninsertticketnote') != '0') {
				$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('addnote'), 'icon_note.png', "\$('#replynotes').toggle(function(){ \$('#replyticketnotes').focus(); });", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'replynotes');
			}

			$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('dispatchattachfile'), 'icon_file.gif', "\$('#replyattachments').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'replyattachments');

			if ($_SWIFT->Staff->GetPermission('staff_tcanfollowup') != '0') {
				$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('followup'), 'icon_followup.png', "\$('#replyfollowup').toggle(); LoadFollowUp('replyfollowup', '" . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/re/' . substr(BuildHash(), 6) . "');", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'replyfollowup');
			}

			$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('options'), 'icon_settings2.gif', "\$('#replyoptions').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'replyoptions');
			$_ReplyTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
					SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

			// Begin Hook: staff_ticket_replytabtoolbar
			unset($_hookCode);
			($_hookCode = SWIFT_Hook::Execute('staff_ticket_replytabtoolbar')) ? eval($_hookCode) : false;
			// End Hook

			$this->RenderDispatchTab(self::TAB_REPLY, $_ReplyTabObject, $_SWIFT_TicketObject, $_SWIFT_UserObject, $_ticketWatchContainer);
		}

		/*
		 * ###############################################
		 * END REPLY TAB
		 * ###############################################
		*/


















		/*
		 * ###############################################
		 * BEGIN FORWARD TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetPermission('staff_tcanforward') != '0' && $_SWIFT->Staff->GetDepartmentPermission($_SWIFT_TicketObject->GetProperty('departmentid'), 'd_t_canforward') != '0' && $_SWIFT->Staff->GetPermission('staff_tcanforward') != '0') {
			$_ForwardTabObject = $this->UserInterface->AddTab($this->Language->Get('tabforward'), 'icon_ticketforward.png', 'forward', $_isForwardTabSelected, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/Forward/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/' . substr(BuildHash(), 6));
			$_ForwardTabObject->EventQueue('show', '$("#forwardcontents").focus();');
		}

		/*
		 * ###############################################
		 * END FORWARD TAB
		 * ###############################################
		*/


















		/*
		 * ###############################################
		 * BEGIN FOLLOW-UP TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetPermission('staff_tcanfollowup') != '0' && $_SWIFT->Staff->GetDepartmentPermission($_SWIFT_TicketObject->GetProperty('departmentid'), 'd_t_canfollowup') != '0') {
			$_followUpCounterHTML = '';
			$_followUpCount = $_SWIFT_TicketObject->GetProperty('followupcount');
			if ($_followUpCount > 0) {
				$_followUpCount = number_format($_followUpCount, 0);
			}
			$_FollowUpTabObject = $this->UserInterface->AddTab($this->Language->Get('tabfollowup'), 'icon_ticketfollowup.png', 'followup', $_isFollowUpTabSelected, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/FollowUp/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/0/' . substr(BuildHash(), 6));
			$_FollowUpTabObject->SetTabCounter($_followUpCount);
			$_FollowUpTabObject->EventQueue('show', '$("#fufollowupvalue").focus();');
		}

		/*
		 * ###############################################
		 * END FOLLOW-UP TAB
		 * ###############################################
		*/

















		/*
		 * ###############################################
		 * BEGIN BILLING TAB
		 * ###############################################
		*/
		if ($_SWIFT->Staff->GetPermission('staff_tcanviewbilling') != '0' && $_SWIFT->Staff->GetDepartmentPermission($_SWIFT_TicketObject->GetProperty('departmentid'), 'd_t_canbilling') != '0') {
			$_timeTrackCounterHTML = '';
			$_timeTrackCount = 0;
			if ($_SWIFT_TicketObject->GetProperty('hasbilling') == '1') {
				$_timeTrackCount = $_SWIFT_TicketObject->GetTimeTrackCount();
			}
			if ($_timeTrackCount > 0) {
				$_timeTrackCount = number_format($_timeTrackCount, 0);
			}

			$_BillingTabObject = $this->UserInterface->AddTab($this->Language->Get('tabbilling') . $_timeTrackCounterHTML, 'icon_ticketbilling.png', 'billing', $_isBillingTabSelected, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/Billing/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/' . substr(BuildHash(), 6));
			$_BillingTabObject->SetTabCounter($_timeTrackCount);
			$_BillingTabObject->EventQueue('show', '$("#billingtimeworked").focus();ClearFunctionQueue();');
		}

		/*
		 * ###############################################
		 * END BILLING TAB
		 * ###############################################
		*/

















		/*
		 * ###############################################
		 * BEGIN RELEASE TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetPermission('staff_tcanrelease') != '0') {
			$_ReleaseTabObject = $this->UserInterface->AddTab($this->Language->Get('tabrelease'), 'icon_ticketrelease.png', 'release', $_isReleaseTabSelected, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/Release/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/' . substr(BuildHash(), 6));
		}

		/*
		 * ###############################################
		 * END RELEASE TAB
		 * ###############################################
		*/




















		/*
		 * ###############################################
		 * BEGIN CHATS TAB
		 * ###############################################
		*/

		if (SWIFT_App::IsInstalled(APP_LIVECHAT)) {
			SWIFT_Loader::LoadModel('Chat:Chat', APP_LIVECHAT);

			$_chatsCounterHTML = '';

			$_chatsCount = 0;
			if ($_SWIFT_TicketObject->GetProperty('userid') != '0') {
				$_chatsCount = SWIFT_Chat::GetHistoryCount($_SWIFT_TicketObject->GetProperty('userid'), IIF($_SWIFT_TicketObject->GetProperty('replyto') != '', $_SWIFT_TicketObject->GetProperty('replyto'), $_SWIFT_TicketObject->GetProperty('email')));
			}
			if ($_chatsCount > 0) {
				$_chatsCount = number_format($_chatsCount, 0);
			}

			$_historyArguments = 'userid=' . intval($_SWIFT_TicketObject->GetProperty('userid')) . '&email=' . urlencode(IIF($_SWIFT_TicketObject->GetProperty('replyto') != '', $_SWIFT_TicketObject->GetProperty('replyto'), $_SWIFT_TicketObject->GetProperty('email')));
			$_ChatsTabObject = $this->UserInterface->AddTab($this->Language->Get('tabchats') . $_chatsCounterHTML, 'icon_chatballoon.png', 'chats', false, false, 0, SWIFT::Get('basename') . '/LiveChat/ChatHistory/History/' . base64_encode($_historyArguments));
			$_ChatsTabObject->SetTabCounter($_chatsCount);
		}

		/*
		 * ###############################################
		 * END CHATS TAB
		 * ###############################################
		*/











		/*
		 * ###############################################
		 * BEGIN CALLS TAB
		 * ###############################################
		*/
		if (SWIFT_App::IsInstalled(APP_LIVECHAT)) {

			$_callHistoryCounterHTML = '';
			SWIFT_Loader::LoadModel('Call:Call', APP_LIVECHAT);
			$_callHistoryCount = SWIFT_Call::GetHistoryCountOnUser($_SWIFT_UserObject, $_SWIFT_TicketObject->GetProperty('email'));
			if ($_callHistoryCount > 0) {
				$_callHistoryCount = number_format($_callHistoryCount, 0);
			}

			$_userIDCall = -1;
			if ($_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
				$_userIDCall = $_SWIFT_UserObject->GetUserID();
			}

			$_callEmailList = '&email[]=' . urlencode($_SWIFT_TicketObject->GetProperty('email'));

			$_CallsTabObject = $this->UserInterface->AddTab($this->Language->Get('tabcalls') . $_callHistoryCounterHTML, 'icon_phone.gif', 'calls', false, false, 0, SWIFT::Get('basename') . '/LiveChat/Call/History/' . base64_encode('userid=' . intval($_userIDCall) . $_callEmailList));
			$_CallsTabObject->SetTabCounter($_callHistoryCount);
		}

		/*
		 * ###############################################
		 * END CALLS TAB
		 * ###############################################
		*/




















		/*
		 * ###############################################
		 * BEGIN HISTORY TAB
		 * ###############################################
		*/

		$_historyCounterHTML = '';
		$_historyCount = $_SWIFT_TicketObject->GetHistoryCount();
		if ($_historyCount > 0) {
			$_historyCount = number_format($_historyCount, 0);
		}
		$_HistoryTabObject = $this->UserInterface->AddTab($this->Language->Get('tabhistory') . $_historyCounterHTML, 'icon_spacer.gif', 'history', false, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/History/' . $_SWIFT_TicketObject->GetTicketID() . '/' . substr(BuildHash(), 6));
		$_HistoryTabObject->SetTabCounter($_historyCount);
		/*
		 * ###############################################
		 * END HISTORY TAB
		 * ###############################################
		*/


		/*
		 * ###############################################
		 * BEGIN RECURRENCE TAB
		 * ###############################################
		 */

		// Check permission
		if ($_SWIFT->Staff->GetPermission('staff_tcanviewrecurrence') != '0') {
			$_TicketRecurrence = SWIFT_TicketRecurrence::RetrieveOnTicket($_SWIFT_TicketObject);

			// Search from the parent ticket ID, if the ticket is created using recurrence
			if (!$_TicketRecurrence instanceof SWIFT_TicketRecurrence && $_SWIFT_TicketObject->Get('recurrencefromticketid') != '0') {
				$_recurrenceParentTicketID = $_SWIFT_TicketObject->Get('recurrencefromticketid');
				$_RecurrenceParentTicket   = SWIFT_Ticket::GetObjectOnID($_recurrenceParentTicketID);

				if ($_RecurrenceParentTicket instanceof SWIFT_Ticket) {
					$_TicketRecurrence = SWIFT_TicketRecurrence::RetrieveOnTicket($_RecurrenceParentTicket);
				}
			}

			if ($_TicketRecurrence instanceof SWIFT_TicketRecurrence) {
				$_RecurrenceTab = $this->UserInterface->AddTab($this->Language->Get('tabrecurrence'), 'icon_spacer.gif', 'recurrence', false, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/Recurrence/' . $_SWIFT_TicketObject->GetID() . '/' . $_TicketRecurrence->GetTicketRecurrenceID() . '/' . substr(BuildHash(), 6));
			}
		}

		/*
		 * ###############################################
		 * END RECURRENCE TAB
		 * ###############################################
		 */


		/*
		 * ###############################################
		 * BEGIN AUDITLOG TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetPermission('staff_tcanviewauditlog') != '0') {
			$_AuditLogTabObject = $this->UserInterface->AddTab($this->Language->Get('tabauditlog'), 'icon_spacer.gif', 'auditlog', false, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/AuditLog/' . $_SWIFT_TicketObject->GetTicketID() . '/' . substr(BuildHash(), 6));
		}

		/*
		 * ###############################################
		 * END AUDITLOG TAB
		 * ###############################################
		*/


















		/*
		 * ###############################################
		 * BEGIN EDIT TAB
		 * ###############################################
		*/

		if ($_SWIFT->Staff->GetPermission('staff_tcanupdateticket') != '0') {
			$_EditTabObject = $this->UserInterface->AddTab($this->Language->Get('tabedit'), 'icon_spacer.gif', 'edit', false, false, 0, SWIFT::Get('basename') . '/Tickets/Ticket/Edit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . substr(BuildHash(), 6));
		}

		/*
		 * ###############################################
		 * END EDIT TAB
		 * ###############################################
		*/



		// Begin Hook: staff_tickets_viewtickettab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_tickets_viewtickettab')) ? eval($_hookCode) : false;
		// End Hook

		if (SWIFT_App::IsInstalled(APP_BACKSYNC)) {
			SWIFT_Loader::LoadLibrary('Order:OrderHistory', APP_BACKSYNC);
			$History = new SWIFT_OrderHistory();
			$History->GetOnTicket($_SWIFT_TicketObject->Get('ticketid'));
		}

		/*
		 * ###############################################
		 * BEGIN TICKET POST RENDERING
		 * ###############################################
		*/

		$_ticketPostHTML = '<div class="ticketpostsholder">';

		// Create the pagination
		$_ticketPostPaginationLimit = $_ticketPostLimitCount;
		if ($_ticketPostLimitCount == false) {
			$_ticketPostPaginationLimit = $_ticketPostCount;
		}

		$_paginationHTML = '<div class="ticketpostpaginationtoolbar"><div style="float: right;"><table border="0" cellpadding="0" cellspacing="1"><tr><td class="gridnavpage"><a href="' . SWIFT::Get('basename') . '/Tickets/Ticket/Jump/previous/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '" viewport="1">' . $this->Language->Get('tnavprevticket') . '</a></td><td class="gridnavpage"><a href="' . SWIFT::Get('basename') . '/Tickets/Ticket/Jump/next/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '" viewport="1">' . $this->Language->Get('tnavnextticket') . '</a></td></tr></table></div>'.SWIFT_CRLF;
		$_paginationHTML .= '<table border="0" cellpadding="0" cellspacing="1"><tr>' .
				SWIFT_UserInterfaceGrid::RenderPagination('javascript: loadViewportData("' . $_ticketURL . '/', $_ticketPostCount, $_ticketPostPaginationLimit, $_ticketPostOffset, '5', 'pageoftotal', true, false, true, true, true) .'</tr></table>';
		$_paginationHTML .= '</div>';

		$_ticketPostHTML .= $_paginationHTML;

		$_userProfileImageObjectContainer = SWIFT_UserProfileImage::RetrieveOnUserList($_userImageUserIDList);
		$_staffProfileImageObjectContainer = SWIFT_StaffProfileImage::RetrieveOnStaffList($_staffImageUserIDList);

		// Process attachments
		$_ticketAttachmentContainer = array();
		if ($_SWIFT_TicketObject->GetProperty('hasattachments') == '1') {
			$_ticketAttachmentContainer = $_SWIFT_TicketObject->GetAttachmentContainer();
		}

		$_ticketPostIDList = array_keys($_ticketPostContainer);
		$_ratingResultContainer = SWIFT_RatingResult::Retrieve($_ratingIDList, $_ticketPostIDList);

		$_ticketPostUserContainer = array();
		$this->Database->Query("SELECT * FROM " . TABLE_PREFIX . "users WHERE userid IN (" . BuildIN($_userImageUserIDList) . ")");
		while ($this->Database->NextRecord()) {
			$_ticketPostUserContainer[$this->Database->Record['userid']] = $this->Database->Record;
		}

		foreach ($_ticketPostContainer as $_ticketPostID => $_SWIFT_TicketPostObject) {
			$_postFooter = $_postTitle = '';

			$_userRecordContainer = array();
			if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_USER && $_SWIFT_TicketPostObject->GetProperty('userid') != '0' && isset($_ticketPostUserContainer[$_SWIFT_TicketPostObject->GetProperty('userid')])) {
				$_userRecordContainer = $_ticketPostUserContainer[$_SWIFT_TicketPostObject->GetProperty('userid')];
			}

			$_postTitle = sprintf($this->Language->Get(IIF($_SWIFT_TicketPostObject->GetProperty('issurveycomment') == '1', 'tppostedonsurvey', 'tppostedon')), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketPostObject->GetProperty('dateline')));

			if ($_SWIFT_TicketObject->GetProperty('isphonecall') == '1' && $_SWIFT_TicketObject->GetProperty('firstpostid') == $_SWIFT_TicketPostObject->GetTicketPostID()) {
				$_postFooter .= sprintf($this->Language->Get('phoneext'), htmlspecialchars($_SWIFT_TicketObject->GetProperty('phoneno'))) . '&nbsp;&nbsp;&nbsp;';
			}

			if ($_SWIFT_TicketPostObject->GetProperty('emailto') != '') {
				// Sent as email (New Ticket from Staff CP)
				if ($_ticketPostID == $_SWIFT_TicketObject->GetProperty('firstpostid') && $_SWIFT_TicketObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_STAFF) {
					$_postFooter .= sprintf($this->Language->Get('tpemailto'), htmlspecialchars($_SWIFT_TicketPostObject->GetProperty('emailto'))) . '&nbsp;&nbsp;&nbsp;';

					// Email Forwarded
				} else {
					$_postFooter .= sprintf($this->Language->Get('tpemailforwardedto'), htmlspecialchars($_SWIFT_TicketPostObject->GetProperty('emailto'))) . '&nbsp;&nbsp;&nbsp;';

				}
			}

			$_postFooter .= sprintf($this->Language->Get('tpemail'), htmlspecialchars($_SWIFT_TicketPostObject->GetProperty('email')));

			$_badgeText = $_badgeClass = '';

			if ($_SWIFT_TicketPostObject->GetProperty('dateline') >= $_SWIFT->Staff->GetProperty('lastvisit')) {
				$_postTitle .= '&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_new3d_orange.png" align="top" border="0" />';
			}

			$_postFooterRight = '';


			if ($_SWIFT_TicketPostObject->GetProperty('ipaddress') != '') {
				$_postFooterRight = sprintf($this->Language->Get('tpipaddress'), htmlspecialchars($_SWIFT_TicketPostObject->GetProperty('ipaddress')));
			}

			if ($_SWIFT_TicketPostObject->GetProperty('isthirdparty') == '1' || $_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_THIRDPARTY) {
				$_badgeClass = 'ticketpostbarbadgered';
				$_badgeText = $this->Language->Get('badgethirdparty');
			} else if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_CC) {
				$_badgeClass = 'ticketpostbarbadgered';
				$_badgeText = $this->Language->Get('badgecc');
			} else if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_BCC) {
				$_badgeClass = 'ticketpostbarbadgered';
				$_badgeText = $this->Language->Get('badgebcc');
			} else if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_USER) {
				$_badgeClass = 'ticketpostbarbadgeblue';
				$_badgeText = $this->Language->Get('badgeuser');
			} else if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_STAFF) {
				$_badgeClass = 'ticketpostbarbadgered';
				$_badgeText = $this->Language->Get('badgestaff');
			}

			$_ticketPostHTML .= '<div class="ticketpostcontainer">';

			// DIV ENCLOSURE BEGIN
			$_ticketPostHTML .= '<div class="ticketpostbar">';
			$_ticketPostHTML .= '<div class="ticketpostbarname">' . StripName(htmlspecialchars($_SWIFT_TicketPostObject->GetProperty('fullname')), 19) . '</div>';
			if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_STAFF && isset($_staffCache[$_SWIFT_TicketPostObject->GetProperty('staffid')]) &&
					!empty($_staffCache[$_SWIFT_TicketPostObject->GetProperty('staffid')]['designation'])) {
				$_ticketPostHTML .= '<div class="ticketpostbardesignation">' . htmlspecialchars(StripName($_staffCache[$_SWIFT_TicketPostObject->GetProperty('staffid')]['designation'], 39)) . '</div>';
			}elseif ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_USER && isset($_userRecordContainer['userdesignation']) && $_userRecordContainer['userdesignation'] != '') {
				$_ticketPostHTML .= '<div class="ticketpostbardesignation">' . htmlspecialchars(StripName($_userRecordContainer['userdesignation'], 39)) . '</div>';
			}
			$_ticketPostHTML .= '<div class="' . $_badgeClass . '"><div class="tpbadgetext">' . htmlspecialchars($_badgeText) . '</div></div>';

			// Begin Avatar Display
			if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_USER &&
					isset($_userProfileImageObjectContainer[$_SWIFT_TicketPostObject->GetProperty('userid')])) {
				$_ticketPostHTML .= '<div class="ticketpostavatar"><div class="tpavatar"><img src="' . SWIFT::Get('basename') .
						'/Base/User/GetProfileImage/' . intval($_SWIFT_TicketPostObject->GetProperty('userid')) . '" align="absmiddle" border="0" /></div></div>';
			} else if ($_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_STAFF &&
					isset($_staffProfileImageObjectContainer[$_SWIFT_TicketPostObject->GetProperty('staffid')])) {
				$_ticketPostHTML .= '<div class="ticketpostavatar"><div class="tpavatar"><img src="' . SWIFT::Get('basename') .
						'/Base/StaffProfile/GetProfileImage/' . intval($_SWIFT_TicketPostObject->GetProperty('staffid')) . '" align="absmiddle" border="0" /></div></div>';
			}

			$_ratingHTML = '';
			if ($_SWIFT->Staff->GetPermission('staff_canviewratings') != '0' && $_SWIFT_TicketPostObject->GetProperty('creator') == SWIFT_TicketPost::CREATOR_STAFF) {
				$_ratingHTML = SWIFT_RatingRenderer::Render(array(SWIFT_Rating::TYPE_TICKETPOST), $_SWIFT_TicketPostObject->GetTicketPostID(), '/Tickets/Ticket/RatingPost/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketPostObject->GetTicketPostID(), $_ratingContainer, $_ratingResultContainer, 'ticketpostinfo');
			}

			if (!empty($_ratingHTML)) {
				$_ticketPostHTML .= '<div class="ticketpostbox">' . $_ratingHTML . '</div>';
			}

			$_ticketPostHTML .= '</div>';
			// DIV ENCLOSURE END

			// Prepare post content suffix
			$_postContentSuffix = '';
			if ($_SWIFT_TicketPostObject->GetProperty('edited') == 1) {
				$_editStaffName = $this->Language->Get('na');
				if (isset($_staffCache[$_SWIFT_TicketPostObject->GetProperty('editedbystaffid')])) {
					$_editStaffName = htmlspecialchars($_staffCache[$_SWIFT_TicketPostObject->GetProperty('editedbystaffid')]['fullname']);
				}
				$_postContentSuffix .= '<div class="ticketpostedited">' . sprintf($this->Language->Get('lastedited'), $_editStaffName, SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketPostObject->GetProperty('editeddateline'))) . '</div>';
			}

			// Process the ticket attachments
			$_attachmentHTML = '';
			if (isset($_ticketAttachmentContainer[$_SWIFT_TicketPostObject->GetTicketPostID()]) && _is_array($_ticketAttachmentContainer[$_SWIFT_TicketPostObject->GetTicketPostID()])) {
				$_attachmentHTML .= '<div class="ticketpostcontentsattachments">';
				foreach ($_ticketAttachmentContainer[$_SWIFT_TicketPostObject->GetTicketPostID()] as $_attachmentID => $_attachmentContainer) {
					$_mimeDataContainer = array();
					try {
						$_fileExtension = mb_strtolower(substr($_attachmentContainer['filename'], (strrpos($_attachmentContainer['filename'], '.')+1)));

						$_MIMEListObject = new SWIFT_MIMEList();
						$_mimeDataContainer = $_MIMEListObject->Get($_fileExtension);
					} catch (SWIFT_MIME_Exception $_SWIFT_MIME_ExceptionObject) {
						// Do nothing
					}

					if (isset($_mimeDataContainer[1])) {
						$_attachmentIcon = $_mimeDataContainer[1];
					} else {
						$_attachmentIcon = 'icon_file.gif';
					}

					$_attachmentHTML .= '<a class="ticketpostcontentsattachmentitem" href="' . SWIFT::Get('basename') . '/Tickets/Ticket/GetAttachment/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_attachmentContainer['attachmentid'] . '" target="_blank"
						style="background-image: URL(\'' . SWIFT::Get('themepathimages') . $_attachmentIcon . '\');">' . htmlspecialchars($_attachmentContainer['filename']) . ' <span>(' . FormattedSize($_attachmentContainer['filesize']) . ')</span>' . '</a>';
				}

				$_attachmentHTML .= '</div>';
			}

			$_ticketPostHTML .= '<div class="ticketpostcontents" >';
			$_ticketPostHTML .= '<div class="ticketpostcontentsbar' . IIF($_SWIFT_TicketPostObject->GetProperty('issurveycomment') == '1', 'green') . IIF($_SWIFT_TicketPostObject->GetProperty('isprivate') == '1', 'gray') . '"><div class="ticketbarquote" title="' . $_SWIFT->Language->Get('qticketpost') . '" alt="' . $_SWIFT->Language->Get('qticketpost') . '" onclick="javascript: QuoteTicketPost(\'' . $_SWIFT_TicketObject->GetTicketID() . '\', \'' . $_SWIFT_TicketPostObject->GetTicketPostID() . '\');"></div><div class="ticketbarcontents">' . $_postTitle . '</div><span class="ticketbardatefold"></span></div>';
			$_ticketPostHTML .= '<div class="ticketpostcontentsdetails"><div class="ticketpostcontentsholder"><div class="ticketpostcontentsdetailscontainer">' . $_SWIFT_TicketPostObject->GetDisplayContents() . $_postContentSuffix . '</div></div>' . $_attachmentHTML . '</div>';

			$_ticketPostHTML .= '<div class="ticketpostcontentsbottom"><span class="ticketpostbottomright">' . $_postFooterRight . '</span><div class="ticketpostbottomcontents">' . $_postFooter . '</div></div>';
			$_ticketPostHTML .= '</div>';

			// Edit & Delete
			$_ticketPostHTML .= '<div class="ticketpostbarbottom"><div class="ticketpostbottomcontents">';
			if ($_SWIFT->Staff->GetPermission('staff_tcanupaticketpost') != '0') {
				$_ticketPostHTML .= '<a href="javascript: void(0);" onclick="javascript: UICreateWindow(\'' . SWIFT::Get('basename') .
						'/Tickets/Ticket/EditPost/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketPostObject->GetTicketPostID() . '/' . $_ticketURLSuffix .
						'\', \'editticketpost\', \'' . $_SWIFT->Language->Get('wineditticketpost') . '\', \'' . $_SWIFT->Language->Get('loadingwindow') .
						'\', 650, 430, true);"><img src="' . SWIFT::Get('themepathimages') . 'icon_editgray.gif" align="absmiddle" border="0" /></a>&nbsp;&nbsp;';
			}

			if ($_SWIFT->Staff->GetPermission('staff_tcandeleteticketpost') != '0' && $_SWIFT_TicketObject->GetProperty('firstpostid') != $_SWIFT_TicketPostObject->GetTicketPostID()) {
				$_ticketPostHTML .= '<a href="javascript: void(0);" onclick="javascript: doConfirm(\'' . $this->Language->Get('actionconfirm') . '\', \'' . SWIFT::Get('basename') . '/Tickets/Ticket/DeletePost/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketPostObject->GetTicketPostID() . '/' . $_ticketURLSuffix . '\');"><img src="' . SWIFT::Get('themepathimages') . 'icon_delete.gif" align="absmiddle" border="0" /></a>&nbsp;&nbsp;';
			}
			$_ticketPostHTML .= '</div></div>';

			$_ticketPostHTML .= '<div class="ticketpostclearer"></div>';

			$_ticketPostHTML .= '</div>';
		}


		$_ticketPostHTML .= $_paginationHTML;

		$_ticketPostHTML .= '</div>';

		// Retrieve the Ticket Status & Priority JSON
		$_ticketDataJSON = $this->GetTicketDataJSON();


		$_ticketPostHTML .= '<script language="Javascript" type="text/javascript">';
		$_ticketPostHTML .= '_ticketData = ' . $_ticketDataJSON . ';';

		$_ticketPostHTML .= 'if (window.$UIObject) { window.$UIObject.Queue(function(){';
		$_ticketPostHTML .= '$(\'.ticketgeneralpropertiestitle, .ticketgeneralpropertiescontent\').unbind(\'click\').click(function(event) { return HandleTicketPropertiesClick(event); });';

		if ($_SWIFT_TicketObject->GetProperty('resolutionduedateline') != '0') {
			/* Bug Fix : Saloni Dhall
			 *
			 * SWIFT-3023 : Specifying a bad date format in Date & Time settings causes all hell to break loose
			 *
			 * Comments : The string to be escaped.
			 */
			$_ticketPostHTML .= 'UITipBubble(\'labelresolutiondue\', \'' . addslashes(SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketObject->GetProperty('resolutionduedateline'))) . '\');';
		}

		if ($_SWIFT_TicketObject->GetProperty('duetime') != '0') {
			/* Bug Fix : Saloni Dhall
			 *
			 * SWIFT-3023 : Specifying a bad date format in Date & Time settings causes all hell to break loose
			 *
			 * Comments : The string to be escaped.
			 */
			$_ticketPostHTML .= 'UITipBubble(\'labeldue\', \'' . addslashes(SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketObject->GetProperty('duetime'))) . '\');';
		}
		$_ticketPostHTML .= '}); }</script>';

		$_ticketPostHTML .= $this->GetFlagMenu($_SWIFT_TicketObject);

		$this->UserInterface->AppendHTML($_ticketPostHTML);

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Render the Reply/Forward Tabs
	 *
	 * @author Varun Shoor
	 * @param constant $_tabType The Tab Type
	 * @param SWIFT_Ticket $_SWIFT_TicketObject
	 * @param SWIFT_User $_SWIFT_UserObject
	 * @param SWIFT_UserInterfaceTab $_TabObject
	 * @param array $_ticketWatchContainer (OPTIONAL) The Ticket Watch Container
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function RenderDispatchTab($_tabType, SWIFT_UserInterfaceTab $_TabObject, SWIFT_Ticket $_SWIFT_TicketObject = null, $_SWIFT_UserObject = null,
			$_ticketWatchContainer = array(), $_departmentID = false) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_ticketDraftContents = $_destinationDescription = '';

		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded() &&
				$_SWIFT_TicketObject->GetProperty('hasdraft') == '1') {
			$_SWIFT_TicketDraftObject = SWIFT_TicketDraft::Retrieve($_SWIFT_TicketObject, $_SWIFT->Staff);
			if ($_SWIFT_TicketDraftObject instanceof SWIFT_TicketDraft && $_SWIFT_TicketDraftObject->GetIsClassLoaded()) {

				// Decoding emoji characters
				$_emojiObject = new SWIFT_Emoji();

				$_ticketDraftContents = $_emojiObject->decode($_SWIFT_TicketDraftObject->GetProperty('contents'));
			}
		} else if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
			$_ticketDraftContents = SWIFT_TicketPostLock::RetrieveOnTicketAndStaff($_SWIFT_TicketObject, $_SWIFT->Staff);
		}

		$_SWIFT_TicketViewObject = SWIFT_TicketViewRenderer::GetDefaultTicketViewObject();

		// This is necessary to show the right queue list when opening a ticket which wasnt created through a email queue
		if (!$_departmentID && $_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
			$_departmentID = $_SWIFT_TicketObject->GetProperty('departmentid');
		}

		$_tabPrefix = 'reply';
		if ($_tabType == self::TAB_FORWARD) {
			$_tabPrefix = 'forward';
		} else if ($_tabType == self::TAB_NEWTICKET_EMAIL || $_tabType == self::TAB_NEWTICKET_USER) {
			$_tabPrefix = 'newticket';
		}

		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');
		$_templateGroupCache = $this->Cache->Get('templategroupcache');
		$_departmentCache = $this->Cache->Get('departmentcache');

		$_departmentTitle = $this->Language->Get('na');

		if (isset($_departmentCache[$_departmentID])) {
			$_departmentTitle = $_departmentCache[$_departmentID]['title'];
		}

		$_ticketEmailQueueID = 0;
		$_recipientContainer = $_extendedDataContainer = array();
		$_ticketID = 0;
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
			if ($_SWIFT_TicketObject->GetProperty('replyto') != '' && $_SWIFT_TicketObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_STAFF) {
				$_destinationDescription = htmlspecialchars($_SWIFT_TicketObject->GetProperty('replyto'));
			} else {
				if ($_SWIFT_TicketObject->GetProperty('fullname') != '') {
					$_destinationDescription = htmlspecialchars($_SWIFT_TicketObject->GetProperty('fullname') . ' <' . $_SWIFT_TicketObject->GetProperty('email') . '>');
				} else {
					$_destinationDescription = htmlspecialchars($_SWIFT_TicketObject->GetProperty('email'));
				}
			}

			$_ticketID = intval($_SWIFT_TicketObject->GetTicketID());
			$_recipientContainer = SWIFT_TicketRecipient::RetrieveOnTicket($_SWIFT_TicketObject);
			$_ticketEmailQueueID = intval($_SWIFT_TicketObject->GetProperty('emailqueueid'));

			if ($_SWIFT_TicketViewObject->GetProperty('setasowner') == '1') {
				$_extendedDataContainer['_exOwnerStaffID'] = $_SWIFT->Staff->GetStaffID();
			}

			$_defaultTicketStatusOnReply = $_SWIFT_TicketViewObject->GetProperty('defaultstatusonreply');

			if ($_defaultTicketStatusOnReply != '0' && isset($_ticketStatusCache[$_defaultTicketStatusOnReply]) &&
					($_ticketStatusCache[$_defaultTicketStatusOnReply]['departmentid'] == '0' || $_ticketStatusCache[$_defaultTicketStatusOnReply]['departmentid'] == $_SWIFT_TicketObject->GetProperty('departmentid'))) {
				$_extendedDataContainer['_exTicketStatusID'] = $_defaultTicketStatusOnReply;
			}

		} else {
			$_extendedDataContainer['_exDepartmentID'] = $_departmentID;
			$_extendedDataContainer['_exOwnerStaffID'] = $_SWIFT->Staff->GetStaffID();

			// Calculate Default Values
			foreach ($_templateGroupCache as $_templateGroupID => $_templateGroupContainer) {
				if ($_templateGroupContainer['isdefault'] == '1') {
					$_extendedDataContainer['_exTicketStatusID'] = $_templateGroupContainer['ticketstatusid'];
					$_extendedDataContainer['_exTicketPriorityID'] = $_templateGroupContainer['priorityid'];
					$_extendedDataContainer['_exTicketTypeID'] = $_templateGroupContainer['tickettypeid'];
				}
			}
		}

		$_ticketStatusContainer = false;
		/// Get Default Status from Ticket
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded() && isset($_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')])) {
			$_ticketStatusContainer = $_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')];

			// Retrieve Default Status from Master Group
		} else if (isset($_extendedDataContainer['_exTicketStatusID']) && isset($_ticketStatusCache[$_extendedDataContainer['_exTicketStatusID']])) {
			$_ticketStatusContainer = $_ticketStatusCache[$_extendedDataContainer['_exTicketStatusID']];
		}

		$_ticketPriorityContainer = false;

		// Get Default Priority from Ticket
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded() && isset($_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')])) {
			$_ticketPriorityContainer = $_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')];

			// Get Default Priority from Master Template Group
		} else if (isset($_extendedDataContainer['_exTicketPriorityID']) && isset($_ticketPriorityCache[$_extendedDataContainer['_exTicketPriorityID']])) {
			$_ticketPriorityContainer = $_ticketPriorityCache[$_extendedDataContainer['_exTicketPriorityID']];
		}

		$_titleBackgroundColor = '#626262';
		if ($_ticketStatusContainer) {
			$_titleBackgroundColor = $_ticketStatusContainer['statusbgcolor'];
		}

		// Override the color if the default status on reply is different than the active ticket status
		if (isset($_extendedDataContainer['_exTicketStatusID']) &&
				(($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_extendedDataContainer['_exTicketStatusID'] != $_SWIFT_TicketObject->GetProperty('ticketstatusid') && isset($_ticketStatusCache[$_extendedDataContainer['_exTicketStatusID']])) ||
						(!$_SWIFT_TicketObject instanceof SWIFT_Ticket && isset($_ticketStatusCache[$_extendedDataContainer['_exTicketStatusID']])))) {
			$_titleBackgroundColor = $_ticketStatusCache[$_extendedDataContainer['_exTicketStatusID']]['statusbgcolor'];
		}

		$_priorityBackgroundColor = false;
		if ($_ticketPriorityContainer && isset($_ticketPriorityContainer['bgcolorcode']) && !empty($_ticketPriorityContainer['bgcolorcode'])) {
			$_priorityBackgroundColor = $_ticketPriorityContainer['bgcolorcode'];
		}


		$_ticketCCEmailContainer = $_ticketBCCEmailContainer = $_ticketThirdPartyEmailContainer = $_ticketForwardContainer = array();

		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_THIRDPARTY])) {
			$_ticketThirdPartyEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_THIRDPARTY];
		}

		if (count($_ticketThirdPartyEmailContainer) == 1) {
			$_ticketForwardContainer = $_ticketThirdPartyEmailContainer;
		}

		/**
		 * BUG Fix : Abhinav Kumar <abhinav.kumar@kayako.com>
		 *
		 * SWIFT-2375: While forwarding a ticket to a third party, 'CC' users should not be selected by default.
		 *
		 * Comments: use SWIFT_UserInterfaceTab::TextMultipleAutoCompleteExtended() for the forward tab
		 */
		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_CC])) {
			if ($_tabType == self::TAB_FORWARD) {
				foreach ($_recipientContainer[SWIFT_TicketRecipient::TYPE_CC] as $_key => $_val) {
					$_ticketCCEmail			= array();
					$_ticketCCEmail['key']		= $_key;
					$_ticketCCEmail['value']		= $_val;
					$_ticketCCEmail['checked']	= '';

					$_ticketCCEmailContainer[] = $_ticketCCEmail;
				}
			} else {
				$_ticketCCEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_CC];
			}
		}

		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_BCC])) {
			$_ticketBCCEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_BCC];
		}

		$_emailQueueCache = $this->Cache->Get('queuecache');

		$_TabObject->SetColumnWidth('130');

		$_optionsContainer = array();
		$_index = 0;
		$_queueFrom = false;
		$_selected = false;

		/*
		 * BUG FIX - Ashish Kataria
		 *
		 * SWIFT-1988 From address during post reply is set to email queue of lowest queue ID on department where no email queue specified
		 *
		 * Comments: Set $_selected to true when we get selected option
		 */
		$_selected = false;

		// Attempt to retrieve email queue based on department
		if (!empty($_departmentID) && isset($_emailQueueCache['list']) && _is_array($_emailQueueCache['list'])) {
			foreach ($_emailQueueCache['list'] as $_emailQueueID => $_emailQueueContainer) {
				if ($_emailQueueContainer['departmentid'] == $_departmentID && $_emailQueueContainer['isenabled'] == '1') {
					/*
					 * BUG FIX - Ashish Kataria <ashish.kataria@kayako.com>, Nidhi Gupta <nidhi.gupta@kayako.com>
					 *
					 * SWIFT-2520 Ticket Reply FROM does not use mail queue FROM NAME
					 *
					 * Comments: Default value set to Staff full name, check for customfromname if found then replace the fromNameSuffix
					 */
					$_fromNameSuffix = !empty($_emailQueueContainer['customfromname']) ? $_emailQueueContainer['customfromname'] : $_SWIFT->Staff->GetProperty('fullname');
					$_optionsContainer[$_index]['title'] = $_fromNameSuffix . ' <' . $_emailQueueContainer['email'] . '>';
					$_optionsContainer[$_index]['value'] = $_emailQueueID;
					if ($_ticketEmailQueueID == $_emailQueueID) {
						$_optionsContainer[$_index]['selected'] = true;
						$_selected = true;
					}

					$_index++;
					$_queueFrom = true;
					$_selected = true;
				}
			}
		}

		/*
		 * BUG FIX - Varun Shoor
		 *
		 * SWIFT-1667 Email queue address linked with Parent department should also be availbale for sub-department
		 *
		 * Comments: If we are unable to find an email for this department and we have a parent department, we try to match up against that
		 */
		$_parentDepartmentID = 0;
		if (!empty($_departmentCache[$_departmentID]['parentdepartmentid'])) {
			$_parentDepartmentID = $_departmentCache[$_departmentID]['parentdepartmentid'];
		}

		if (!$_queueFrom && !empty($_parentDepartmentID)) {
			foreach ($_emailQueueCache['list'] as $_emailQueueID => $_emailQueueContainer) {
				if ($_emailQueueContainer['departmentid'] == $_parentDepartmentID && $_emailQueueContainer['isenabled'] == '1') {
					/*
					 * BUG FIX - Ashish Kataria <ashish.kataria@kayako.com>, Nidhi Gupta <nidhi.gupta@kayako.com>
					 *
					 * SWIFT-2520 Ticket Reply FROM does not use mail queue FROM NAME
					 *
					 * Comments: Default value set to Staff full name, check for customfromname if found then replace the fromNameSuffix
					 */
					$_fromNameSuffix = !empty($_emailQueueContainer['customfromname']) ? $_emailQueueContainer['customfromname'] : $_SWIFT->Staff->GetProperty('fullname');
					$_optionsContainer[$_index]['title'] = $_fromNameSuffix . ' <' . $_emailQueueContainer['email'] . '>';
					$_optionsContainer[$_index]['value'] = $_emailQueueID;
					$_optionsContainer[$_index]['selected'] = true;

					$_index++;

					$_queueFrom = true;
				}
			}
		}

		/*
		 * BUG FIX - Varun Shoor
		 *
		 * SWIFT-1317 From address should also check the ticket template group id with 'Queue Template Group' name under email queue.
		 *
		 * Comments: Try to compare the email queue based on template group if we couldnt match on any of the scenarios above
		 */
		$_ticketTemplateGroupID = 0;
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
			$_ticketTemplateGroupID = intval($_SWIFT_TicketObject->GetProperty('tgroupid'));
		}
		/*
		 * BUG FIX - Saloni Dhall
		 *
		 * SWIFT-1988 From address during post reply is set to email queue of lowest queue ID on department .
		 */
		if (!$_queueFrom && !empty($_ticketTemplateGroupID)) {
			foreach ($_emailQueueCache['list'] as $_emailQueueID => $_emailQueueContainer) {
				if ($_ticketTemplateGroupID == $_emailQueueContainer['tgroupid'] && $_emailQueueContainer['isenabled'] == '1' && $_emailQueueContainer['departmentid'] == $_departmentID) {
					/*
					 * BUG FIX - Ashish Kataria <ashish.kataria@kayako.com>, Nidhi Gupta <nidhi.gupta@kayako.com>
					 *
					 * SWIFT-2520 Ticket Reply FROM does not use mail queue FROM NAME
					 *
					 * Comments: Default value set to Staff full name, check for customfromname if found then replace the fromNameSuffix
					 */
					$_fromNameSuffix = !empty($_emailQueueContainer['customfromname']) ? $_emailQueueContainer['customfromname'] : $_SWIFT->Staff->GetProperty('fullname');
					$_optionsContainer[$_index]['title'] = $_fromNameSuffix . ' <' . $_emailQueueContainer['email'] . '>';
					$_optionsContainer[$_index]['value'] = $_emailQueueID;
					$_optionsContainer[$_index]['selected'] = true;

					$_index++;

					$_queueFrom = true;
				}
			}
		}

		/*
		 * BUG FIX - Varun Shoor
		 *
		 * SWIFT-1301 Improvement in From Email Address while replying to a ticket from Staff CP
		 *
		 * Comments: If we couldnt find a queue linked with this ticket then we try to match one up using the domain name
		 */
		if (!$_queueFrom && !empty($_ticketEmailQueueID) && isset($_emailQueueCache['list'][$_ticketEmailQueueID]['email'])) {
			$_ticketEmailQueueAddress = mb_strtolower($_emailQueueCache['list'][$_ticketEmailQueueID]['email']);

			foreach ($_emailQueueCache['list'] as $_emailQueueID => $_emailQueueContainer) {
				$_emailQueueAddress = mb_strtolower($_emailQueueContainer['email']);

				if (strstr($_ticketEmailQueueAddress, '@') == strstr($_emailQueueAddress, '@') && $_emailQueueContainer['isenabled'] == '1') {
					/*
					 * BUG FIX - Ashish Kataria <ashish.kataria@kayako.com>, Nidhi Gupta <nidhi.gupta@kayako.com>
					 *
					 * SWIFT-2520 Ticket Reply FROM does not use mail queue FROM NAME
					 *
					 * Comments: Default value set to Staff full name, check for customfromname if found then replace the fromNameSuffix
					 */
					$_fromNameSuffix = !empty($_emailQueueContainer['customfromname']) ? $_emailQueueContainer['customfromname'] : $_SWIFT->Staff->GetProperty('fullname');
					$_optionsContainer[$_index]['title'] = $_fromNameSuffix . ' <' . $_emailQueueAddress . '>';
					$_optionsContainer[$_index]['value'] = $_emailQueueID;
					$_optionsContainer[$_index]['selected'] = true;

					$_index++;

					$_queueFrom = true;
				}
			}
		}



		// Use Default Return Email
		$_optionsContainer[$_index]['title'] = $_SWIFT->Staff->GetProperty('fullname') . ' <' . $this->Settings->Get('general_returnemail') . '>';
		$_optionsContainer[$_index]['value'] = '0';

		if (!$_selected) {
			$_optionsContainer[$_index]['selected'] = true;
		}
		$_index++;

		$_optionsContainer[$_index]['title'] = $_SWIFT->Staff->GetProperty('fullname') . ' <' . $_SWIFT->Staff->GetProperty('email') . '>';
		$_optionsContainer[$_index]['value'] = '-1';

		$_TabObject->Select($_tabPrefix . 'from', $this->Language->Get('dispatchfrom'), '', $_optionsContainer);

		if ($_tabType == self::TAB_REPLY) {
			$_TabObject->DefaultDescriptionRow($this->Language->Get('dispatchto'), '', '<span class="tabledescriptionbig">' . $_destinationDescription . '</span>');
		}

		if ($_tabType == self::TAB_NEWTICKET_EMAIL || $_tabType == self::TAB_NEWTICKET_USER) {
			$_TabObject->Text($_tabPrefix . 'subject', $this->Language->Get('dispatchsubject'), '', '', 'text', '60');
		}

		if ($_tabType == self::TAB_FORWARD || $_tabType == self::TAB_NEWTICKET_EMAIL) {
			$_tagSuffixHTML = '';
			if ($_tabType == self::TAB_FORWARD) {
				$_tagSuffixHTML = '<label for="opt' . $_tabPrefix . '_addrecipients%tagid">&nbsp;&nbsp;[ <input type="checkbox" id="opt' . $_tabPrefix . '_addrecipients%tagid" name="opt' . $_tabPrefix . '_addrecipients[]" value="%tagvalue"> ' . $this->Language->Get('tagaddtorecp') . ' ]</label>';

				/*
				 * BUG FIX - Ravi Sharma
				 *
				 * SWIFT-3402: Edit Subject Field option should be available on ticket forwarding page.
				 *
				 * Comments: Adding subject field in forward tab.
				 */
				$_TabObject->Text($_tabPrefix . 'subject', $this->Language->Get('dispatchsubject'), '', $_SWIFT_TicketObject->GetProperty('subject'), 'text', '60');
			}
			$_TabObject->TextMultipleAutoComplete($_tabPrefix . 'to', $this->Language->Get('dispatchto'), '', '/Tickets/Ajax/SearchEmail', $_ticketForwardContainer, 'icon_email.gif',
					false, false, 2, false, false, false, $_tagSuffixHTML, array('containemail' => true));
		} else if ($_tabType == self::TAB_NEWTICKET_USER) {
			$_extendedHTML = '&nbsp;&nbsp;<a href="' . "javascript: UICreateWindow('" . SWIFT::Get('basename') . "/Base/User/QuickInsert/" .
					"', 'userquickinsert', '" . $_SWIFT->Language->Get('winuserquickinsert') . "', '" . $_SWIFT->Language->Get('loadingwindow') . "', 850, 610, true, this);" . '" ><img src="' . SWIFT::Get('themepathimages') . 'icon_addplus.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchnewuser') . '</a><div id="quickinsertuserdiv" style="display: none;"></div>';
			$_TabObject->TextAutoComplete('userid', $this->Language->Get('dispatchuser'), '/Base/User/AjaxSearch', '', '', 0, '', '30', 0, $_extendedHTML);
		}

		/**
		 * BUG Fix : Abhinav Kumar <abhinav.kumar@kayako.com>
		 *
		 * SWIFT-2375: While forwarding a ticket to a third party, 'CC' users should not be selected by default.
		 *
		 * Comments: use SWIFT_UserInterfaceTab::TextMultipleAutoCompleteExtended() for the forward tab
		 */
		if ($_tabType == self::TAB_FORWARD) {
			$_TabObject->TextMultipleAutoCompleteExtended($_tabPrefix . 'cc', $this->Language->Get('dispatchcc'), '', '/Tickets/Ajax/SearchEmail', $_ticketCCEmailContainer, 'icon_email.gif', false, false, 2, false, false, true, '', array('containemail' => true));
		} else {
			$_TabObject->TextMultipleAutoComplete($_tabPrefix . 'cc', $this->Language->Get('dispatchcc'), '', '/Tickets/Ajax/SearchEmail', $_ticketCCEmailContainer, 'icon_email.gif', false, false, 2, false, false, true, '', array('containemail' => true));
		}

		if (_is_array($_ticketBCCEmailContainer))
		{
			$_TabObject->TextMultipleAutoComplete($_tabPrefix . 'bcc', $this->Language->Get('dispatchbcc'), '', '/Tickets/Ajax/SearchEmail', $_ticketBCCEmailContainer, 'icon_email.gif', false, false, 2, false, false, true, '', array('containemail' => true));
		}

		// Begin Quick Insert
		$_quickInsertHTML = '<div class="swifttextquickinsertdiv">';
		$_quickInsertHTML .= '<div class="qipadding"><input type="text" class="swifttextautocompleteinput" name="qi' . $_tabPrefix . '_macro" id="qi' . $_tabPrefix . '_macro" value="' . $this->Language->Get('qimacro') . '" autocomplete="off" size="40" /></div>';
		$_quickInsertHTML .= '<span id="qi' . $_tabPrefix . '_macromenu">&nbsp;</span>';
		$_quickInsertHTML .= '</div>';

		if (SWIFT_App::IsInstalled(APP_KNOWLEDGEBASE)) {
			$_quickInsertHTML .= '<div class="swifttextquickinsertdiv">';
			$_quickInsertHTML .= '<div class="qipadding"><input type="text" class="swifttextautocompleteinput" name="qi' . $_tabPrefix . '_knowledgebase" id="qi' . $_tabPrefix . '_knowledgebase" value="' . $this->Language->Get('qiknowledgebase') . '" autocomplete="off" size="40" /></div>';
			$_quickInsertHTML .= '<span id="qi' . $_tabPrefix . '_knowledgebasemenu">&nbsp;</span>';
			$_quickInsertHTML .= '</div>';
		}

		$_TabObject->DefaultDescriptionRow($this->Language->Get('quickinsert'), '', $_quickInsertHTML);

		// Begin Properties
		$_dividerHTML = '<div class="ticketreleasepropertiesdivider"><img src="' . SWIFT::Get('themepathimages') . 'ticketpropertiesdivider.png" align="middle" border="0" /></div>';
		$_renderHTML = '<tr><td colspan="2"><div class="ticketreplycontainer">';
		$_renderHTML .= '<div class="ticketreplyproperties" id="' . $_tabPrefix . 'ticketproperties" style="background-color: ' . htmlspecialchars($_titleBackgroundColor) . ';">';

		// Departments
		if ($_tabType == self::TAB_NEWTICKET_EMAIL || $_tabType == self::TAB_NEWTICKET_USER) {
			$_renderHTML .= '<div class="ticketgeneralpropertiesobject"><div class="newticketpropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div>';
			$_renderHTML .= '<div class="newticketpropertiesselect"><select id="' . $_tabPrefix . '_departmentid" name="' . $_tabPrefix . 'departmentid" class="swiftselect" style="width:160px;" onchange="javascript: UpdateTicketStatusDiv(this, \'' . $_tabPrefix . 'ticketstatusid\', false, false, \'' . $_tabPrefix . 'ticketproperties\'); UpdateTicketTypeDiv(this, \'' . $_tabPrefix . 'tickettypeid\', false, false); UpdateTicketOwnerDiv(this, \'' . $_tabPrefix . 'ownerstaffid\', false, false);">';
			$_renderHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_DEPARTMENT, $_extendedDataContainer);
			$_renderHTML .= '</select></div></div>';
		} else {
			$_renderHTML .= '<div class="ticketreplypropertiesobject"><div class="ticketreplypropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div>';
			$_renderHTML .= '<div class="ticketreplypropertiesselect"><select id="' . $_tabPrefix . '_departmentid" name="' . $_tabPrefix . 'departmentid" class="swiftselect" style="width:160px;" onchange="javascript: UpdateTicketStatusDiv(this, \'' . $_tabPrefix . 'ticketstatusid\', false, false, \'' . $_tabPrefix . 'ticketproperties\'); UpdateTicketTypeDiv(this, \'' . $_tabPrefix . 'tickettypeid\', false, false); UpdateTicketOwnerDiv(this, \'' . $_tabPrefix . 'ownerstaffid\', false, false);">';
			$_renderHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_DEPARTMENT, $_extendedDataContainer);
			$_renderHTML .= '</select></div></div>';
		}
		$_renderHTML .= $_dividerHTML;

		// Owner
		$_ownerSelectHTML = '<div class="ticketreplypropertiesselect"><div id="' . $_tabPrefix . 'ownerstaffid_container"><select id="select' . $_tabPrefix . 'ownerstaffid" name="' . $_tabPrefix . 'ownerstaffid" class="swiftselect" style="width:160px;">';
		$_ownerSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_OWNER, $_extendedDataContainer);
		$_ownerSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreplypropertiesobject"><div class="ticketreplypropertiestitle">' . $this->Language->Get('proptitleowner') . '</div>' . $_ownerSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Type
		$_ticketTypeSelectHTML = '<div class="ticketreplypropertiesselect"><div id="' . $_tabPrefix . 'tickettypeid_container"><select id="select' . $_tabPrefix . 'tickettypeid" name="' . $_tabPrefix . 'tickettypeid" class="swiftselect" style="width:160px;">';
		$_ticketTypeSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_TYPE, $_extendedDataContainer);
		$_ticketTypeSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreplypropertiesobject"><div class="ticketreplypropertiestitle">' . $this->Language->Get('proptitletype') . '</div>' . $_ticketTypeSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Status
		$_ticketStatusSelectHTML = '<div class="ticketreplypropertiesselect"><div id="' . $_tabPrefix . 'ticketstatusid_container"><select id="select' . $_tabPrefix . 'ticketstatusid" onchange="javascript: ResetStatusParentColor(this, \'' . $_tabPrefix . 'ticketproperties\');" name="' . $_tabPrefix . 'ticketstatusid" class="swiftselect" style="width:160px;">';
		$_ticketStatusSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_STATUS, $_extendedDataContainer);
		$_ticketStatusSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreplypropertiesobject"><div class="ticketreplypropertiestitle">' . $this->Language->Get('proptitlestatus') . '</div>' . $_ticketStatusSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Priority
		$_ticketPrioritySelectHTML = '<div class="ticketreplypropertiesselect"><select id="' . $_tabPrefix . '_ticketpriorityid" name="' . $_tabPrefix . 'ticketpriorityid" onchange="javascript: ResetPriorityParentColor(this, \'' . $_tabPrefix . 'priorityproperties\');" class="swiftselect" style="width:160px;">';
		$_ticketPrioritySelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_PRIORITY, $_extendedDataContainer);
		$_ticketPrioritySelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketreplypropertiesobject" id="' . $_tabPrefix . 'priorityproperties"' . IIF(!empty($_priorityBackgroundColor), ' style="background-color: ' . htmlspecialchars($_priorityBackgroundColor) . ';"') . '><div class="ticketreplypropertiestitle">' . $this->Language->Get('proptitlepriority') . '</div>' . $_ticketPrioritySelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		$_renderHTML .= '</div>';

		$_renderHTML .= '</div></td></tr>';

		$_TabObject->RowHTML($_renderHTML);

		// Tags
		$_ticketTagContainer = array();
		if ($_SWIFT->Staff->GetPermission('staff_canupdatetags') != '0') {
			if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
				$_ticketTagContainer = SWIFT_Tag::GetTagList(SWIFT_TagLink::TYPE_TICKET, $_SWIFT_TicketObject->GetTicketID());
			}

			$_TabObject->TextMultipleAutoComplete('' . $_tabPrefix . 'tags', false, false, '/Base/Tags/QuickSearch', $_ticketTagContainer, 'icon_taginput.png', 'gridrow2', true, 2, false, true);
		}

		if ($_tabType == self::TAB_NEWTICKET_EMAIL || $_tabType == self::TAB_NEWTICKET_USER) {
			$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_FIELDS, SWIFT_UserInterface::MODE_INSERT,
					array(SWIFT_CustomFieldGroup::GROUP_STAFFTICKET, SWIFT_CustomFieldGroup::GROUP_STAFFUSERTICKET), $_TabObject,
					0, $_POST['departmentid']);
		}

		$_TabObject->Title($this->Language->Get('dispatchcontents'), 'doublearrows.gif');

		$_textAreaDataSuffix = '<div id="' . $_tabPrefix . 'attachmentlistcontainer">';
		if ($_tabType == self::TAB_FORWARD)
		{
			$_textAreaDataSuffix .= SWIFT_AttachmentRenderer::RenderCheckbox(SWIFT_Attachment::LINKTYPE_TICKETPOST, $_SWIFT_TicketObject->GetTicketPostIDList(true), $_tabPrefix . 'attachmentslist');;
		}
		$_textAreaDataSuffix .= '</div>';

		$_TabObject->TextArea($_tabPrefix . 'contents', '', '', $_ticketDraftContents, '30', '14', false, '', '<div id="ticket' . $_tabPrefix . 'lockcontainer' . intval($_ticketID) . '"></div>' . $_textAreaDataSuffix);

		$_sendMailCheckedStatus = ' checked ';
		if ($_tabType == self::TAB_NEWTICKET_USER) {
			$_sendMailCheckedStatus = ' ';
		}

		$_extendedOptions = '<tr class="tablerow1_tr"><td align="left" valign="top" colspan="2" class="tablerow1">';

		if ($_tabType == self::TAB_NEWTICKET_USER) {
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'isphone"><input type="checkbox" value="1" id="' . $_tabPrefix . 'isphone" class="swiftcheckbox" name="opt' . $_tabPrefix . '_isphone" checked />&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_phonesmall.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchisphone') . '</label>';
		}

		/**
		* BUG FIX: Parminder Singh
		*
		* SWIFT-1523: "Send mail" checkmark on Forward not used
		*
		* Comments: There is no need of Send Mail check box while forwarding
		*/
		if ($_tabType != self::TAB_FORWARD) {
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'sendmail"><input type="checkbox" value="1" id="' . $_tabPrefix . 'sendmail" class="swiftcheckbox" name="opt' . $_tabPrefix . '_sendemail"' . $_sendMailCheckedStatus . '/>&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_emailsmall.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchsendmail') . '</label>';
		}

		if ($_tabType != self::TAB_NEWTICKET_USER && $_tabType != self::TAB_NEWTICKET_EMAIL) {
			$_privateChecked = false;
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'private"><input type="checkbox" value="1" id="' . $_tabPrefix . 'private" class="swiftcheckbox" name="opt' . $_tabPrefix . '_private"' . $_privateChecked . '/>&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_privatesmall.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchprivate') . '</label>';
		}

		if ($_tabType == self::TAB_NEWTICKET_USER) {
			$_sendArCheckedStatus = ' ';

			if ($_tabType == self::TAB_NEWTICKET_USER) {
				$_sendArCheckedStatus = ' checked ';
			}

			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'sendar"><input type="checkbox" value="1" id="' . $_tabPrefix . 'sendar" class="swiftcheckbox" name="opt' . $_tabPrefix . '_sendar"' . $_sendArCheckedStatus . '/>&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_emailsmall.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchsendar') . '</label>';
		}

		if ($_tabType == self::TAB_REPLY && $_SWIFT_TicketObject->GetProperty('creator') == SWIFT_Ticket::CREATOR_USER) {
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'createasuser"><input type="checkbox" value="1" id="' . $_tabPrefix . 'createasuser" class="swiftcheckbox" name="opt' . $_tabPrefix . '_createasuser" />&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_dashboardrecentactivity.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchasuser') . '</label>';
		}


		if ($_SWIFT->Staff->GetPermission('staff_tcaninsertmacro') != '0') {
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'addmacro"><input type="checkbox" value="1" id="' . $_tabPrefix . 'addmacro" class="swiftcheckbox" name="opt' . $_tabPrefix . '_addmacro" />&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_plus2.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchaddmacro') . '</label>';
		}

		if (SWIFT_App::IsInstalled(APP_KNOWLEDGEBASE)) {
			$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'addkb"><input type="checkbox" value="1" id="' . $_tabPrefix . 'addkb" class="swiftcheckbox" name="opt' . $_tabPrefix . '_addkb" />&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_plus2.gif' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchaddkb') . '</label>';
		}

		$_watchChecked = false;
		if (isset($_ticketWatchContainer[$_SWIFT->Staff->GetStaffID()])) {
			$_watchChecked = true;
		}
		$_extendedOptions .= '&nbsp;&nbsp;&nbsp;&nbsp;<label for="' . $_tabPrefix . 'watch"><input type="checkbox" value="1" id="' . $_tabPrefix . 'watch" class="swiftcheckbox" name="opt' . $_tabPrefix . '_watch"' . IIF($_watchChecked == true, ' checked') . ' />&nbsp;&nbsp;<img src="' . SWIFT::Get('themepathimages') . 'icon_ticketwatchsmall.png' . '" align="absmiddle" border="0" /> ' . $this->Language->Get('dispatchwatch') . '</label>';

		$_extendedOptions .= '&nbsp;&nbsp;&nbsp;' . $this->Language->Get('billworked') . ' <input type="text" class="swifttextnumeric2small" name="' . $_tabPrefix . 'billingtimeworked" id="' . $_tabPrefix . 'billingtimeworked" value="" size="3" />';
		$_extendedOptions .= '&nbsp;&nbsp;&nbsp;' . $this->Language->Get('billbillable') . ' <input type="text" class="swifttextnumeric2small" name="' . $_tabPrefix . 'billingtimebillable" id="' . $_tabPrefix . 'billingtimebillable" value="" onfocus="javascript: HandleBillingBillableFocus(this, \'' . $_tabPrefix . '\');" size="3" />';

		// Begin Hook: staff_ticket_workflow
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_workflow')) ? eval($_hookCode) : false;
		// End Hook

		$_extendedOptions .= '</td></tr>';

		$_TabObject->RowHTML($_extendedOptions);

		// Begin Hook: staff_ticket_dispatchtab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_dispatchtab')) ? eval($_hookCode) : false;
		// End Hook

		// Notes
		$_TabObject->StartContainer($_tabPrefix . 'notes', false);
		$_TabObject->Notes($_tabPrefix . 'ticketnotes', $this->Language->Get('addnotes'), '', 1);

		$_radioContainer = array();
		$_radioContainer[0]['title'] = $this->Language->Get('notes_ticket');
		$_radioContainer[0]['value'] = 'ticket';
		$_radioContainer[0]['checked'] = true;

		if ($_SWIFT->Staff->GetPermission('staff_caninsertusernote') != '0' && $_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
			$_radioContainer[1]['title'] = $this->Language->Get('notes_user');
			$_radioContainer[1]['value'] = 'user';

			$_radioContainer[2]['title'] = $this->Language->Get('notes_userorganization');
			$_radioContainer[2]['value'] = 'userorganization';
		}

		$_TabObject->Radio($_tabPrefix . 'notetype', $this->Language->Get('notetype'), '', $_radioContainer, false);

		$_TabObject->EndContainer();

		// Follow-Up
		$_TabObject->StartContainer($_tabPrefix . 'followup', false);
		$_TabObject->Title($this->Language->Get('followup'), 'doublearrows.gif');
		$_TabObject->RowHTML('<tr><td><div id="' . $_tabPrefix . 'followupcontainer"></div></td></tr>');
		$_TabObject->EndContainer();

		// Options
		$_TabObject->StartContainer($_tabPrefix . 'options', false);
		$_TabObject->Title($this->Language->Get('options'), 'doublearrows.gif');

		if (!_is_array($_ticketBCCEmailContainer))
		{
			$_TabObject->TextMultipleAutoComplete($_tabPrefix . 'bcc', $this->Language->Get('dispatchbcc'), '', '/Tickets/Ajax/SearchEmail', $_ticketBCCEmailContainer, 'icon_email.gif', false, false, 2, false, false, true, '', array('containemail' => true));
		}

		$_dueDate = '';
		$_ticketDueTime = false;
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded() && $_SWIFT_TicketObject->GetProperty('duetime') != '0') {
			$_dueDate = gmdate(SWIFT_Date::GetCalendarDateFormat(), $_SWIFT_TicketObject->GetProperty('duetime'));

			$_ticketDueTime = $_SWIFT_TicketObject->GetProperty('duetime');
		}
		$_TabObject->Date($_tabPrefix . 'due', $this->Language->Get('dialogduetimeline'), '', $_dueDate, $_ticketDueTime, true);

		$_resolutionDueDate = '';
		$_ticketResolutionDueTime = false;
		if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded() && $_SWIFT_TicketObject->GetProperty('resolutionduedateline') != '0') {
			$_resolutionDueDate = gmdate(SWIFT_Date::GetCalendarDateFormat(), $_SWIFT_TicketObject->GetProperty('resolutionduedateline'));

			$_ticketResolutionDueTime = $_SWIFT_TicketObject->GetProperty('resolutionduedateline');
		}
		$_TabObject->Date($_tabPrefix . 'resolutiondue', $this->Language->Get('dialogresolutionduetimeline'), '', $_resolutionDueDate, $_ticketResolutionDueTime, true);

		$_TabObject->EndContainer();

		// Attach Files
		$_SWIFT_UserInterfaceToolbarObject_Attachment = new SWIFT_UserInterfaceToolbar($this->UserInterface);
		$_SWIFT_UserInterfaceToolbarObject_Attachment->AddButton($this->Language->Get('dispatchaddfile'), 'icon_addplus.gif',
				"AddTicketFile('" . $_tabPrefix . "');", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', '', false);

		$_TabObject->StartContainer($_tabPrefix . 'attachments', false, $_SWIFT_UserInterfaceToolbarObject_Attachment->Render(false));

		$_attachmentContainerHTML = '<tr class="tablerow1_tr"><td align="left" valign="top class="tablerow1"><div id="' . $_tabPrefix . 'attachmentcontainer">';
		$_attachmentFileHTML = '<div class="ticketattachmentitem"><div class="ticketattachmentitemdelete" onclick="javascript: $(this).parent().remove();">&nbsp;</div><input name="' . $_tabPrefix . 'attachments[]" type="file" size="20" class="swifttextlarge swifttextfile" /></div>';
		for ($index = 0; $index < 3; $index++) {
			$_attachmentContainerHTML .= $_attachmentFileHTML;
		}
		$_attachmentContainerHTML .= '</div></td></tr>';

		$_TabObject->RowHTML($_attachmentContainerHTML);

		$_TabObject->EndContainer();

		// Retrieve the Ticket Status & Priority JSON
		if ($_tabType == self::TAB_NEWTICKET_EMAIL || $_tabType == self::TAB_NEWTICKET_USER) {
			$_ticketDataJSON = $this->GetTicketDataJSON();
			$_ticketDataHTML = '<script language="Javascript" type="text/javascript">';
			$_ticketDataHTML .= '_ticketData = ' . $_ticketDataJSON . ';';
			$_ticketDataHTML .= '</script>';

			$this->UserInterface->AppendHTML($_ticketDataHTML);
		}

		$_scriptHTML = '<script language="Javascript" type="text/javascript">';
		$_scriptHTML .= 'if (window.$UIObject) { window.$UIObject.Queue(function(){';
		$_scriptHTML .= ' $("#' . $_tabPrefix . 'billingtimeworked").mask("99:99");';
		$_scriptHTML .= ' $("#' . $_tabPrefix . 'billingtimebillable").mask("99:99");';
		$_scriptHTML .= ' QuickInsertLoad(\'' . $_tabPrefix . '\');';
		$_scriptHTML .= '}); }';
		$_scriptHTML .= '</script>';

		$_TabObject->AppendHTML($_scriptHTML);

		return true;
	}

	/**
	 * Render the Edit Post Form
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param SWIFT_TicketPost $_SWIFT_TicketPostObject The Ticket Post Object
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderEditPost(SWIFT_Ticket $_SWIFT_TicketObject, SWIFT_TicketPost $_SWIFT_TicketPostObject, $_listType = 'inbox',
			$_departmentID = -1, $_ticketStatusID = -1, $_ticketTypeID = -1, $_ticketLimitOffset = 0) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$this->UserInterface->Start(get_class($this) . 'post', '/Tickets/Ticket/EditPostSubmit/'. $_SWIFT_TicketObject->GetTicketID() . '/' .
				$_SWIFT_TicketPostObject->GetTicketPostID() . '/' . $_listType . '/' . $_departmentID . '/' . $_ticketStatusID . '/' .
				$_ticketTypeID . '/' . $_ticketLimitOffset, SWIFT_UserInterface::MODE_EDIT, true);


		if (isset($_POST['_isDialog']) && $_POST['_isDialog'] == 1) {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif');
		}

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		/*
		 * ###############################################
		 * BEGIN GENERAL TAB
		 * ###############################################
		*/
		$_GeneralTabObject = $this->UserInterface->AddTab($this->Language->Get('tabgeneral'), 'icon_form.gif', 'generaledit', true);

		$_GeneralTabObject->TextArea('postcontents', '', '', $_SWIFT_TicketPostObject->GetProperty('contents'), '30', '12');

		/*
		 * ###############################################
		 * END GENERAL TAB
		 * ###############################################
		*/

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Render the Billing Tab for Tickets interface
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderBilling(SWIFT_Ticket $_SWIFT_TicketObject, $_listType, $_departmentID, $_ticketStatusID, $_ticketTypeID,
			$_ticketLimitOffset) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_staffCache = $this->Cache->Get('staffcache');

		$_ticketURLSuffix = SWIFT::Get('ticketurlsuffix');
		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_BillingTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabbilling'), '', 1, 'billing', false, false, 0, '');
		$_BillingTabObject->SetColumnWidth('15%');
		$_BillingTabObject->LoadToolbar();
		$_BillingTabObject->Toolbar->AddButton($this->Language->Get('insert'), 'icon_addplus.gif', '/Tickets/Ticket/BillingSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);
		$_BillingTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$_billingHTML = $this->RenderBillingEntries($_SWIFT_TicketObject);

		if (!empty($_billingHTML)) {
			$_BillingTabObject->RowHTML('<tr class="gridrow3" id="ticketbillingcontainerdivholder"><td colspan="2" align="left" valign="top class="gridrow3" id="ticketbillingcontainertd">' . $_billingHTML . '</td></tr>');
		} else {
			$_BillingTabObject->RowHTML('<tr class="gridrow3" style="display: none;" id="ticketbillingcontainerdivholder"><td colspan="2" align="left" valign="top class="gridrow3" id="ticketbillingcontainertd"></td></tr>');
		}

		if ($_SWIFT->Staff->GetPermission('staff_tcaninsertbilling') != '0') {
			$this->CreateBillingForm($_BillingTabObject, $_SWIFT->Staff->GetStaffID(), DATENOW, DATENOW, '', '');
		}

		$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_FIELDS, SWIFT_UserInterface::MODE_INSERT,
				array(SWIFT_CustomFieldGroup::GROUP_TIMETRACK), $_BillingTabObject);

		// Begin Hook: staff_ticket_billingtab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_billingtab')) ? eval($_hookCode) : false;
		// End Hook

		$_renderHTML = $_BillingTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= 'QueueFunction(function() {';
		$_renderHTML .= ' $("#billingtimeworked").mask("99:99");';
		$_renderHTML .= ' $("#billingtimebillable").mask("99:99");';
		$_renderHTML .= '}); reParseDoc();';
		$_renderHTML .= '</script>';


		echo $_renderHTML;

		return true;
	}

	/**
	 * Create a billing form
	 *
	 * @author Varun Shoor
	 * @param SWIFT_UserInterfaceTab $_BillingTabObject The Billing Tab Object
	 * @param int $_workerStaffID The Worker Staff ID
	 * @param int $_defaultBillDate The UNIX Date Timestamp
	 * @param int $_defaultWorkDate The Default work date in timestamp
	 * @param int $_defaultTimeWorked (OPTIONAL)
	 * @param int $-defaultTimeBillable (OPTIONAL)
	 * @param string $_defaultNotes (OPTIONAL)
	 * @param int $_defaultNoteColor (OPTIONAL)
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	protected function CreateBillingForm(SWIFT_UserInterfaceTab $_BillingTabObject, $_workerStaffID, $_defaultBillDate, $_defaultWorkDate,
			$_defaultTimeWorked = '', $_defaultTimeBillable = '', $_defaultNotes = '', $_defaultNoteColor = 1, $_type = '') {
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_staffCache = $this->Cache->Get('staffcache');

		foreach (array('_defaultTimeWorked', '_defaultTimeBillable') as $_variable) {
			$_value = $$_variable;

			$_timeMinutes = $_value/60;
			$_timeHours = $_timeMinutes/60;

			$_finalHours = floor($_timeHours);
			$_finalMinutes = $_timeMinutes - ($_finalHours*60);
			if (strlen($_finalHours) == 1) {
				$_finalHours = '0' . $_finalHours;
			}

			if (strlen($_finalMinutes) == 1) {
				$_finalMinutes = '0' . $_finalMinutes;
			}

			$$_variable = $_finalHours . ':' . $_finalMinutes;
		}

		$_billingEntriesHTML = $this->Language->Get('billworked') . ' <input type="text" class="swifttextnumeric2" name="' . $_type . 'billingtimeworked" id="' . $_type . 'billingtimeworked" value="' . $_defaultTimeWorked . '" size="5" />';
		$_billingEntriesHTML .= '&nbsp;&nbsp;&nbsp;' . $this->Language->Get('billbillable') . ' <input type="text" class="swifttextnumeric2" name="' . $_type . 'billingtimebillable" id="' . $_type . 'billingtimebillable" value="' . $_defaultTimeBillable . '" onfocus="javascript: HandleBillingBillableFocus(this, \'' . $_type . '\');" size="5" />';
		$_BillingTabObject->DefaultDescriptionRow($this->Language->Get('billtimespent'), '', $_billingEntriesHTML);

		$_parsedBillDate = $_parsedWorkDate = '';
		if (!empty($_defaultBillDate)) {
			$_parsedBillDate = gmdate(SWIFT_Date::GetCalendarDateFormat(), $_defaultBillDate);
		}

		if (!empty($_defaultWorkDate)) {
			$_parsedWorkDate = gmdate(SWIFT_Date::GetCalendarDateFormat(), $_defaultWorkDate);
		}

		$_BillingTabObject->Date($_type . 'billdate', $this->Language->Get('billdate'), '', $_parsedBillDate, $_defaultBillDate, true, true, 'SyncTicketBillDate(\'' . $_type . '\');');
		$_BillingTabObject->Date($_type . 'billworkdate', $this->Language->Get('billworkdate'), '', $_parsedWorkDate, $_defaultWorkDate, true, true);

		$_optionsContainer = array();
		$_index = 0;
		foreach ($_staffCache as $_staffID => $_staffContainer) {
			$_optionsContainer[$_index]['title'] = $_staffContainer['fullname'];
			$_optionsContainer[$_index]['value'] = $_staffID;

			if ($_staffID == $_workerStaffID) {
				$_optionsContainer[$_index]['selected'] = true;
			}

			$_index++;
		}

		$_BillingTabObject->Select($_type . 'billingworkerstaffid', $this->Language->Get('billworker'), '', $_optionsContainer);

		// Notes
		$_BillingTabObject->Notes($_type . 'billingnotes', $this->Language->Get('notes'), $_defaultNotes, $_defaultNoteColor);

		return true;
	}

	/**
	 * Render the Billing Form
	 *
	 * @author Varun Shoor
	 * @param int $_mode The Render Mode
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer
	 * @param SWIFT_TicketTimeTrack $_SWIFT_TicketTimeTrackObject The SWIFT_TicketTimeTrack Object Poitner
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderBillingForm($_mode, SWIFT_Ticket $_SWIFT_TicketObject, SWIFT_TicketTimeTrack $_SWIFT_TicketTimeTrackObject) {
		$_SWIFT = SWIFT::GetInstance();

		$_staffCache = $this->Cache->Get('staffcache');

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$this->UserInterface->Start('ticketbillingform', '/Tickets/Ticket/EditBillingSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketTimeTrackObject->GetTicketTimeTrackID(), SWIFT_UserInterface::MODE_EDIT, true, true, false, false, 'ticketbillingcontainertd');

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		/*
		 * ###############################################
		 * BEGIN BILLING TAB
		 * ###############################################
		*/

		$_BillingTabObject = $this->UserInterface->AddTab($this->Language->Get('tabeditbilling'), 'icon_clock.png', 'editbilling', true);
		$_BillingTabObject->Overflow(400);

		/**
		 * BUG FIX - Parminder Singh
		 *
		 * SWIFT-2975: Editing a billing entry results in error being logged
		 *
		 */
		$_ticketTimeTrackNotes = '';
		$_SWIFT_TicketTimeTrackNoteObject = SWIFT_TicketTimeTrackNote::RetrieveObjectOnTicketTimeTrackID($_SWIFT_TicketTimeTrackObject);
		if ($_SWIFT_TicketTimeTrackNoteObject instanceof SWIFT_TicketTimeTrackNote && $_SWIFT_TicketTimeTrackNoteObject->GetIsClassLoaded()) {
			$_ticketTimeTrackNotes = $_SWIFT_TicketTimeTrackNoteObject->GetProperty('notes');
		}

		$this->CreateBillingForm($_BillingTabObject, $_SWIFT_TicketTimeTrackObject->GetProperty('workerstaffid'),
			$_SWIFT_TicketTimeTrackObject->GetProperty('dateline'), $_SWIFT_TicketTimeTrackObject->GetProperty('workdateline'),
			$_SWIFT_TicketTimeTrackObject->GetProperty('timespent'), $_SWIFT_TicketTimeTrackObject->GetProperty('timebillable'),
			$_ticketTimeTrackNotes, $_SWIFT_TicketTimeTrackObject->GetProperty('notecolor'), 'e');

		$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_FIELDS, SWIFT_UserInterface::MODE_EDIT,
				array(SWIFT_CustomFieldGroup::GROUP_TIMETRACK), $_BillingTabObject, $_SWIFT_TicketTimeTrackObject->GetTicketTimeTrackID());


		/*
		 * ###############################################
		 * END BILLING TAB
		 * ###############################################
		*/

		$_renderHTML = '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'QueueFunction(function() {';
		$_renderHTML .= ' $("#ebillingtimeworked").mask("99:99");';
		$_renderHTML .= ' $("#ebillingtimebillable").mask("99:99");';
		$_renderHTML .= '});';
		$_renderHTML .= '</script>';

		$_BillingTabObject->AppendHTML($_renderHTML);

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Render the Billing Tab for User Interface
	 *
	 * @author Varun Shoor
	 * @param SWIFT_User $_SWIFT_UserObject The User Object
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderBillingUser(SWIFT_User $_SWIFT_UserObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_staffCache = $this->Cache->Get('staffcache');

		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_BillingTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabbilling'), '', 1, 'billing', false, false, 0, '');
		$_BillingTabObject->LoadToolbar();
		$_BillingTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$_billingHTML = $this->RenderBillingEntries($_SWIFT_UserObject);

		if (!empty($_billingHTML)) {
			$_BillingTabObject->RowHTML('<tr class="gridrow3" id="ticketbillingcontainerdivholder"><td colspan="2" align="left" valign="top class="gridrow3">' . $_billingHTML . '</td></tr>');
		} else {
			$_BillingTabObject->RowHTML('<tr class="tablerow1_tr"><td valign="middle" align="left" class="tablerow1" colspan="8">' . $this->Language->Get('noinfoinview') . '</td></tr>');
		}

		$_renderHTML = $_BillingTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= 'reParseDoc();';
		$_renderHTML .= '</script>';


		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Billing Time Track entries for the given Ticket/User
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Base $_SWIFT_InputObject The SWIFT_Input Object
	 * @return mixed "_renderedHTML" (STRING) on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded or If Invalid Data is Provided
	 */
	public function RenderBillingEntries($_SWIFT_InputObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		} else if ((!$_SWIFT_InputObject instanceof SWIFT_Ticket || !$_SWIFT_InputObject->GetIsClassLoaded()) &&
				(!$_SWIFT_InputObject instanceof SWIFT_User || !$_SWIFT_InputObject->GetIsClassLoaded()) ) {
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);

			return false;
		}

		// Retrieve entries
		$_timeTrackContainer = $_ticketObjectContainer = $_ticketIDList = array();

		$_renderedHTML = '';

		$_totalTimeSpent = $_totalTimeBillable = 0;

		$_ticketIDList = array();
		if ($_SWIFT_InputObject instanceof SWIFT_Ticket) {
			$_ticketIDList[] = $_SWIFT_InputObject->GetTicketID();
		} else if ($_SWIFT_InputObject instanceof SWIFT_User) {
			$_ticketIDList = SWIFT_Ticket::GetTicketIDListOnUser($_SWIFT_InputObject);
		}

		// Fetch ticket time track entries
		$this->Database->Query("SELECT tickettimetracks.*, tickettimetracknotes.notes AS notes
			FROM " . TABLE_PREFIX . "tickettimetracks AS tickettimetracks
			LEFT JOIN " . TABLE_PREFIX . "tickettimetracknotes AS tickettimetracknotes ON (tickettimetracks.tickettimetrackid = tickettimetracknotes.tickettimetrackid)
			WHERE tickettimetracks.ticketid IN (" . BuildIN($_ticketIDList) . ") ORDER BY tickettimetracks.dateline ASC");
		while ($this->Database->NextRecord()) {
			$_timeTrackContainer[$this->Database->Record['tickettimetrackid']] = $this->Database->Record;
			$_ticketIDList[] = $this->Database->Record['ticketid'];

			$_totalTimeSpent += $this->Database->Record['timespent'];
			$_totalTimeBillable += $this->Database->Record['timebillable'];
		}

		if ($_SWIFT_InputObject instanceof SWIFT_User && count($_ticketIDList)) {
			$this->Database->Query("SELECT * FROM " . TABLE_PREFIX . "tickets WHERE ticketid IN (" . BuildIN($_ticketIDList) . ")");
			while ($this->Database->NextRecord()) {
				$_ticketObjectContainer[$this->Database->Record['ticketid']] = new SWIFT_Ticket(new SWIFT_DataStore($this->Database->Record));
			}
		}

		if (!count($_timeTrackContainer)) {
			return '';
		}

		$_renderedHTML .= '<div class="ticketbillinginfocontainer2">';
		$_renderedHTML .= '<img src="' . SWIFT::Get('themepathimages') . 'icon_clock.png' . '" align="absmiddle" border="0" /> ' .
				'<b>' . $this->Language->Get('billtotalworked') . '</b> ' . SWIFT_Date::ColorTime($_totalTimeSpent, false, true) .
				'&nbsp;&nbsp;&nbsp;&nbsp;' .
				'<b>' . $this->Language->Get('billtotalbillable') . '</b> ' . SWIFT_Date::ColorTime($_totalTimeBillable, false, true);
		$_renderedHTML .= '</div>';

		$_renderedHTML .= '<div id="ticketbillingcontainerdiv">';

		foreach ($_timeTrackContainer as $_ticketTimeTrackID => $_ticketTimeTrack) {
			$_icon = 'icon_clock.png';
			$_timeTrackColor = GetSanitizedNoteColor($_ticketTimeTrack['notecolor']);
			$_timeTrackContents = $_ticketTimeTrack['notes'];

			$_timeTrackTitle = '';

			// If this is a user type then we will need to display ticket information along with the other details + a link to open the ticket
			if ($_SWIFT_InputObject instanceof SWIFT_User && isset($_ticketObjectContainer[$_ticketTimeTrack['ticketid']])) {
				$_LinkedTicketObject = $_ticketObjectContainer[$_ticketTimeTrack['ticketid']];
				$_timeTrackTitle = '<a href="' . SWIFT::Get('basename') . '/Tickets/Ticket/View/' . $_LinkedTicketObject->GetTicketID() . '" viewport="1">' . $_LinkedTicketObject->GetTicketDisplayID() . '</a> - ';
			}

			$_timeTrackTitle .= sprintf($this->Language->Get('billingtitle'), htmlspecialchars($_ticketTimeTrack['workerstaffname']), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_ticketTimeTrack['dateline']));

			// Only display the worked on value if its different
			if ($_ticketTimeTrack['workdateline'] != $_ticketTimeTrack['dateline']) {
				$_timeTrackTitle .= sprintf($this->Language->Get('billingtitlework'), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_ticketTimeTrack['workdateline']));
			}

			// Edited but not by staff?
			if (empty($_ticketTimeTrack['editedstaffid']) && $_ticketTimeTrack['isedited'] == '1') {
				$_timeTrackTitle .= sprintf($this->Language->Get('billingeditedtitle2'), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_ticketTimeTrack['editedtimeline']));
				// Edited by staff
			} else if (!empty($_ticketTimeTrack['editedstaffid']) && $_ticketTimeTrack['isedited'] == '1') {
				$_timeTrackTitle .= sprintf($this->Language->Get('billingeditedtitle'), htmlspecialchars($_ticketTimeTrack['editedstaffname']), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_ticketTimeTrack['editedtimeline']));

			}

			// Render the additional time track details
			$_timeTrackDetails = '<p>' . '<b>' . $this->Language->Get('billworked') . '</b> ' . SWIFT_Date::ColorTime($_ticketTimeTrack['timespent'], false, true) . '&nbsp;&nbsp;&nbsp;&nbsp;<b>' . $this->Language->Get('billbillable') . '</b> ' . SWIFT_Date::ColorTime($_ticketTimeTrack['timebillable'], false, true) . '</p>';

			$_finalTimeTrackContents = '';
			if (trim($_timeTrackContents) != '') {
				$_finalTimeTrackContents = '<p>' . nl2br(htmlspecialchars($_timeTrackContents)) . '</p>';
			}

			$_customFieldHTML = $this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_STATIC, SWIFT_UserInterface::MODE_INSERT,
					array(SWIFT_CustomFieldGroup::GROUP_TIMETRACK), null, $_ticketTimeTrackID, 0, true, true);
			$_finalCustomFieldHTML = '';
			if (!empty($_customFieldHTML)) {
				$_finalCustomFieldHTML = $_customFieldHTML;
			}

			$_renderedHTML .= '<div id="note' . intval($_timeTrackColor) . '" class="bubble"><div class="notebubble"><blockquote>' .
					$_finalTimeTrackContents . $_finalCustomFieldHTML . '<hr class="ticketbillinghr" />'. $_timeTrackDetails . '</blockquote></div><cite class="tip"><strong><img src="' . SWIFT::Get('themepath') .
					'images/' . $_icon . '" align="absmiddle" border="0" /> ' . $_timeTrackTitle . '</strong><div style="float: right; padding-right: 4px;">';

			if ($_SWIFT_InputObject instanceof SWIFT_Ticket) {
				if ($_SWIFT->Staff->GetPermission('staff_tcanupdatebilling') != '0') {
					$_renderedHTML .= '<a href="javascript: void(0);" onclick="javascript: UICreateWindow(\'' . SWIFT::Get('basename') . '/Tickets/Ticket/EditBilling/' . $_SWIFT_InputObject->GetTicketID() . '/' . intval($_ticketTimeTrackID) . "', 'editbilling', '". $this->Language->Get('editbilling') ."', '". $this->Language->Get('loadingwindow') . '\', 650, 560, true, this);"><img src="' . SWIFT::Get('themepath') . 'images/icon_commentgray.gif' . '" align="absmiddle" border="0" /></a> ';
				}

				if ($_SWIFT->Staff->GetPermission('staff_tcandeletebilling') != '0') {
					$_renderedHTML .= '<a href="javascript: void(0);" onclick="javascript: TicketDeleteBilling(\'' . addslashes($this->Language->Get('ticketbillingdelconfirm')) . '\', \'' . intval($_SWIFT_InputObject->GetTicketID()) . '/' . intval($_ticketTimeTrackID) . '\');"><img src="' . SWIFT::Get('themepath') . 'images/icon_delete.gif' . '" align="absmiddle" border="0" /></a>';
				}
			}

			$_renderedHTML .= '</div></cite></div>';
		}

		$_renderedHTML .= '</div>';

		return $_renderedHTML;
	}

	/**
	 * Render the Forward Tab
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param SWIFT_User $_SWIFT_UserObject The User Object
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderForward(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject = null, $_listType, $_departmentID,
			$_ticketStatusID, $_ticketTypeID, $_ticketLimitOffset) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_ticketWatchContainer = SWIFT_TicketWatcher::RetrieveOnTicket($_SWIFT_TicketObject);

		$_ticketURLSuffix = SWIFT::Get('ticketurlsuffix');
		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_ForwardTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabforward'), '', 1, 'forward', false, false, 4, '');
		$_ForwardTabObject->SetColumnWidth('15%');
		$_ForwardTabObject->LoadToolbar();
		$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('dispatchsend'), 'icon_check.gif', '/Tickets/Ticket/ForwardSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);

		if ($_SWIFT->Staff->GetPermission('staff_tcaninsertticketnote') != '0') {
			$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('addnote'), 'icon_note.png', "\$('#forwardnotes').toggle(); \$('#forwardticketnotes').focus();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'forwardnotes');
		}

		$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('dispatchattachfile'), 'icon_file.gif', "\$('#forwardattachments').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'forwardattachments');

		if ($_SWIFT->Staff->GetPermission('staff_tcanfollowup') != '0') {
			$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('followup'), 'icon_followup.png', "\$('#forwardfollowup').toggle(); LoadFollowUp('forwardfollowup', '" . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix . '/fr/' . substr(BuildHash(), 6) . "');", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'forwardfollowup');
		}

		$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('options'), 'icon_settings2.gif', "\$('#forwardoptions').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'forwardoptions');
		$_ForwardTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$this->RenderDispatchTab(self::TAB_FORWARD, $_ForwardTabObject, $_SWIFT_TicketObject, $_SWIFT_UserObject, $_ticketWatchContainer);

		// Begin Hook: staff_ticket_forwardtab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_forwardtab')) ? eval($_hookCode) : false;
		// End Hook

		$_renderHTML = $_ForwardTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= '</script>';


		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Follow-Up Tab
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param SWIFT_User $_SWIFT_UserObject The User Object
	 * @param string $_prefix The ID Prefix Value
	 * @param string $_listType The List Type
	 * @param int $_departmentID The Department ID
	 * @param int $_ticketStatusID The Ticket Status ID
	 * @param int $_ticketTypeID The Ticket Type ID
	 * @param int $_ticketLimitOffset The offset to display ticket posts on
	 * @param int $_isInline Whether its an inline display
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderFollowUp(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject = null, $_prefix, $_listType, $_departmentID,
			$_ticketStatusID, $_ticketTypeID, $_ticketLimitOffset, $_isInline) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_ticketURLSuffix = $_listType . '/' . $_departmentID . '/' . $_ticketStatusID . '/' . $_ticketTypeID;

		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');

		$_ticketStatusContainer = false;
		if (isset($_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')])) {
			$_ticketStatusContainer = $_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')];
		}

		$_ticketPriorityContainer = false;
		if (isset($_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')])) {
			$_ticketPriorityContainer = $_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')];
		}

		$_titleBackgroundColor = '#626262';
		if ($_ticketStatusContainer) {
			$_titleBackgroundColor = $_ticketStatusContainer['statusbgcolor'];
		}

		$_priorityBackgroundColor = false;
		if ($_ticketPriorityContainer && isset($_ticketPriorityContainer['bgcolorcode']) && !empty($_ticketPriorityContainer['bgcolorcode'])) {
			$_priorityBackgroundColor = $_ticketPriorityContainer['bgcolorcode'];
		}

		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_FollowUpTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabfollowup'), '', 1, 'followup', false, false, 0, '');
		$_FollowUpTabObject->SetColumnWidth('8%');

		if ($_isInline == false) {
			$_FollowUpTabObject->LoadToolbar();
			$_FollowUpTabObject->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif', '/Tickets/Ticket/FollowUpSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);
			$_FollowUpTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
					SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

			if ($_SWIFT_TicketObject->GetProperty('hasfollowup') == '1') {
				$_FollowUpTabObject->RowHTML('<tr><td>' . $this->RenderFollowUpEntries($_SWIFT_TicketObject) . '</td></tr>');
			}
		}

		$_selectorHTML = '<select class="swiftselect" name="' . $_prefix . 'followuptype" onChange="javascript: FollowUpTrigger(this, \'' . $_prefix . '\');">';
		$_selectorHTML .= '<option value="minutes">' . $this->Language->Get('followupmins') . '</option><option value="hours" selected>' . $this->Language->Get('followuphours') . '</option><option value="days">' . $this->Language->Get('followupdays') . '</option><option value="weeks">' . $this->Language->Get('followupweeks') . '</option><option value="months">' . $this->Language->Get('followupmonths') . '</option><option value="custom">' . $this->Language->Get('followupcustom') . '</option></select><div id="' . $_prefix . 'followupblock" style="display: inline; padding-left: 6px;"><input type="text" name="' . $_prefix . 'followupvalue" class="swifttext" id="' . $_prefix . 'followupvalue" value="" size="4" /></div>';

		$_columnContainer = array();
		$_columnContainer[0]['align'] = 'left';
		$_columnContainer[0]['valign'] = 'top';
		$_columnContainer[0]['nowrap'] = true;
		$_columnContainer[0]['value'] = $_selectorHTML;

		$_FollowUpTabObject->Row($_columnContainer, '', '');
		$_FollowUpTabObject->RowHTML('<tr><td><div id="' . $_prefix . 'followupcustomvaluecontainer' . '" style="DISPLAY: none;"><table width="100%" border="0" cellspacing="0" cellpadding="0">');
		$_FollowUpTabObject->Date($_prefix . 'followupcustomvalue', $this->Language->Get('date'), '', '', DATENOW, true, true);
		$_FollowUpTabObject->RowHTML('</table></div></td></tr>');

		// Begin Properties
		$_FollowUpTabObject->Title('<label for="' . $_prefix . 'dochangeproperties"><input type="checkbox" name="' . $_prefix . 'dochangeproperties" onclick="javascript: ToggleTicketFollowUpCheckbox(this);" value="1" id="' . $_prefix . 'dochangeproperties" /> ' . $this->Language->Get('fugeneral') . '</label>');
		$_FollowUpTabObject->RowHTML('<tr><td><div id="' . $_prefix . 'dochangeproperties_container' . '" style="DISPLAY: none;"><table width="100%" border="0" cellspacing="0" cellpadding="0">');

		$_dividerHTML = '<div class="ticketfupropertiesdivider"><img src="' . SWIFT::Get('themepathimages') . 'ticketpropertiesdivider.png" align="middle" border="0" /></div>';
		$_renderHTML = '<tr><td colspan="2"><div class="ticketfucontainer">';
		$_renderHTML .= '<div class="ticketfuproperties" id="' . $_prefix . 'ticketproperties" style="background-color: ' . htmlspecialchars($_titleBackgroundColor) . ';">';

		// Departments
		$_departmentSelectHTML = '<div class="ticketfupropertiesselect"><select id="' . $_prefix . '_departmentid" name="' . $_prefix . 'departmentid" class="swiftselect" onchange="javascript: UpdateTicketStatusDiv(this, \'' . $_prefix . 'ticketstatusid\', false, false, \'' . $_prefix . 'ticketproperties\'); UpdateTicketTypeDiv(this, \'' . $_prefix . 'tickettypeid\', false, false); UpdateTicketOwnerDiv(this, \'' . $_prefix . 'ownerstaffid\', false, false);" style="max-width:160px;">';
		$_departmentSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_DEPARTMENT);
		$_departmentSelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketfupropertiesobject"><div class="ticketfupropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div>' . $_departmentSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Owner
		$_ownerSelectHTML = '<div class="ticketfupropertiesselect"><div id="' . $_prefix . 'ownerstaffid_container"><select id="select' . $_prefix . 'ownerstaffid" name="' . $_prefix . 'ownerstaffid" class="swiftselect" style="max-width:160px;">';
		$_ownerSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_OWNER);
		$_ownerSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketfupropertiesobject"><div class="ticketfupropertiestitle">' . $this->Language->Get('proptitleowner') . '</div>' . $_ownerSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Type
		$_ticketTypeSelectHTML = '<div class="ticketfupropertiesselect"><div id="' . $_prefix . 'tickettypeid_container"><select id="select' . $_prefix . 'tickettypeid" name="' . $_prefix . 'tickettypeid" class="swiftselect" style="max-width:160px;">';
		$_ticketTypeSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_TYPE);
		$_ticketTypeSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketfupropertiesobject"><div class="ticketfupropertiestitle">' . $this->Language->Get('proptitletype') . '</div>' . $_ticketTypeSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Status
		$_ticketStatusSelectHTML = '<div class="ticketfupropertiesselect"><div id="' . $_prefix . 'ticketstatusid_container"><select id="select' . $_prefix . 'ticketstatusid" onchange="javascript: ResetStatusParentColor(this, \'' . $_prefix . 'ticketproperties\');" name="' . $_prefix . 'ticketstatusid" class="swiftselect" style="max-width:160px;">';
		$_ticketStatusSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_STATUS);
		$_ticketStatusSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketfupropertiesobject"><div class="ticketfupropertiestitle">' . $this->Language->Get('proptitlestatus') . '</div>' . $_ticketStatusSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Priority
		$_ticketPrioritySelectHTML = '<div class="ticketfupropertiesselect"><select id="' . $_prefix . '_ticketpriorityid" name="' . $_prefix . 'ticketpriorityid" class="swiftselect" onchange="javascript: ResetPriorityParentColor(this, \'' . $_prefix . 'priorityproperties\');" style="max-width:160px;">';
		$_ticketPrioritySelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_PRIORITY);
		$_ticketPrioritySelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketfupropertiesobject" id="' . $_prefix . 'priorityproperties"' . IIF(!empty($_priorityBackgroundColor), ' style="background-color: ' . htmlspecialchars($_priorityBackgroundColor) . ';"') . '><div class="ticketfupropertiestitle">' . $this->Language->Get('proptitlepriority') . '</div>' . $_ticketPrioritySelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		$_renderHTML .= '</div>';

		$_renderHTML .= '</div></td></tr>';

		$_FollowUpTabObject->RowHTML($_renderHTML);
		$_FollowUpTabObject->RowHTML('</table></div></td></tr>');



		// Add Note
		$_FollowUpTabObject->Title('<label for="' . $_prefix . 'donote"><input type="checkbox" name="' . $_prefix . 'donote" onclick="javascript: ToggleTicketFollowUpCheckbox(this);" value="1" id="' . $_prefix . 'donote" /> ' . $this->Language->Get('fuaddnote') . '</label>');

		$_FollowUpTabObject->RowHTML('<tr><td><div id="' . $_prefix . 'donote_container' . '" style="DISPLAY: none;"><table width="100%" border="0" cellspacing="0" cellpadding="4">');

		$_FollowUpTabObject->Notes($_prefix . 'ticketnotes', $this->Language->Get('addnotes'), '', 1);

		$_radioContainer = array();
		$_radioContainer[0]['title'] = $this->Language->Get('notes_ticket');
		$_radioContainer[0]['value'] = 'ticket';
		$_radioContainer[0]['checked'] = true;

		if ($_SWIFT->Staff->GetPermission('staff_caninsertusernote') != '0' && $_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
			$_radioContainer[1]['title'] = $this->Language->Get('notes_user');
			$_radioContainer[1]['value'] = 'user';

			$_radioContainer[2]['title'] = $this->Language->Get('notes_userorganization');
			$_radioContainer[2]['value'] = 'userorganization';
		}

		$_FollowUpTabObject->Radio($_prefix . 'notetype', $this->Language->Get('notetype'), '', $_radioContainer, false);

		$_FollowUpTabObject->RowHTML('</table></div></td></tr>');




		// Post Reply
		$_FollowUpTabObject->Title('<label for="' . $_prefix . 'doreply"><input type="checkbox" name="' . $_prefix . 'doreply" onclick="javascript: ToggleTicketFollowUpCheckbox(this);" value="1" id="' . $_prefix . 'doreply" /> ' . $this->Language->Get('fupostreply') . '</label>');
		$_FollowUpTabObject->RowHTML('<tr><td><div id="' . $_prefix . 'doreply_container' . '" style="DISPLAY: none;"><table width="100%" border="0" cellspacing="0" cellpadding="4">');
		$_FollowUpTabObject->TextArea($_prefix . 'replycontents', '', '', '', '30', '10', false, '');
		$_FollowUpTabObject->RowHTML('</table></div></td></tr>');




		// Forward
		$_FollowUpTabObject->Title('<label for="' . $_prefix . 'doforward"><input type="checkbox" name="' . $_prefix . 'doforward" onclick="javascript: ToggleTicketFollowUpCheckbox(this);" value="1" id="' . $_prefix . 'doforward" /> ' . $this->Language->Get('fuforward') . '</label>');
		$_FollowUpTabObject->RowHTML('<tr><td><div id="' . $_prefix . 'doforward_container' . '" style="DISPLAY: none;"><table width="100%" border="0" cellspacing="0" cellpadding="4">');
    	$_FollowUpTabObject->TextMultipleAutoComplete($_prefix . 'to', $this->Language->Get('dispatchto'), '(Email will be sent to first recipient only).', '/Tickets/Ajax/SearchEmail', array(), 'icon_email.gif', false, false, 2, false, false, false, '', array('containemail' => true));
		$_FollowUpTabObject->TextArea($_prefix . 'forwardcontents', '', '', '', '30', '10', false, '');
		$_FollowUpTabObject->RowHTML('</table></div></td></tr>');

		// Begin Hook: staff_ticket_followuptab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_followuptab')) ? eval($_hookCode) : false;
		// End Hook


		$_renderHTML = $_FollowUpTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= 'QueueFunction(function() {';
		$_renderHTML .= ' $("#relbillingtimeworked").mask("99:99");';
		$_renderHTML .= ' $("#relbillingtimebillable").mask("99:99");';
		$_renderHTML .= '}); reParseDoc();';
		$_renderHTML .= '</script>';

		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Follow-Up Entries
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer
	 * @return string Rendered HTML
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	protected function RenderFollowUpEntries(SWIFT_Ticket $_SWIFT_TicketObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_staffCache = $this->Cache->Get('staffcache');
		$_departmentCache = $this->Cache->Get('departmentcache');
		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketTypeCache = $this->Cache->Get('tickettypecache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');

		$_ticketFollowUpContainer = SWIFT_TicketFollowUp::RetrieveOnTicket($_SWIFT_TicketObject);
		if (!count($_ticketFollowUpContainer)) {
			return '';
		}

		$_finalHTML = '<ol id="followuplist" class="followuplist"><div>';

		foreach ($_ticketFollowUpContainer as $_ticketFollowUpID => $_SWIFT_TicketFollowUpObject) {
			$_staffName = $this->Language->Get('na');
			if (isset($_staffCache[$_SWIFT_TicketFollowUpObject->GetProperty('staffid')])) {
				$_staffName = htmlspecialchars($_staffCache[$_SWIFT_TicketFollowUpObject->GetProperty('staffid')]['fullname']);
			}

			$_deleteHTML = '';
			if ($_SWIFT->Staff->GetPermission('staff_tcandeletefollowup') != '0') {
				$_deleteHTML = '<a href="javascript: void(0);" onclick="javascript: doConfirmViewport(\''. addslashes($this->Language->Get('actionconfirm')) .'\', \''. SWIFT::Get('basename') . '/Tickets/Ticket/DeleteFollowUp/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketFollowUpObject->GetTicketFollowUpID() . '\');"><img src="' . SWIFT::Get('themepath') . 'images/icon_delete.gif' . '" align="absmiddle" border="0" /></a>';
			}

			$_finalHTML .= '<li>';
			$_finalHTML .= '<div><b>' . sprintf($this->Language->Get('followup_willrunattime'),
					SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_SWIFT_TicketFollowUpObject->GetProperty('executiondateline')),
					$_staffName,
					SWIFT_Date::ColorTime($_SWIFT_TicketFollowUpObject->GetProperty('executiondateline')-DATENOW, true)) . '</b>&nbsp;&nbsp;' . $_deleteHTML . '';
			$_finalHTML .= '<ul>';

			if ($_SWIFT_TicketFollowUpObject->GetProperty('dochangeproperties') == '1') {
				if (isset($_departmentCache[$_SWIFT_TicketFollowUpObject->GetProperty('departmentid')])) {
					$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willchangedepartmentto'), htmlspecialchars($_departmentCache[$_SWIFT_TicketFollowUpObject->GetProperty('departmentid')]['title'])) . '</li>';
				}

				if (isset($_staffCache[$_SWIFT_TicketFollowUpObject->GetProperty('ownerstaffid')])) {
					$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willchangeownerto'), htmlspecialchars($_staffCache[$_SWIFT_TicketFollowUpObject->GetProperty('ownerstaffid')]['fullname'])) . '</li>';
				} else if ($_SWIFT_TicketFollowUpObject->GetProperty('ownerstaffid') == '0') {
					$_finalHTML .= '<li>' . $this->Language->Get('followup_removeowner') . '</li>';
				}

				if (isset($_ticketTypeCache[$_SWIFT_TicketFollowUpObject->GetProperty('tickettypeid')])) {
					$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willchangetypeto'), htmlspecialchars($_ticketTypeCache[$_SWIFT_TicketFollowUpObject->GetProperty('tickettypeid')]['title'])) . '</li>';
				}

				if (isset($_ticketStatusCache[$_SWIFT_TicketFollowUpObject->GetProperty('ticketstatusid')])) {
					$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willchangestatusto'), htmlspecialchars($_ticketStatusCache[$_SWIFT_TicketFollowUpObject->GetProperty('ticketstatusid')]['title'])) . '</li>';
				}

				if (isset($_ticketPriorityCache[$_SWIFT_TicketFollowUpObject->GetProperty('priorityid')])) {
					$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willchangepriorityto'), htmlspecialchars($_ticketPriorityCache[$_SWIFT_TicketFollowUpObject->GetProperty('priorityid')]['title'])) . '</li>';
				}
			}

			if ($_SWIFT_TicketFollowUpObject->GetProperty('donote') == '1') {
				if ($_SWIFT_TicketFollowUpObject->GetProperty('notetype') == 'ticket') {
					$_finalHTML .= '<li>' . $this->Language->Get('followup_willaddstaffnotes') . '</li>';
				} else {
					$_finalHTML .= '<li>' . $this->Language->Get('followup_willaddusernotes') . '</li>';
				}
			}

			if ($_SWIFT_TicketFollowUpObject->GetProperty('doreply') == '1') {
				$_finalHTML .= '<li>' . $this->Language->Get('followup_willaddareply') . '</li>';
			}

			if ($_SWIFT_TicketFollowUpObject->GetProperty('doforward') == '1') {
				$_finalHTML .= '<li>' . sprintf($this->Language->Get('followup_willforwardto'), htmlspecialchars($_SWIFT_TicketFollowUpObject->GetProperty('forwardemailto'))) . '</li>';
			}

			$_finalHTML .= '</ul></li>';
		}

		$_finalHTML .= '</div></ol>';

		return $_finalHTML;
	}

	/**
	 * Render the Release Tab
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param SWIFT_User $_SWIFT_UserObject The User Object
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderRelease(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject = null, $_listType, $_departmentID,
			$_ticketStatusID, $_ticketTypeID, $_ticketLimitOffset) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_ticketURLSuffix = $_listType . '/' . $_departmentID . '/' . $_ticketStatusID . '/' . $_ticketTypeID;

		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');

		$_ticketStatusContainer = false;
		if (isset($_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')])) {
			$_ticketStatusContainer = $_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')];
		}

		$_ticketPriorityContainer = false;
		if (isset($_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')])) {
			$_ticketPriorityContainer = $_ticketPriorityCache[$_SWIFT_TicketObject->GetProperty('priorityid')];
		}

		$_titleBackgroundColor = '#626262';
		if ($_ticketStatusContainer) {
			$_titleBackgroundColor = $_ticketStatusContainer['statusbgcolor'];
		}

		$_priorityBackgroundColor = false;
		if ($_ticketPriorityContainer && isset($_ticketPriorityContainer['bgcolorcode']) && !empty($_ticketPriorityContainer['bgcolorcode'])) {
			$_priorityBackgroundColor = $_ticketPriorityContainer['bgcolorcode'];
		}

		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_ReleaseTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabrelease'), '', 1, 'release', false, false, 4, '');
		$_ReleaseTabObject->SetColumnWidth('15%');
		$_ReleaseTabObject->LoadToolbar();
		$_ReleaseTabObject->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif', '/Tickets/Ticket/ReleaseSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);
		$_ReleaseTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		// Begin Properties
		$_dividerHTML = '<div class="ticketreleasepropertiesdivider"><img src="' . SWIFT::Get('themepathimages') . 'ticketpropertiesdivider.png" align="middle" border="0" /></div>';
		$_renderHTML = '<tr><td colspan="2"><div class="ticketreleasecontainer">';
		$_renderHTML .= '<div class="ticketreleaseproperties" id="releaseticketproperties" style="background-color: ' . htmlspecialchars($_titleBackgroundColor) . ';">';

		// Departments
		$_departmentSelectHTML = '<div class="ticketreleasepropertiesselect"><select id="release_departmentid" name="reldepartmentid" class="swiftselect" onchange="javascript: UpdateTicketStatusDiv(this, \'relticketstatusid\', false, false, \'releaseticketproperties\'); UpdateTicketTypeDiv(this, \'reltickettypeid\', false, false); UpdateTicketOwnerDiv(this, \'relownerstaffid\', false, false);" style="max-width:160px">';
		$_departmentSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_DEPARTMENT);
		$_departmentSelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketreleasepropertiesobject"><div class="ticketreleasepropertiestitle">' . $this->Language->Get('proptitledepartment') . '</div>' . $_departmentSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Owner
		$_ownerSelectHTML = '<div class="ticketreleasepropertiesselect"><div id="relownerstaffid_container"><select id="selectrelownerstaffid" name="relownerstaffid" class="swiftselect" style="max-width:160px">';
		$_ownerSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_OWNER);
		$_ownerSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreleasepropertiesobject"><div class="ticketreleasepropertiestitle">' . $this->Language->Get('proptitleowner') . '</div>' . $_ownerSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Type
		$_ticketTypeSelectHTML = '<div class="ticketreleasepropertiesselect"><div id="reltickettypeid_container"><select id="selectreltickettypeid" name="reltickettypeid" class="swiftselect" style="max-width:160px">';
		$_ticketTypeSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_TYPE);
		$_ticketTypeSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreleasepropertiesobject"><div class="ticketreleasepropertiestitle">' . $this->Language->Get('proptitletype') . '</div>' . $_ticketTypeSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Status
		$_ticketStatusSelectHTML = '<div class="ticketreleasepropertiesselect"><div id="relticketstatusid_container"><select id="selectrelticketstatusid" onchange="javascript: ResetStatusParentColor(this, \'releaseticketproperties\');" name="relticketstatusid" class="swiftselect" style="max-width:160px">';
		$_ticketStatusSelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_STATUS);
		$_ticketStatusSelectHTML .= '</select></div></div>';

		$_renderHTML .= '<div class="ticketreleasepropertiesobject"><div class="ticketreleasepropertiestitle">' . $this->Language->Get('proptitlestatus') . '</div>' . $_ticketStatusSelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		// Priority
		$_ticketPrioritySelectHTML = '<div class="ticketreleasepropertiesselect"><select id="rel_ticketpriorityid" name="relticketpriorityid" class="swiftselect" onchange="javascript: ResetPriorityParentColor(this, \'releasepriorityproperties\');" style="max-width:160px">';
		$_ticketPrioritySelectHTML .= $this->GetSelectOptions($_SWIFT_TicketObject, self::TYPE_PRIORITY);
		$_ticketPrioritySelectHTML .= '</select></div>';

		$_renderHTML .= '<div class="ticketreleasepropertiesobject" id="releasepriorityproperties"' . IIF(!empty($_priorityBackgroundColor), ' style="background-color: ' . htmlspecialchars($_priorityBackgroundColor) . ';"') . '><div class="ticketreleasepropertiestitle">' . $this->Language->Get('proptitlepriority') . '</div>' . $_ticketPrioritySelectHTML . '</div>';
		$_renderHTML .= $_dividerHTML;

		$_renderHTML .= '</div>';

		$_renderHTML .= '</div></td></tr>';

		$_ReleaseTabObject->RowHTML($_renderHTML);

		// Tags
		if ($_SWIFT->Staff->GetPermission('staff_canupdatetags') != '0') {
			$_ticketTagContainer = SWIFT_Tag::GetTagList(SWIFT_TagLink::TYPE_TICKET, $_SWIFT_TicketObject->GetTicketID());
			$_ReleaseTabObject->TextMultipleAutoComplete('reltags', false, false, '/Base/Tags/QuickSearch', $_ticketTagContainer, 'icon_taginput.png', 'gridrow2', true, 2, false, true);
		}

		// Notes
		$_ReleaseTabObject->Notes('releaseticketnotes', $this->Language->Get('addnotes'), '', 1);

		$_radioContainer = array();
		$_radioContainer[0]['title'] = $this->Language->Get('notes_ticket');
		$_radioContainer[0]['value'] = 'ticket';
		$_radioContainer[0]['checked'] = true;

		if ($_SWIFT->Staff->GetPermission('staff_caninsertusernote') != '0' && $_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
			$_radioContainer[1]['title'] = $this->Language->Get('notes_user');
			$_radioContainer[1]['value'] = 'user';

			$_radioContainer[2]['title'] = $this->Language->Get('notes_userorganization');
			$_radioContainer[2]['value'] = 'userorganization';
		}

		$_ReleaseTabObject->Radio('releasenotetype', $this->Language->Get('notetype'), '', $_radioContainer, false);


		// Options
		$_ReleaseTabObject->Title($this->Language->Get('options'), 'doublearrows.gif');

		$_dueDateline           = $_SWIFT_TicketObject->GetProperty('duetime');
		$_resolutionDueDateline = $_SWIFT_TicketObject->GetProperty('resolutionduedateline');

		if (!empty($_dueDateline)) {
			$_dueDateline = strtotime(SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_dueDateline));
		}

		if (!empty($_resolutionDueDateline)) {
			$_resolutionDueDateline = strtotime(SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_resolutionDueDateline));
		}

		$_dueDate           = IIF(!empty($_dueDateline), date(SWIFT_Date::GetCalendarDateFormat(), $_dueDateline), '');
		$_resolutionDueDate = IIF(!empty($_resolutionDueDateline), date(SWIFT_Date::GetCalendarDateFormat(), $_resolutionDueDateline), '');

		$_ReleaseTabObject->Date('releasedue', $this->Language->Get('dialogduetimeline'), '', $_dueDate, $_dueDateline, true);
		$_ReleaseTabObject->Date('releaseresolutiondue', $this->Language->Get('dialogresolutionduetimeline'), '', $_resolutionDueDate, $_resolutionDueDateline, true);

		$_billingEntriesHTML = $this->Language->Get('billworked') . ' <input type="text" class="swifttextnumeric2" name="relbillingtimeworked" id="relbillingtimeworked" value="" size="5" />';
		$_billingEntriesHTML .= '&nbsp;&nbsp;&nbsp;' . $this->Language->Get('billbillable') . ' <input type="text" class="swifttextnumeric2" name="relbillingtimebillable" id="relbillingtimebillable" value="" onfocus="javascript: HandleBillingBillableFocus(this, \'rel\');" size="5" />';
		$_ReleaseTabObject->DefaultDescriptionRow($this->Language->Get('billtimespent'), '', $_billingEntriesHTML);

		// Begin Hook: staff_ticket_releasetab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_releasetab')) ? eval($_hookCode) : false;
		// End Hook

		$_renderHTML = $_ReleaseTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= 'QueueFunction(function() {';
		$_renderHTML .= ' $("#relbillingtimeworked").mask("99:99");';
		$_renderHTML .= ' $("#relbillingtimebillable").mask("99:99");';
		$_renderHTML .= '}); reParseDoc();';
		$_renderHTML .= '</script>';

		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the History
	 *
	 * @author Varun Shoor
	 * @param mixed $_SWIFT_BaseObject The Ticket/User Object
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderHistory($_SWIFT_BaseObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_departmentCache = $_SWIFT->Cache->Get('departmentcache');
		$_ticketStatusCache = $_SWIFT->Cache->Get('statuscache');
		$_ticketPriorityCache = $_SWIFT->Cache->Get('prioritycache');
		$_ticketTypeCache = $_SWIFT->Cache->Get('tickettypecache');

		$_historyContainer = array();
		if ($_SWIFT_BaseObject instanceof SWIFT_Ticket && $_SWIFT_BaseObject->GetIsClassLoaded()) {
			$_historyContainer = $_SWIFT_BaseObject->RetrieveHistory();
		} else if ($_SWIFT_BaseObject instanceof SWIFT_User && $_SWIFT_BaseObject->GetIsClassLoaded()) {
			$_historyContainer = SWIFT_Ticket::RetrieveHistoryOnUser($_SWIFT_BaseObject);
		} else if (is_array($_SWIFT_BaseObject)) {
			$_historyContainer = SWIFT_Ticket::RetrieveHistoryOnUser(false, $_SWIFT_BaseObject);
		} else {
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);
		}

		$_renderHTML = '<table width="100%" cellspacing="0" cellpadding="4" border="0">';
		$_renderHTML .= '<tbody><tr class=""><td valign="middle" align="left" class="gridtabletitlerow" width="16">&nbsp;</td><td valign="middle" align="left" class="gridtabletitlerow" width="120">' . $this->Language->Get('history_ticketid') . '</td><td valign="middle" align="left" class="gridtabletitlerow">' . $this->Language->Get('history_subject') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="160">' . $this->Language->Get('history_date') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="120">' . $this->Language->Get('history_department') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="90">' . $this->Language->Get('history_type') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="100">' . $this->Language->Get('history_status') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="90">' . $this->Language->Get('history_priority') . '</td></tr>';

		$_historyCount = 0;
		foreach ($_historyContainer as $_ticketID => $_TicketObject_History) {
			if ($_SWIFT_BaseObject instanceof SWIFT_Ticket && $_ticketID == $_SWIFT_BaseObject->GetTicketID()) {
				continue;
			}

			$_historyCount++;

			$_ticketURL = $_ticketURLPrefix = $_ticketURLSuffix = $_departmentHTML = $_typeHTML = $_statusHTML = $_priorityHTML = $_statusStyle = $_priorityStyle = '';

			$_ticketIcon = 'icon_ticket.png';
			if (!$_TicketObject_History->CanAccess($_SWIFT->Staff)) {
				$_ticketIcon = 'icon_lock.gif';
			} else {
				$_ticketURL = SWIFT::Get('basename') . '/Tickets/Ticket/View/' . intval($_TicketObject_History->GetTicketID());
				$_ticketURLPrefix = '<a href="' . $_ticketURL . '" viewport="1">';
				$_ticketURLSuffix = '</a>';
			}
			$_ticketIconHTML = '<img src="' . SWIFT::Get('themepath') . 'images/' . $_ticketIcon . '" align="absmiddle" border="0" />';

			// Department
			if (isset($_departmentCache[$_TicketObject_History->GetProperty('departmentid')])) {
				$_departmentHTML = htmlspecialchars(StripName($_departmentCache[$_TicketObject_History->GetProperty('departmentid')]['title'], 15));
			} else {
				$_departmentHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Status
			if (isset($_ticketStatusCache[$_TicketObject_History->GetProperty('ticketstatusid')])) {
				$_ticketStatusContainer = $_ticketStatusCache[$_TicketObject_History->GetProperty('ticketstatusid')];
				$_displayIconImage = '';
				if (!empty($_ticketStatusContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketStatusContainer['displayicon']) .
							'" align="absmiddle" border="0" /> ';
				}

				$_statusHTML = $_displayIconImage . htmlspecialchars(StripName($_ticketStatusContainer['title'], 15));
				$_statusStyle = 'background-color: ' . $_ticketStatusContainer['statusbgcolor'] . '; color: ' .
						$_ticketStatusContainer['statuscolor'];
			} else {
				$_statusHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Priority
			if (isset($_ticketPriorityCache[$_TicketObject_History->GetProperty('priorityid')])) {
				$_ticketPriorityContainer = $_ticketPriorityCache[$_TicketObject_History->GetProperty('priorityid')];
				$_displayIconImage = '';
				if (!empty($_ticketPriorityContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketPriorityContainer['displayicon']) .
							'" align="absmiddle" border="0" /> ';
				}

				$_priorityHTML = $_displayIconImage . htmlspecialchars(StripName($_ticketPriorityContainer['title'], 15));
				$_priorityStyle = 'background-color: ' . $_ticketPriorityContainer['bgcolorcode'] . '; color: ' .
						$_ticketPriorityContainer['frcolorcode'] . ';';
			} else {
				$_priorityHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Type
			if (isset($_ticketTypeCache[$_TicketObject_History->GetProperty('tickettypeid')])) {
				$_ticketTypeContainer = $_ticketTypeCache[$_TicketObject_History->GetProperty('tickettypeid')];
				$_displayIconImage = '';
				if (!empty($_ticketTypeContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketTypeContainer['displayicon']) .
							'" align="absmiddle" border="0" /> ';
				}

				$_typeHTML = $_displayIconImage . htmlspecialchars(StripName($_ticketTypeContainer['title'], 15));
			} else {
				$_typeHTML = $_SWIFT->Language->Get('na');
			}

			$_renderHTML .= '<tr class="tablerow1_tr"><td valign="middle" align="center" class="tablerow1">' . $_ticketIconHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_ticketURLPrefix . $_TicketObject_History->GetTicketDisplayID() . $_ticketURLSuffix . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_ticketURLPrefix . htmlspecialchars($_TicketObject_History->GetProperty('subject')) . $_ticketURLSuffix . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1" width="220">' . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_TicketObject_History->GetProperty('dateline')) . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_departmentHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_typeHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_statusHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1" style="' . $_priorityStyle . '">' . $_priorityHTML . '</td>';
			$_renderHTML .= '</tr>';
		}

		if ($_historyCount == 0) {
			$_renderHTML .= '<tr class="tablerow1_tr"><td valign="middle" align="left" class="tablerow1" colspan="8">' . $this->Language->Get('noinfoinview') . '</td></tr>';
		}

		$_renderHTML .= '</tbody></table>';

		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Audit Log
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderAuditLog(SWIFT_Ticket $_SWIFT_TicketObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_auditLogContainer = SWIFT_TicketAuditLog::RetrieveOnTicket($_SWIFT_TicketObject);

		$_renderHTML = '<table width="100%" cellspacing="0" cellpadding="4" border="0">';
		$_renderHTML .= '<tbody><tr class=""><td valign="middle" align="left" class="gridtabletitlerow">' . $this->Language->Get('aldescription') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="220">' . $this->Language->Get('alentrytype') . '</td></tr>';

		foreach ($_auditLogContainer as $_actionHash => $_hashContainer) {
			$_diffSeconds = DATENOW - $_hashContainer['dateline'];

			$_renderHTML .= '<tr class="tabletitlerowtitle"><td valign="middle" align="left" class="tabletitlerowtitle" colspan="2"><b>' . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_hashContainer['dateline']) . ' - </b>' . SWIFT_Date::ColorTime($_diffSeconds) . '</td></tr>';
			foreach ($_hashContainer['items'] as $_ticketAuditLogID => $_logContainer) {

				$_creatorText = $_logContainer['creatorfullname'];
				if ($_logContainer['creatortype'] == SWIFT_TicketAuditLog::CREATOR_STAFF) {
					$_creatorText .= $this->Language->Get('alstaff');
				} else if ($_logContainer['creatortype'] == SWIFT_TicketAuditLog::CREATOR_USER) {
					$_creatorText .= $this->Language->Get('aluser');
				} else if ($_logContainer['creatortype'] == SWIFT_TicketAuditLog::CREATOR_SYSTEM) {
					$_creatorText .= $this->Language->Get('alsystem');
				} else if ($_logContainer['creatortype'] == SWIFT_TicketAuditLog::CREATOR_PARSER) {
					$_creatorText .= $this->Language->Get('alparser');
				}

				$_renderHTML .= '<tr class="tablerow1_tr"><td valign="middle" align="left" class="tablerow1">' . htmlspecialchars($_logContainer['actionmsg']) . '</td><td valign="middle" align="left" class="tablerow1">' . htmlspecialchars($_creatorText) . '</td></tr>';
			}
		}

		$_renderHTML .= '</tbody></table>';

		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Edit Tab
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The Ticket Object
	 * @param string $_listType (OPTIONAL) The List Type
	 * @param int $_departmentID (OPTIONAL) The Department ID
	 * @param int $_ticketStatusID (OPTIONAL) The Ticket Status ID
	 * @param int $_ticketTypeID (OPTIONAL) The Ticket Type ID
	 * @param int $_ticketLimitOffset (OPTIONAL) The offset to display ticket posts on
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderEdit(SWIFT_Ticket $_SWIFT_TicketObject, $_listType, $_departmentID,
			$_ticketStatusID, $_ticketTypeID, $_ticketLimitOffset) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_slaPlanCache = $this->Cache->Get('slaplancache');

		$_ticketURLSuffix = $_listType . '/' . $_departmentID . '/' . $_ticketStatusID . '/' . $_ticketTypeID;

		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
		$_EditTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabedit'), '', 1, 'edit', false, false, 4, '');
		$_EditTabObject->SetColumnWidth('15%');
		$_EditTabObject->LoadToolbar();
		$_EditTabObject->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif', '/Tickets/Ticket/EditSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketURLSuffix, SWIFT_UserInterfaceToolbar::LINK_FORM);
		$_EditTabObject->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$this->Controller->CustomFieldRendererStaff->Render(SWIFT_CustomFieldRenderer::TYPE_FIELDS, SWIFT_UserInterface::MODE_EDIT,
				array(SWIFT_CustomFieldGroup::GROUP_STAFFTICKET, SWIFT_CustomFieldGroup::GROUP_USERTICKET, SWIFT_CustomFieldGroup::GROUP_STAFFUSERTICKET), $_EditTabObject,
				$_SWIFT_TicketObject->GetTicketID(), $_SWIFT_TicketObject->GetProperty('departmentid'));

		// Merge Ticket
		$_EditTabObject->Title($this->Language->Get('mergeoptions'), 'doublearrows.gif');
		$_EditTabObject->Text('mergeticketid', $this->Language->Get('mergeparentticket'), $this->Language->Get('desc_mergeparentticket'), '');

		// Ticket Properties
		$_EditTabObject->Title($this->Language->Get('edittproperties'), 'doublearrows.gif');

		$_EditTabObject->Text('editsubject', $this->Language->Get('edit_subject'), '', $_SWIFT_TicketObject->GetProperty('subject'));
		$_EditTabObject->Text('editfullname', $this->Language->Get('edit_fullname'), '', $_SWIFT_TicketObject->GetProperty('fullname'));

		$_ticketEmailAddress = $_SWIFT_TicketObject->GetProperty('email');
		if ($_SWIFT_TicketObject->GetProperty('replyto') != '')
		{
			$_ticketEmailAddress = $_SWIFT_TicketObject->GetProperty('replyto');
		}
		$_EditTabObject->Text('editemail', $this->Language->Get('edit_email'), '', $_ticketEmailAddress);

		$_optionsContainer = array();
		$_index = 1;
		$_optionsContainer[0]['title'] = $this->Language->Get('editslausedef');
		$_optionsContainer[0]['value'] = '0';

		if ($_SWIFT_TicketObject->GetProperty('ticketslaplanid') == '0') {
			$_optionsContainer[0]['selected'] = true;
		}

		foreach ($_slaPlanCache as $_slaPlanID => $_slaPlanContainer) {
			$_optionsContainer[$_index]['title'] = $_slaPlanContainer['title'];
			$_optionsContainer[$_index]['value'] = $_slaPlanID;

			if ($_SWIFT_TicketObject->GetProperty('ticketslaplanid') == $_slaPlanID) {
				$_optionsContainer[$_index]['selected'] = true;
			}

			$_index++;
		}

		$_EditTabObject->Select('editticketslaplanid', $this->Language->Get('edit_overridesla'), $this->Language->Get('desc_edit_overridesla'), $_optionsContainer);

		// Recipients
		$_EditTabObject->Title($this->Language->Get('edittrecipients'), 'doublearrows.gif');
		$_EditTabObject->Description($this->Language->Get('editrecipientsdesc'), '', 'tabledescriptionext', 2, true);

		$_recipientContainer = SWIFT_TicketRecipient::RetrieveOnTicket($_SWIFT_TicketObject);
		$_ccEmailContainer = $_bccEmailContainer = $_thirdPartyEmailContainer = array();

		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_THIRDPARTY])) {
			$_thirdPartyEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_THIRDPARTY];
		}

		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_CC])) {
			$_ccEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_CC];
		}

		if (isset($_recipientContainer[SWIFT_TicketRecipient::TYPE_BCC])) {
			$_bccEmailContainer = $_recipientContainer[SWIFT_TicketRecipient::TYPE_BCC];
		}

		$_EditTabObject->TextMultipleAutoComplete('editthirdparty', $this->Language->Get('editthirdparty'), '', false, $_thirdPartyEmailContainer, 'icon_email.gif', false, false, 2, false, false, false, '', array('containemail' => true));
		$_EditTabObject->TextMultipleAutoComplete('editcc', $this->Language->Get('editcc'), '', false, $_ccEmailContainer, 'icon_email.gif', false, false, 2, false, false, false, '', array('containemail' => true));
		$_EditTabObject->TextMultipleAutoComplete('editbcc', $this->Language->Get('editbcc'), '', false, $_bccEmailContainer, 'icon_email.gif', false, false, 2, false, false, false, '', array('containemail' => true));

		// Begin Hook: staff_ticket_edittab
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_edittab')) ? eval($_hookCode) : false;
		// End Hook

		$_renderHTML = $_EditTabObject->GetDisplayHTML(true);

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= '</script>';

		echo $_renderHTML;

		return true;
	}

	/**
	 * Render the Notes for the given Ticket (including his organization notes)
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object
	 * @param SWIFT_User $_SWIFT_UserObject (OPTIONAL) The SWIFT_User Object
	 * @return mixed "_renderedHTML" (STRING) on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded or If Invalid Data is Provided
	 */
	public function RenderNotes(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject = null) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		} else if (!$_SWIFT_TicketObject instanceof SWIFT_Ticket || !$_SWIFT_TicketObject->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);

			return false;
		}

		// Retrieve notes
		$_noteContainer = array();



		$_userNoteContainer = array();
		$_renderedHTML = '';

		// Fetch user notes
		if ($_SWIFT->Staff->GetPermission('staff_canviewusernotes') != '0' && $_SWIFT_UserObject instanceof SWIFT_User &&
				$_SWIFT_UserObject->GetIsClassLoaded()) {
			$this->Database->Query("SELECT usernotes.*, usernotedata.* FROM " . TABLE_PREFIX . "usernotes AS usernotes LEFT JOIN " . TABLE_PREFIX .
					"usernotedata AS usernotedata ON (usernotes.usernoteid = usernotedata.usernoteid) WHERE (usernotes.linktype = '" .
					SWIFT_UserNote::LINKTYPE_USER . "' AND usernotes.linktypeid = '" . intval($_SWIFT_UserObject->GetUserID()) .
					"') OR (usernotes.linktype = '" . SWIFT_UserNote::LINKTYPE_ORGANIZATION . "' AND usernotes.linktypeid = '" .
					intval($_SWIFT_UserObject->GetProperty('userorganizationid')) . "') ORDER BY usernotes.dateline DESC");
			while ($this->Database->NextRecord()) {
				$_noteKey = $this->Database->Record['dateline'] . '.' . $this->Database->Record['usernoteid'] . '.1';

				$_noteContainer[$_noteKey] = $this->Database->Record;

				$_noteContainer[$_noteKey][':customtype'] = 'user';
			}
		}

		// Fetch ticket notes
		if ($_SWIFT->Staff->GetPermission('staff_tcanviewticketnotes') != '0') {
			$this->Database->Query("SELECT * FROM " . TABLE_PREFIX . "ticketnotes WHERE linktype = '" . SWIFT_TicketNoteManager::LINKTYPE_TICKET .
					"' AND linktypeid = '" . intval($_SWIFT_TicketObject->GetTicketID()) . "'");
			while ($this->Database->NextRecord()) {
				if ($this->Database->Record['forstaffid'] != '0' && $this->Database->Record['forstaffid'] != $_SWIFT->Staff->GetStaffID() && $this->Database->Record['staffid'] != $_SWIFT->Staff->GetStaffID()) {
					continue;
				}

				$_noteKey = $this->Database->Record['dateline'] . '.' . $this->Database->Record['ticketnoteid'] . '.2';

				$_noteContainer[$_noteKey] = $this->Database->Record;

				$_noteContainer[$_noteKey][':customtype'] = 'ticket';
			}
		}

		// Sort the data
		ksort($_noteContainer);


		foreach ($_noteContainer as $_note) {
			$_icon = $_noteColor = $_noteContents = '';

			if ($_note[':customtype'] == 'user' && $_note['linktype'] == SWIFT_UserNote::LINKTYPE_USER) {
				$_icon = 'icon_user2.png';
				$_noteColor = SWIFT_UserNote::GetSanitizedNoteColor($_note['notecolor']);

				$_noteContents = $_note['notecontents'];
			} else if ($_note[':customtype'] == 'user' && $_note['linktype'] == SWIFT_UserNoteManager::LINKTYPE_ORGANIZATION) {
				$_icon = 'icon_userorganization.png';
				$_noteColor = SWIFT_UserNote::GetSanitizedNoteColor($_note['notecolor']);

				$_noteContents = $_note['notecontents'];
			} else if ($_note[':customtype'] == 'ticket' && $_note['linktype'] == SWIFT_TicketNote::LINKTYPE_TICKET) {
				$_icon = 'icon_ticket.png';
				$_noteColor = SWIFT_TicketNote::GetSanitizedNoteColor($_note['notecolor']);

				$_noteContents = $_note['note'];
			}

			$_renderedHTML .= '<div id="note' . intval($_noteColor) . '" class="bubble"><div class="notebubble"><blockquote><p>' .
					AutoLink(nl2br(htmlspecialchars($_noteContents))) . '</p></blockquote></div><cite class="tip"><strong><img src="' . SWIFT::Get('themepath') .
					'images/' . $_icon . '" align="absmiddle" border="0" /> ' . sprintf($this->Language->Get('notetitle'),
					htmlspecialchars($_note['staffname']), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_note['dateline']))
					. IIF(!empty($_note['editedstaffid']) && !empty($_note['editedstaffname']), sprintf($this->Language->Get('noteeditedtitle'),
					htmlspecialchars($_note['editedstaffname']), SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_note['editedtimeline'])))
					. '</strong><div style="float: right; padding-right: 4px;">';

			if ($_note[':customtype'] == 'ticket' && $_SWIFT->Staff->GetPermission('staff_tcanupdateticketnote') != '0') {
				$_renderedHTML .= '<a href="javascript: void(0);" onclick="javascript: UICreateWindow(\'' . SWIFT::Get('basename') . '/Tickets/Ticket/EditNote/' . $_SWIFT_TicketObject->GetTicketID() . '/' . intval($_note['ticketnoteid']) . "', 'editnote', '". $this->Language->Get('editnote') ."', '". $this->Language->Get('loadingwindow') . '\', 650, 350, true, this);"><img src="' . SWIFT::Get('themepath') . 'images/icon_commentgray.gif' . '" align="absmiddle" border="0" /></a> ';
			}

			if ($_note[':customtype'] == 'ticket' && $_SWIFT->Staff->GetPermission('staff_tcandeleteticketnote') != '0') {
				$_renderedHTML .= '<a href="javascript: void(0);" onclick="javascript: TicketDeleteNote(\'' . addslashes($this->Language->Get('ticketnotedelconfirm')) . '\', \'' . intval($_SWIFT_TicketObject->GetTicketID()) . '/' . intval($_note['ticketnoteid']) . '\');"><img src="' . SWIFT::Get('themepath') . 'images/icon_delete.gif' . '" align="absmiddle" border="0" /></a>';
			}

			$_renderedHTML .= '</div></cite></div>';
		}

		return $_renderedHTML;
	}

	/**
	 * Render the Add Note Dialog
	 *
	 * @author Varun Shoor
	 * @param int $_mode The Render Mode
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer
	 * @param SWIFT_TicketNote $_SWIFT_TicketNoteObject The SWIFT_TicketNote Object Poitner
	 * @param SWIFT_User $_SWIFT_UserObject The SWIFT_User Object Pointer
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderNoteForm($_mode, SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_TicketNoteObject = null,
			$_SWIFT_UserObject = null) {
		$_SWIFT = SWIFT::GetInstance();

		$_staffCache = $this->Cache->Get('staffcache');

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		// Calculate the URL
		if ($_mode == SWIFT_UserInterface::MODE_INSERT) {
			$this->UserInterface->Start('ticketaddnotes', '/Tickets/Ticket/AddNoteSubmit/' . $_SWIFT_TicketObject->GetTicketID(), SWIFT_UserInterface::MODE_EDIT, true, false, false, false, 'ticketnotescontainerdiv');
		} else {
			$this->UserInterface->Start('ticketaddnotes', '/Tickets/Ticket/EditNoteSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_SWIFT_TicketNoteObject->GetTicketNoteID(), SWIFT_UserInterface::MODE_EDIT, true, false, false, false, 'ticketnotescontainerdiv');
		}

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$_defaultNoteContents = '';
		$_defaultNoteColor = 1;
		if ($_SWIFT_TicketNoteObject instanceof SWIFT_TicketNote && $_SWIFT_TicketNoteObject->GetIsClassLoaded()) {
			$_defaultNoteContents = $_SWIFT_TicketNoteObject->GetProperty('note');
			$_defaultNoteColor = intval($_SWIFT_TicketNoteObject->GetProperty('notecolor'));
		}

		/*
		 * ###############################################
		 * BEGIN ADD NOTES TAB
		 * ###############################################
		*/

		$_AddNoteTabObject = $this->UserInterface->AddTab(IIF($_mode == SWIFT_UserInterface::MODE_INSERT, $this->Language->Get('tabaddnote'), $this->Language->Get('tabeditnote')), 'icon_note.png', 'addnote', true);

		$_AddNoteTabObject->Notes('ticketnotes', $this->Language->Get('addnotes'), $_defaultNoteContents, $_defaultNoteColor);

		if ($_mode == SWIFT_UserInterface::MODE_INSERT) {
			$_radioContainer = array();
			$_radioContainer[0]['title'] = $this->Language->Get('notes_ticket');
			$_radioContainer[0]['value'] = 'ticket';
			$_radioContainer[0]['checked'] = true;

			if ($_SWIFT->Staff->GetPermission('staff_caninsertusernote') != '0' && $_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
				$_radioContainer[1]['title'] = $this->Language->Get('notes_user');
				$_radioContainer[1]['value'] = 'user';

				$_radioContainer[2]['title'] = $this->Language->Get('notes_userorganization');
				$_radioContainer[2]['value'] = 'userorganization';
			}

			$_AddNoteTabObject->Radio('notetype', $this->Language->Get('notetype'), '', $_radioContainer, false, 'HandleTicketNoteRestriction();');



			$_optionsContainer = array();
			$_optionsContainer[0]['title'] = $this->Language->Get('notesvisibleall');
			$_optionsContainer[0]['value'] = '0';
			$_optionsContainer[0]['selected'] = true;

			$_index = 1;
			foreach ($_staffCache as $_staffID => $_staffContainer) {
				$_optionsContainer[$_index]['title'] = htmlspecialchars($_staffContainer['fullname']);
				$_optionsContainer[$_index]['value'] = $_staffID;

				$_index++;
			}

			$_AddNoteTabObject->Select('forstaffid', $this->Language->Get('notevisibleto'), $this->Language->Get('desc_notevisibleto'), $_optionsContainer);
		}


		/*
		 * ###############################################
		 * END ADD NOTES TAB
		 * ###############################################
		*/

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Retrieve the Options HTML for SELECT element
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer
	 * @param constant $_selectType The Select Type
	 * @param array $_extendedDataContainer
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded or If Invalid Data is Provided
	 */
	protected function GetSelectOptions($_SWIFT_TicketObject, $_selectType, $_extendedDataContainer = array()) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_exDepartmentID = $_exOwnerStaffID = $_exTicketTypeID = $_exTicketStatusID = $_exTicketPriorityID = false;

		extract($_extendedDataContainer);
		if (!$_SWIFT_TicketObject instanceof SWIFT_Ticket || !$_SWIFT_TicketObject->GetIsClassLoaded()) {
		} else if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
			if (!isset($_extendedDataContainer['_exDepartmentID'])) {
				$_exDepartmentID = $_SWIFT_TicketObject->GetProperty('departmentid');
			}

			if (!isset($_extendedDataContainer['_exOwnerStaffID'])) {
				$_exOwnerStaffID = $_SWIFT_TicketObject->GetProperty('ownerstaffid');
			}

			if (!isset($_extendedDataContainer['_exTicketTypeID'])) {
				$_exTicketTypeID = $_SWIFT_TicketObject->GetProperty('tickettypeid');
			}

			if (!isset($_extendedDataContainer['_exTicketStatusID'])) {
				$_exTicketStatusID = $_SWIFT_TicketObject->GetProperty('ticketstatusid');
			}

			if (!isset($_extendedDataContainer['_exTicketPriorityID'])) {
				$_exTicketPriorityID = $_SWIFT_TicketObject->GetProperty('priorityid');
			}
		}

		$_departmentMap = SWIFT_Department::GetDepartmentMap(APP_TICKETS);
		$_staffCache = $this->Cache->Get('staffcache');
		$_ticketTypeCache = $this->Cache->Get('tickettypecache');
		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');
		$_staffGroupTicketStatusIDList = SWIFT_StaffGroupLink::RetrieveListFromCacheOnStaffGroup(SWIFT_StaffGroupLink::TYPE_TICKETSTATUS, $_SWIFT->Staff->GetProperty('staffgroupid'));

		$_renderHTML = '';

		$_departmentCache = $this->Cache->Get('departmentcache');
		$_parentDepartmentID = false;
		if (isset($_departmentCache[$_exDepartmentID])) {
			$_parentDepartmentID = $_departmentCache[$_exDepartmentID]['parentdepartmentid'];
		}

		if ($_selectType == self::TYPE_DEPARTMENT) {

			$_assignedDepartmentList        = (array) SWIFT_Staff::GetAssignedDepartmentsOnStaffID($_SWIFT->Staff->GetStaffID(), APP_TICKETS);
			$_canChangeUnAssignedDepartment = $_SWIFT->Staff->GetPermission('staff_tcanchangeunassigneddepartment');

			foreach ($_departmentMap as $_departmentID => $_departmentContainer) {
				if (!$_canChangeUnAssignedDepartment && !in_array($_departmentID, $_assignedDepartmentList)) {
					continue;
				}
				$_renderHTML .= '<option value="' . intval($_departmentID) . '"';
				if ($_exDepartmentID == $_departmentID) {
					$_renderHTML .= ' selected';
				}
				$_renderHTML .= '>' . htmlspecialchars($_departmentContainer['title']) . '</option>';

				foreach ($_departmentContainer['subdepartments'] as $_subDepartmentID => $_subDepartmentContainer) {
					if (!$_canChangeUnAssignedDepartment && !in_array($_subDepartmentID, $_assignedDepartmentList)) {
						continue;
					}
					$_renderHTML .= '<option value="' . intval($_subDepartmentID) . '"';
					if ($_exDepartmentID == $_subDepartmentID) {
						$_renderHTML .= ' selected';
					}

					$_renderHTML .= '> |-' . htmlspecialchars($_subDepartmentContainer['title']) . '</option>';
				}
			}

		} else if ($_selectType == self::TYPE_OWNER) {
			$_renderHTML .= '<option value="0"' . IIF($_exOwnerStaffID == '0', ' selected') . '>' . $this->Language->Get('unassigned') . '</option>';
			foreach ($_staffCache as $_staffID => $_staffContainer) {
				$_activeStaffAssignedDepartmentIDList = SWIFT_Staff::GetAssignedDepartmentsOnStaffID($_staffID, APP_TICKETS);
				if (!in_array($_exDepartmentID, $_activeStaffAssignedDepartmentIDList) || $_staffContainer['isenabled'] == '0') {
					continue;
				}

				$_renderHTML .= '<option value="' . intval($_staffID) . '"';
				if ($_exOwnerStaffID == $_staffID) {
					$_renderHTML .= ' selected';
				}

				$_renderHTML .= '>' . htmlspecialchars($_staffContainer['fullname']) . '</option>';
			}

		} else if ($_selectType == self::TYPE_TYPE) {
			foreach ($_ticketTypeCache as $_ticketTypeID => $_ticketTypeContainer) {
				if ($_ticketTypeContainer['departmentid'] != '0' && $_ticketTypeContainer['departmentid'] != $_exDepartmentID && $_ticketTypeContainer['departmentid'] != $_parentDepartmentID) {
					continue;
				}

				$_renderHTML .= '<option value="' . intval($_ticketTypeID) . '"';
				if ($_exTicketTypeID == $_ticketTypeID) {
					$_renderHTML .= ' selected';
				}

				$_renderHTML .= '>' . htmlspecialchars($_ticketTypeContainer['title']) . '</option>';
			}

		} else if ($_selectType == self::TYPE_STATUS) {
			foreach ($_ticketStatusCache as $_ticketStatusID => $_ticketStatusContainer) {
				if (($_ticketStatusContainer['departmentid'] != '0' && $_ticketStatusContainer['departmentid'] != $_exDepartmentID) ||
						($_ticketStatusContainer['staffvisibilitycustom'] == '1' && !in_array($_ticketStatusID, $_staffGroupTicketStatusIDList))) {
					continue;
				}

				$_renderHTML .= '<option value="' . intval($_ticketStatusID) . '"';
				if ($_exTicketStatusID == $_ticketStatusID) {
					$_renderHTML .= ' selected';
				}

				$_renderHTML .= '>' . htmlspecialchars($_ticketStatusContainer['title']) . '</option>';
			}

		} else if ($_selectType == self::TYPE_PRIORITY) {
			foreach ($_ticketPriorityCache as $_ticketPriorityID => $_ticketPriorityContainer) {
				$_renderHTML .= '<option value="' . intval($_ticketPriorityID) . '"';
				if ($_exTicketPriorityID == $_ticketPriorityID) {
					$_renderHTML .= ' selected';
				}

				$_renderHTML .= '>' . htmlspecialchars($_ticketPriorityContainer['title']) . '</option>';
			}

		}


		return $_renderHTML;
	}

	/**
	 * Render the Workflow Box
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object
	 * @param array $_ticketLinkedTableContainer The Linked Table Values Container
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function RenderWorkflowBox(SWIFT_Ticket $_SWIFT_TicketObject, $_ticketLinkedTableContainer) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		if ($_SWIFT->Staff->GetPermission('staff_tcanworkflow') == '0') {
			return true;
		}

		if (!isset($_ticketLinkedTableContainer[SWIFT_TicketLinkedTable::LINKTYPE_WORKFLOW])) {
			return false;
		}

		$_workflowHTML = '';

		$_ticketWorkflowCache = $this->Cache->Get('ticketworkflowcache');

		foreach ($_ticketLinkedTableContainer[SWIFT_TicketLinkedTable::LINKTYPE_WORKFLOW] as $_ticketLinkedTableValue) {
			$_ticketWorkflowID = $_ticketLinkedTableValue['linktypeid'];

			if (!isset($_ticketWorkflowCache[$_ticketWorkflowID])) {
				continue;
			}

			$_ticketWorkflowContainer = $_ticketWorkflowCache[$_ticketWorkflowID];

			$_staffGroupIDList = SWIFT_StaffGroupLink::RetrieveListFromCache(SWIFT_StaffGroupLink::TYPE_WORKFLOW, $_ticketWorkflowID);

			if ($_ticketWorkflowContainer['staffvisibilitycustom'] == '1' && !in_array($_SWIFT->Staff->GetProperty('staffgroupid'), $_staffGroupIDList)) {
				continue;
			}

			$_workflowHTML .= '<div class="ticketworkflowitem" onclick="javascript: loadViewportData(\'' . SWIFT::Get('basename') . '/Tickets/Ticket/ExecuteWorkflow/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketWorkflowID . '/' .  SWIFT::Get('ticketurlsuffix') . '\');">' . StripName(htmlspecialchars($_ticketWorkflowContainer['title']), 22) . '</div>';
		}

		$this->UserInterface->AddNavigationBox($this->Language->Get('workflowbox'), $_workflowHTML);

		return true;
	}

	/**
	 * Render the Participants Information Box
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object
	 * @param array $_participantHTMLContainer
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function RenderParticipantBox(SWIFT_Ticket $_SWIFT_TicketObject, $_participantHTMLContainer) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_informationHTML = '';

		if (count($_participantHTMLContainer) <= 2) {
			return true;
		}

		foreach ($_participantHTMLContainer as $_participant) {
			$_informationHTML .= '<div class="ticketinfoitemtext">' .
					'<div class="ticketinfoitemtitle">' . mb_strtoupper($_participant[0]) . '</div><div class="ticketinfoitemcontent">' . StripName(htmlspecialchars($_participant[1]), 20) . '</div></div>';
		}

		$this->UserInterface->AddNavigationBox($this->Language->Get('participantbox'), $_informationHTML);

		return true;
	}


	/**
	 * Render the Information Box
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object
	 * @param SWIFT_User $_SWIFT_UserObject (OPTIONAL) The SWIFT_User Object
	 * @param SWIFT_UserOrganization $_SWIFT_UserOrganizationObject (OPTIONAL) The SWIFT_UserOrganization Object
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function RenderInfoBox(SWIFT_Ticket $_SWIFT_TicketObject, $_SWIFT_UserObject, $_SWIFT_UserOrganizationObject) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_informationHTML = '';

		$_userGroupCache = $this->Cache->Get('usergroupcache');

		$_informationHTML .= '<div class="ticketinfoitem"><div class="ticketinfoitemtitle">' . $this->Language->Get('tinfobticketid') . '</div><div class="ticketinfoitemlink"><a viewport="1" href="' . SWIFT::Get('basename') . '/Tickets/Ticket/View/' . $_SWIFT_TicketObject->GetTicketID() . '/' .  SWIFT::Get('ticketurlsuffix') . '" >' . $_SWIFT_TicketObject->GetTicketDisplayID() . '</a></div></div>';

		if ($_SWIFT->Staff->GetPermission('staff_canviewusers') != '0') {
			if ($_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded()) {
				$_ticketUserURL = SWIFT::Get('basename') . '/Base/User/Edit/' . $_SWIFT_UserObject->GetUserID();
				$_informationHTML .= '<div class="ticketinfoitem">' .
						'<div class="ticketinfoitemtitle">' . $this->Language->Get('tinfobuser') . '</div><div class="ticketinfoitemcontainer"><span class="ticketinfoitemlink"><a href="' . $_ticketUserURL . '" viewport="1">' . StripName(htmlspecialchars($_SWIFT_UserObject->GetProperty('fullname')), 20) . '</a></span></div></div>';
			}

			if ($_SWIFT_UserOrganizationObject instanceof SWIFT_UserOrganization && $_SWIFT_UserOrganizationObject->GetIsClassLoaded()) {
				$_ticketUserOrganizationURL = SWIFT::Get('basename') . '/Base/UserOrganization/Edit/' . $_SWIFT_UserOrganizationObject->GetUserOrganizationID();

				$_informationHTML .= '<div class="ticketinfoitem">' .
						'<div class="ticketinfoitemtitle">' . $this->Language->Get('tinfobuserorganization') . '</div><div class="ticketinfoitemcontainer"><span class="ticketinfoitemlink"><a href="' . $_ticketUserOrganizationURL . '" viewport="1">' . StripName(htmlspecialchars($_SWIFT_UserOrganizationObject->GetProperty('organizationname')), 20) . '</a></span></div></div>';
			}

			if ($_SWIFT_UserObject instanceof SWIFT_User && $_SWIFT_UserObject->GetIsClassLoaded() && isset($_userGroupCache[$_SWIFT_UserObject->GetProperty('usergroupid')])) {
				$_informationHTML .= '<div class="ticketinfoitemtext">' .
						'<div class="ticketinfoitemtitle">' . $this->Language->Get('tinfobusergroup') . '</div><div class="ticketinfoitemcontent">' . StripName(htmlspecialchars($_userGroupCache[$_SWIFT_UserObject->GetProperty('usergroupid')]['title']), 20) . '</div></div>';
			}
		}

		// Begin Hook: staff_ticket_infobox
		unset($_hookCode);
		($_hookCode = SWIFT_Hook::Execute('staff_ticket_infobox')) ? eval($_hookCode) : false;
		// End Hook

		$this->UserInterface->AddNavigationBox($this->Language->Get('informationbox'), $_informationHTML);

		return true;
	}

	/**
	 * Render the New Ticket Dialog
	 *
	 * @author Varun Shoor
	 * @param int $_chatObjectID (OPTIONAL) The Chat Object ID
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderNewTicketDialog($_chatObjectID = false) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_departmentMap = SWIFT_Department::GetDepartmentMap(APP_TICKETS);
		$_assignedDepartmentIDList = $_SWIFT->Staff->GetAssignedDepartments();

		$_optionsContainer = array();
		$_index = 0;

		foreach ($_departmentMap as $_departmentID => $_departmentContainer) {
			if (!in_array($_departmentID, $_assignedDepartmentIDList) && $_SWIFT->Settings->Get('t_restrictnewticket') == '1') {
				continue;
			}

			$_optionsContainer[$_index]['title'] = $_departmentContainer['title'];
			$_optionsContainer[$_index]['value'] = $_departmentID;

			if ($_index == 0) {
				$_optionsContainer[$_index]['selected'] = true;
			}

			$_index++;

			foreach ($_departmentContainer['subdepartments'] as $_subDepartmentID => $_subDepartmentContainer) {
				if (!in_array($_subDepartmentID, $_assignedDepartmentIDList) && $_SWIFT->Settings->Get('t_restrictnewticket') == '1') {
					continue;
				}

				$_optionsContainer[$_index]['title'] = ' |- ' . $_subDepartmentContainer['title'];
				$_optionsContainer[$_index]['value'] = $_subDepartmentID;

				$_index++;
			}
		}


		$this->UserInterface->Start('newticketdialog', '/Tickets/Ticket/NewTicketForm', SWIFT_UserInterface::MODE_EDIT, false);

		if (count($_optionsContainer)) {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('nt_next'), 'icon_next.gif');
		}

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);


		/*
		 * ###############################################
		 * BEGIN GENERAL TAB
		 * ###############################################
		*/
		$_GeneralTabObject = $this->UserInterface->AddTab($this->Language->Get('tabgeneral'), 'icon_form.gif', 'generalnt', true);

		$_radioContainer = array();
		$_radioContainer[0]['title'] = $this->Language->Get('nt_sendmail');
		$_radioContainer[0]['value'] = 'sendmail';
		$_radioContainer[0]['checked'] = true;

		$_radioContainer[1]['title'] = $this->Language->Get('nt_asuser');
		$_radioContainer[1]['value'] = 'user';

		$_GeneralTabObject->Radio('tickettype', $this->Language->Get('newticket_type'), $this->Language->Get('desc_newticket_type'), $_radioContainer, false);


		$_GeneralTabObject->Select('departmentid', $this->Language->Get('newticket_department'), $this->Language->Get('desc_newticket_department'), $_optionsContainer, '', '', '', false, 'width: 180px;');

		/*
		 * ###############################################
		 * END GENERAL TAB
		 * ###############################################
		*/

		if (!empty($_chatObjectID)) {
			$this->UserInterface->Hidden('chatobjectid', $_chatObjectID);
		}

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Render the New TIcket Tab
	 *
	 * @author Varun Shoor
	 * @param constant $_ticketType
	 * @param int $_departmentID The Department ID
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderNewTicket($_ticketType, $_departmentID) {
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$_departmentCache = $this->Cache->Get('departmentcache');
		$_departmentContainer = $_departmentCache[$_departmentID];

		$this->UserInterface->Start('newticket', '/Tickets/Ticket/NewTicketForm', SWIFT_UserInterface::MODE_INSERT, false, true);

		if ($_ticketType == self::TAB_NEWTICKET_EMAIL) {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('dispatchsend'), 'icon_check.gif', '/Tickets/Ticket/NewTicketSubmit/sendmail', SWIFT_UserInterfaceToolbar::LINK_FORM);
		} else {
			$this->UserInterface->Toolbar->AddButton($this->Language->Get('dispatchcreate'), 'icon_check.gif', '/Tickets/Ticket/NewTicketSubmit/user', SWIFT_UserInterfaceToolbar::LINK_FORM);
		}
		$this->UserInterface->Toolbar->AddButton($this->Language->Get('addnote'), 'icon_note.png', "\$('#newticketnotes').toggle(); \$('#newticketticketnotes').focus();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'newticketnotes');
		$this->UserInterface->Toolbar->AddButton($this->Language->Get('dispatchattachfile'), 'icon_file.gif', "\$('#newticketattachments').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'newticketattachments');
		$this->UserInterface->Toolbar->AddButton($this->Language->Get('options'), 'icon_settings2.gif', "\$('#newticketoptions').toggle();", SWIFT_UserInterfaceToolbar::LINK_JAVASCRIPT, '', 'newticketoptions');
		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'),
				SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$_NewTicketTabObject = $this->UserInterface->AddTab(sprintf($this->Language->Get('tabnewticket2'), htmlspecialchars($_departmentContainer['title'])), 'icon_ticket.png', 'general', true, false, 0);
		$_NewTicketTabObject->SetColumnWidth('15%');

		$this->RenderDispatchTab($_ticketType, $_NewTicketTabObject, null, null, array(), $_departmentID);


		/*
		 * ###############################################
		 * BEGIN RECURRENCE TAB
		 * ###############################################
		 */

		if ($_SWIFT->Staff->GetPermission('staff_tcaninsertrecurrence') != '0') {
			$_RecurrenceTab = $this->UserInterface->AddTab($this->Language->Get('tabrecurrence'), 'icon_spacer.gif', 'recurrence', false);
			$_RecurrenceTab->LoadToolbar();

			if ($_ticketType == self::TAB_NEWTICKET_EMAIL) {
				$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('dispatchsend'), 'icon_check.gif', '/Tickets/Ticket/NewTicketSubmit/sendmail', SWIFT_UserInterfaceToolbar::LINK_FORM);
			} else {
				$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('dispatchcreate'), 'icon_check.gif', '/Tickets/Ticket/NewTicketSubmit/user', SWIFT_UserInterfaceToolbar::LINK_FORM);
			}

			$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

			$_RecurrenceTab->SetColumnWidth('200px');

			$_recurrenceRadioHTML = $_recurrenceDataHTML = '';

			$_recurrenceDataHTML .= '<div id="recurrencecontainer_none">' . $this->Language->Get('recurnotactivated') . '</div>';

			$_recurrenceDataHTML .= '<div id="recurrencecontainer_daily" style="display: none;"><label for="recurdaily_default"><input type="radio" id="recurdaily_default" name="recurrence_daily_type" value="default" checked /> ' . $this->Language->Get('rec_every') . '</label> <input type="text" class="swifttextnumeric" size="3" value="1" name="recurrence_daily_step" onfocus="javascript: $(\'#recurdaily_default\').attr(\'checked\', true);" /> <label for="recurdaily_default">' . $this->Language->Get('rec_days') . '</label><br /><br />';
			$_recurrenceDataHTML .= '<label for="recurdaily_ext"><input type="radio" id="recurdaily_ext" name="recurrence_daily_type" value="extended" /> ' . $this->Language->Get('rec_everyweekday') . '</label>';
			$_recurrenceDataHTML .= '</div>';

			$_recurrenceDataHTML .= '<div id="recurrencecontainer_weekly" style="display: none;"><label for="recurweekly_default"><input type="radio" id="recurweekly_default" name="recurrence_weekly_type" value="default" checked /> ' . $this->Language->Get('rec_every') . '</label> <input type="text" class="swifttextnumeric" size="3" value="1" name="recurrence_weekly_step" /> <label for="recurweekly_default">' . $this->Language->Get('rec_weeks') . '</label><br /><br />';
			$_recurrenceDataHTML .= '<label for="recurweekly_monday"><input type="checkbox" id="recurweekly_monday" name="recurrence_weekly_ismonday" value="1" checked /> ' . $this->Language->Get('rec_monday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_tuesday"><input type="checkbox" id="recurweekly_tuesday" name="recurrence_weekly_istuesday" value="1" checked /> ' . $this->Language->Get('rec_tuesday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_wednesday"><input type="checkbox" id="recurweekly_wednesday" name="recurrence_weekly_iswednesday" value="1" checked /> ' . $this->Language->Get('rec_wednesday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_thursday"><input type="checkbox" id="recurweekly_thursday" name="recurrence_weekly_isthursday" value="1" checked /> ' . $this->Language->Get('rec_thursday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_friday"><input type="checkbox" id="recurweekly_friday" name="recurrence_weekly_isfriday" value="1" checked /> ' . $this->Language->Get('rec_friday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_saturday"><input type="checkbox" id="recurweekly_saturday" name="recurrence_weekly_issaturday" value="1" /> ' . $this->Language->Get('rec_saturday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '<label for="recurweekly_sunday"><input type="checkbox" id="recurweekly_sunday" name="recurrence_weekly_issunday" value="1" /> ' . $this->Language->Get('rec_sunday') . '</label>&nbsp;&nbsp;&nbsp;';
			$_recurrenceDataHTML .= '</div>';

			$_recurrenceDataHTML .= '<div id="recurrencecontainer_monthly" style="display: none;"><label for="recurmonthly_default"><input type="radio" id="recurmonthly_default" name="recurrence_monthly_type" value="default" checked /> ' . $this->Language->Get('rec_day') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . gmdate('d', DATENOW) . '" name="recurrence_monthly_day" onfocus="javascript: $(\'#recurmonthly_default\').attr(\'checked\', true);" /> <label for="recurmonthly_default">' . $this->Language->Get('rec_ofevery') . '</label> <input type="text" class="swifttextnumeric" size="3" value="1" name="recurrence_monthly_step" onfocus="javascript: $(\'#recurmonthly_default\').attr(\'checked\', true);" />  <label for="recurmonthly_default">' . $this->Language->Get('rec_months') . '</label> <br /><br />';
			$_recurrenceDataHTML .= '<label for="recurmonthly_ext"><input type="radio" id="recurmonthly_ext" name="recurrence_monthly_type" value="extended" /> ' . $this->Language->Get('rec_the') . '</label> ';
			$_recurrenceDataHTML .= '<select name="recurrence_monthly_extdaystep" class="swiftselect" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);"><option value="first" selected>' . $this->Language->Get('rec_first') . '</option><option value="second">' . $this->Language->Get('rec_second') . '</option><option value="third">' . $this->Language->Get('rec_third') . '</option><option value="fourth">' . $this->Language->Get('rec_fourth') . '</option><option value="fifth">' . $this->Language->Get('rec_fifth') . '</option></select> ';
			$_recurrenceDataHTML .= '<select name="recurrence_monthly_extday" class="swiftselect" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);"><option value="monday" selected>' . $this->Language->Get('rec_monday') . '</option><option value="tuesday">' . $this->Language->Get('rec_tuesday') . '</option><option value="wednesday">' . $this->Language->Get('rec_wednesday') . '</option><option value="thursday">' . $this->Language->Get('rec_thursday') . '</option><option value="friday">' . $this->Language->Get('rec_friday') . '</option><option value="saturday">' . $this->Language->Get('rec_saturday') . '</option><option value="sunday">' . $this->Language->Get('rec_sunday') . '</option></select> ';
			$_recurrenceDataHTML .= '<label for="recurmonthly_ext">' . $this->Language->Get('rec_ofevery') . '</label> <input type="text" class="swifttextnumeric" size="3" value="1" name="recurrence_monthly_stepext" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);" />  <label for="recurmonthly_ext">' . $this->Language->Get('rec_months') . '</label> <br /><br />';
			$_recurrenceDataHTML .= '</div>';


			$_yearlyMonthlyOptions = '<option value="1"' . IIF(date('m') == '1', ' selected') . '>' . $this->Language->Get('cal_january') . '</option><option value="2"' . IIF(date('m') == '2', ' selected') . '>' . $this->Language->Get('cal_february') . '</option><option value="3"' . IIF(date('m') == '3', ' selected') . '>' . $this->Language->Get('cal_march') . '</option><option value="4"' . IIF(date('m') == '4', ' selected') . '>' . $this->Language->Get('cal_april') . '</option><option value="5"' . IIF(date('m') == '5', ' selected') . '>' . $this->Language->Get('cal_may') . '</option><option value="6"' . IIF(date('m') == '6', ' selected') . '>' . $this->Language->Get('cal_june') . '</option><option value="7"' . IIF(date('m') == '7', ' selected') . '>' . $this->Language->Get('cal_july') . '</option><option value="8"' . IIF(date('m') == '8', ' selected') . '>' . $this->Language->Get('cal_august') . '</option><option value="9"' . IIF(date('m') == '9', ' selected') . '>' . $this->Language->Get('cal_september') . '</option><option value="10"' . IIF(date('m') == '10', ' selected') . '>' . $this->Language->Get('cal_october') . '</option><option value="11"' . IIF(date('m') == '11', ' selected') . '>' . $this->Language->Get('cal_november') . '</option><option value="12"' . IIF(date('m') == '12', ' selected') . '>' . $this->Language->Get('cal_december') . '</option>';
			$_recurrenceDataHTML .= '<div id="recurrencecontainer_yearly" style="display: none;"><label for="recuryearly_default"><input type="radio" id="recuryearly_default" name="recurrence_yearly_type" value="default" checked /> ' . $this->Language->Get('rec_every') . '</label> <select class="swiftselect" name="recurrence_yearly_month" onfocus="javascript: $(\'#recuryearly_default\').attr(\'checked\', true);">' . $_yearlyMonthlyOptions . '</select> <input type="text" class="swifttextnumeric" size="3" value="' . gmdate('d', DATENOW) . '" name="recurrence_yearly_monthday" onfocus="javascript: $(\'#recuryearly_default\').attr(\'checked\', true);" /> <br /><br />';
			$_recurrenceDataHTML .= '<label for="recuryearly_ext"><input type="radio" id="recuryearly_ext" name="recurrence_yearly_type" value="extended" /> ' . $this->Language->Get('rec_the') . '</label> ';
			$_recurrenceDataHTML .= '<select name="recurrence_yearly_extdaystep" class="swiftselect" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);"><option value="first" selected>' . $this->Language->Get('rec_first') . '</option><option value="second">' . $this->Language->Get('rec_second') . '</option><option value="third">' . $this->Language->Get('rec_third') . '</option><option value="fourth">' . $this->Language->Get('rec_fourth') . '</option><option value="fifth">' . $this->Language->Get('rec_fifth') . '</option></select> ';
			$_recurrenceDataHTML .= '<select name="recurrence_yearly_extday" class="swiftselect" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);"><option value="monday" selected>' . $this->Language->Get('rec_monday') . '</option><option value="tuesday">' . $this->Language->Get('rec_tuesday') . '</option><option value="wednesday">' . $this->Language->Get('rec_wednesday') . '</option><option value="thursday">' . $this->Language->Get('rec_thursday') . '</option><option value="friday">' . $this->Language->Get('rec_friday') . '</option><option value="saturday">' . $this->Language->Get('rec_saturday') . '</option><option value="sunday">' . $this->Language->Get('rec_sunday') . '</option></select> ';
			$_recurrenceDataHTML .= '<label for="recuryearly_ext">' . $this->Language->Get('rec_of') . '</label> <select class="swiftselect" name="recurrence_yearly_extmonth" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);">' . $_yearlyMonthlyOptions . '</select> <br /><br />';
			$_recurrenceDataHTML .= '</div>';

			$_recurrenceRadioHTML .= '<div class="tabletitle"><label for="recurrence_none"><input type="radio" onclick="javascript: ToggleRecurrence(\'none\');" id="recurrence_none" name="recurrencetype" value="0" checked /> ' . $this->Language->Get('recurrence_none') . '</label><br />';
			$_recurrenceRadioHTML .= '<label for="recurrence_daily"><input type="radio" onclick="javascript: ToggleRecurrence(\'daily\');" id="recurrence_daily" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_DAILY . '" /> ' . $this->Language->Get('recurrence_daily') . '</label><br />';
			$_recurrenceRadioHTML .= '<label for="recurrence_weekly"><input type="radio" onclick="javascript: ToggleRecurrence(\'weekly\');" id="recurrence_weekly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_WEEKLY . '" /> ' . $this->Language->Get('recurrence_weekly') . '</label><br />';
			$_recurrenceRadioHTML .= '<label for="recurrence_monthly"><input type="radio" onclick="javascript: ToggleRecurrence(\'monthly\');" id="recurrence_monthly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_MONTHLY . '" /> ' . $this->Language->Get('recurrence_monthly') . '</label><br />';
			$_recurrenceRadioHTML .= '<label for="recurrence_yearly"><input type="radio" onclick="javascript: ToggleRecurrence(\'yearly\');" id="recurrence_yearly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_YEARLY . '" /> ' . $this->Language->Get('recurrence_yearly') . '</label><br /></div>';

			$_columnContainer              = array();
			$_columnContainer[0]['value']  = $_recurrenceRadioHTML;
			$_columnContainer[0]['align']  = 'left';
			$_columnContainer[0]['width']  = '150px';
			$_columnContainer[1]['value']  = $_recurrenceDataHTML;
			$_columnContainer[1]['align']  = 'left';
			$_columnContainer[1]['valign'] = 'top';
			$_RecurrenceTab->Row($_columnContainer);

			$_RecurrenceTab->StartContainer('recurrencerangecontainer', false);
			$_RecurrenceTab->Title($this->Language->Get('recurrencerange'), 'icon_doublearrows.gif');

			$_RecurrenceTab->Date('recurrence_start', $this->Language->Get('recur_starts'), '', gmdate(SWIFT_Date::GetCalendarDateFormat(), DATENOW), 0, false, true);

			$_recurrenceEndHTML = '';
			$_recurrenceEndHTML .= '<label for="recurrenceend_noeend"><input type="radio" id="recurrenceend_noeend" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_NOEND . '" checked /> ' . $this->Language->Get('rec_noeenddate') . '</label><br /><br />';
			$_recurrenceEndHTML .= '<label for="recurrenceend_endoccur"><input type="radio" id="recurrenceend_endoccur" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_OCCURENCES . '" /> ' . $this->Language->Get('rec_endafter') . '</label> <input type="text" class="swifttextnumeric" size="3" value="10" name="recurrence_endcount" onfocus="javascript: $(\'#recurrenceend_endoccur\').attr(\'checked\', true);" />  <label for="recurrenceend_endoccur">' . $this->Language->Get('rec_occurrences') . '</label><br /><br />';
			$_recurrenceEndHTML .= '<label for="recurrenceend_enddate"><input type="radio" id="recurrenceend_enddate" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_DATE . '" /> ' . $this->Language->Get('rec_endby') . '</label> <input type="text" name="recurrence_enddateline" id="recur_enddate" size="12" value="" onfocus="javascript: $(\'#recurrenceend_enddate\').attr(\'checked\', true);" class="swifttext" /><script language="Javascript">QueueFunction(function(){ $("#recur_enddate").datepicker(datePickerDefaults); });</script><br />';

			$_columnContainer              = array();
			$_columnContainer[0]['value']  = '<span class="tabletitle">' . $this->Language->Get('recur_ends') . '</span>';
			$_columnContainer[0]['align']  = 'left';
			$_columnContainer[0]['width']  = '150px';
			$_columnContainer[0]['valign'] = 'top';
			$_columnContainer[1]['value']  = $_recurrenceEndHTML;
			$_columnContainer[1]['align']  = 'left';
			$_columnContainer[1]['valign'] = 'top';
			$_RecurrenceTab->Row($_columnContainer);
			$_RecurrenceTab->EndContainer();
		}

		/*
		 * ###############################################
		 * END RECURRENCE TAB
		 * ###############################################
		 */

	   // Begin Hook: staff_newticket_tabs
	   unset($_hookCode);
	   ($_hookCode = SWIFT_Hook::Execute('staff_newticket_tabs')) ? eval($_hookCode) : false;
	   // End Hook

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Render the Dispatch Dialog
	 *
	 * @author Varun Shoor
	 * @param int $_mode The Render Mode
	 * @param SWIFT_Ticket $_SWIFT_TicketObject The SWIFT_Ticket Object Pointer
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function RenderDispatchForm($_mode, SWIFT_Ticket $_SWIFT_TicketObject) {
		$_SWIFT = SWIFT::GetInstance();

		$_staffCache = $this->Cache->Get('staffcache');

		if (!$this->GetIsClassLoaded()) {
			return false;
		}

		$this->UserInterface->Start('ticketdispatch', '/Tickets/Ticket/DispatchSubmit/' . $_SWIFT_TicketObject->GetTicketID() . '/' . SWIFT::Get('ticketurlsuffix'), SWIFT_UserInterface::MODE_EDIT, true, false, false, false);
		$this->UserInterface->SetDialogOptions(false);

		$this->UserInterface->Toolbar->AddButton($this->Language->Get('assign'), 'icon_check.gif');
		$this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);


		$_staffGroupCache = $this->Cache->Get('staffgroupcache');
		$_staffCache = $this->Cache->Get('staffcache');
		$_ticketCountCache = $this->Cache->Get('ticketcountcache');

		$_staffGroupStaffContainer = array();

		foreach ($_staffCache as $_staffID => $_staffContainer) {
			if ($_staffContainer['isenabled'] == '0') {
				continue;
			}

			$_totalUnresolvedItems = 0;
			if (isset($_ticketCountCache['ownerstaff'][$_staffID])) {
				$_totalUnresolvedItems = intval($_ticketCountCache['ownerstaff'][$_staffID]['totalunresolveditems']);
			}

			$_staffGroupStaffContainer[$_staffContainer['staffgroupid']][$_totalUnresolvedItems . '.' . $_staffID] = $_staffContainer;
			$_staffGroupStaffContainer[$_staffContainer['staffgroupid']][$_totalUnresolvedItems . '.' . $_staffID]['totalunresolveditems'] = $_totalUnresolvedItems;

		}


		/*
		 * ###############################################
		 * BEGIN DISPATCH TAB
		 * ###############################################
		*/

		$_DispatchTabObject = $this->UserInterface->AddTab($this->Language->Get('tabdispatch'), 'icon_dispatch.png', 'dispatch', true);

		$_DispatchTabObject->Overflow(390);

		foreach ($_staffGroupCache as $_staffGroupID => $_staffGroupContainer) {
			$_tabHTML = '';

			$_tabHTML .= '<table width="100%" border="0" cellspacing="1" cellpadding="4">';
			$_tabHTML .= '<tr class="settabletitlerowmain2"><td class="settabletitlerowmain2" align="left" colspan="2">';
			$_tabHTML .= '<span style="float: left;"><img src="' . SWIFT::Get('themepath') . 'images/icon_doublearrows.gif' . '" align="absmiddle" border="0" /> ' . htmlspecialchars($_staffGroupContainer['title']) . '</span>';
			$_tabHTML .= '</tr>';
			$_tabHTML .= '</table>';

			$_tabHTML .= '<div id="" style="display: block;">';
			$_tabHTML .= '<table width="100%" border="0" cellspacing="1" cellpadding="4">';

			$_DispatchTabObject->RowHTML($_tabHTML);

			if (isset($_staffGroupStaffContainer[$_staffGroupID]) && _is_array($_staffGroupStaffContainer[$_staffGroupID])) {
				ksort($_staffGroupStaffContainer[$_staffGroupID]);


				foreach ($_staffGroupStaffContainer[$_staffGroupID] as $_staffContainer) {
					$_assignedDepartmentForStaff = SWIFT_Staff::GetAssignedDepartmentsOnStaffID($_staffContainer['staffid']);
					if (!in_array($_SWIFT_TicketObject->GetProperty('departmentid'), $_assignedDepartmentForStaff)) {
						continue;
					}

					$_extendedHTML = '<div class="blocknotecountergreen">0</div>';
					if (!empty($_staffContainer['totalunresolveditems'])) {
						$_divClass = 'blocknotecountergreen';
						if ($_staffContainer['totalunresolveditems'] > 0 && $_staffContainer['totalunresolveditems'] < 20) {
							$_divClass = 'blocknotecounterblue';
						} else {
							$_divClass = 'blocknotecounterred';
						}
						$_extendedHTML = '<div class="' . $_divClass . '">' . number_format($_staffContainer['totalunresolveditems'], 0) . '</div>';
					}
					$_DispatchTabObject->RadioList('dispatchstaffid', $_staffContainer['fullname'], $_staffContainer['staffid'], IIF($_SWIFT_TicketObject->GetProperty('ownerstaffid') == $_staffContainer['staffid'], true, false), '<span style="float: right;">' . $_extendedHTML . '</span>');
				}
			}

			$_DispatchTabObject->RowHTML('</table></div>');
		}


		/*
		 * ###############################################
		 * END DISPATCH TAB
		 * ###############################################
		*/

		$this->UserInterface->End();

		return true;
	}

	/**
	 * Retrieve the relevant JSON associated with ticket data
	 *
	 * @author Varun Shoor
	 * @return string The JSON Data
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function GetTicketDataJSON() {
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');

		$_ticketDataContainer = array();
		foreach ($_ticketStatusCache as $_ticketStatusID => $_ticketStatusContainer) {
			$_ticketDataContainer['status'][$_ticketStatusID]['statusbgcolor'] = $_ticketStatusContainer['statusbgcolor'];
		}

		foreach ($_ticketPriorityCache as $_ticketPriorityID => $_ticketPriorityContainer) {
			$_ticketDataContainer['priority'][$_ticketPriorityID]['bgcolorcode'] = $_ticketPriorityContainer['bgcolorcode'];
		}

		return json_encode($_ticketDataContainer);
	}

	/**
	 * Render the Recurrence
	 *
	 * @author Parminder Singh
	 *
	 * @param SWIFT_Ticket           $_Ticket
	 * @param SWIFT_TicketRecurrence $_TicketRecurrence
	 *
	 * @return bool
	 */
	public function RenderRecurrence($_Ticket, $_TicketRecurrence)
	{
		$_SWIFT = SWIFT::GetInstance();

		$this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);

		$_RecurrenceTab = new SWIFT_UserInterfaceTab($this->UserInterface, $this->Language->Get('tabrecurrence'), '', 1, 'recurrence', false, false, 4, '');

		$_RecurrenceTab->LoadToolbar();
		if ($_SWIFT->Staff->GetPermission('staff_tcanupdaterecurrence') != '0') {
			$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('update'), 'icon_check.gif', '/Tickets/Ticket/UpdateRecurrence/' . $_Ticket->GetID() . '/' . $_TicketRecurrence->GetTicketRecurrenceID(), SWIFT_UserInterfaceToolbar::LINK_FORM);

			$_RecurrenceTab->Toolbar->AddButton(IIF($_TicketRecurrence->Get('nextrecurrence') == '0', $this->Language->Get('resume'), $this->Language->Get('pause')), IIF($_TicketRecurrence->Get('nextrecurrence') == '0', 'icon_play.gif', 'icon_pause.gif'), '/Tickets/Ticket/PauseOrResumeRecurrence/' . $_Ticket->GetID() . '/' . $_TicketRecurrence->GetTicketRecurrenceID(), SWIFT_UserInterfaceToolbar::LINK_FORM);
		}

		if ($_SWIFT->Staff->GetPermission('staff_tcandeleterecurrence') != '0') {
			$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('stop'), 'icon_block.gif', '/Tickets/Ticket/StopRecurrence/' . $_Ticket->GetID() . '/' . $_TicketRecurrence->GetTicketRecurrenceID(), SWIFT_UserInterfaceToolbar::LINK_CONFIRM, '', '', false);
		}

		$_RecurrenceTab->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('ticketmain'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);

		$_RecurrenceTab->SetColumnWidth('150px');

		$_recurrenceRadioHTML = $_recurrenceDataHTML = '';

		$_recurrenceDailyChecked = $_recurDailyDefaultChecked = $_recurDailyExtDaily = $_recurrenceWeeklyChecked = $_recurWeeklyDefaultChecked = $_recurWeeklyMondayChecked = $_recurWeeklyTuesdayChecked = $_recurWeeklyWednesdayChecked = $_recurWeeklyThursdayChecked = $_recurWeeklyFridayChecked = $_recurWeeklySaturdayChecked = $_recurWeeklySundayChecked = $_recurrenceMonthlyChecked = $_recurMonthlyDefaultChecked = $_recurMonthlyExtChecked = $_recurrenceYearlyChecked = $_recurYearlyExtChecked = $_recurrenceendNoeend = $_recurrenceendEndoccurChecked = $_recurrenceendEnddateChecked = '';

		$_recurrenceDailyStepValue = $_recurrenceWeeklyStepValue = $_recurrenceMonthlyDayValue = $_recurrenceMonthlyStepValue = $_recurrenceMonthlyExtdaystepValue = $_recurrenceMonthlyExtdayValue = $_recurrenceMonthlyStepextValue = $_recurrenceYearlyMonthValue = $_recurrenceYearlyMonthdayValue = $_recurrenceYearlyExtdaystepValue = $_recurrenceYearlyExtdayValue = '1';

		$_recurrenceEndCountValue = $_recurEnddateValue = '';

		if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_DAILY) {
			$_recurrenceDailyChecked = ' checked ';

			if ($_TicketRecurrence->Get('intervalstep') != '0') {
				$_recurDailyDefaultChecked = ' checked ';
				$_recurrenceDailyStepValue = intval($_TicketRecurrence->Get('intervalstep'));
			} else if ($_TicketRecurrence->Get('daily_everyweekday') != '0') {
				$_recurDailyExtDaily = ' checked ';
			}
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_WEEKLY) {
			$_recurrenceWeeklyChecked = ' checked ';

			$_recurWeeklyDefaultChecked = ' checked ';

			if ($_TicketRecurrence->Get('intervalstep') != '0') {
				$_recurrenceWeeklyStepValue = intval($_TicketRecurrence->Get('intervalstep'));
			}

			if ($_TicketRecurrence->Get('weekly_monday') != '0') {
				$_recurWeeklyMondayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_tuesday') != '0') {
				$_recurWeeklyTuesdayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_wednesday') != '0') {
				$_recurWeeklyWednesdayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_thursday') != '0') {
				$_recurWeeklyThursdayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_friday') != '0') {
				$_recurWeeklyFridayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_saturday') != '0') {
				$_recurWeeklySaturdayChecked = ' checked ';
			}
			if ($_TicketRecurrence->Get('weekly_sunday') != '0') {
				$_recurWeeklySundayChecked = ' checked ';
			}
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_MONTHLY) {
			$_recurrenceMonthlyChecked = ' checked ';
			if ($_TicketRecurrence->Get('monthly_type') == SWIFT_TicketRecurrence::MONTHLY_DEFAULT) {
				$_recurMonthlyDefaultChecked = ' checked ';
				$_recurrenceMonthlyDayValue  = intval($_TicketRecurrence->Get('monthly_day'));
				$_recurrenceMonthlyStepValue = intval($_TicketRecurrence->Get('intervalstep'));
			} else if ($_TicketRecurrence->Get('monthly_type') == SWIFT_TicketRecurrence::MONTHLY_EXTENDED) {
				$_recurMonthlyExtChecked           = ' checked ';
				$_recurrenceMonthlyExtdaystepValue = $_TicketRecurrence->Get('monthly_extdaystep');
				$_recurrenceMonthlyExtdayValue     = $_TicketRecurrence->Get('monthly_extday');
				$_recurrenceMonthlyStepextValue    = $_TicketRecurrence->Get('intervalstep');
			}
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_YEARLY) {
			$_recurrenceYearlyChecked = ' checked ';
			if ($_TicketRecurrence->Get('yearly_type') == SWIFT_TicketRecurrence::YEARLY_DEFAULT) {
				$_recurrenceYearlyMonthValue    = $_TicketRecurrence->Get('yearly_month');
				$_recurrenceYearlyMonthdayValue = $_TicketRecurrence->Get('yearly_monthday');
			} else if ($_TicketRecurrence->Get('yearly_type') == SWIFT_TicketRecurrence::YEARLY_EXTENDED) {
				$_recurYearlyExtChecked           = ' checked ';
				$_recurrenceYearlyExtdaystepValue = $_TicketRecurrence->Get('yearly_extdaystep');
				$_recurrenceYearlyExtdayValue     = $_TicketRecurrence->Get('yearly_extday');
				$_recurrenceYearlyMonthValue      = $_TicketRecurrence->Get('yearly_extmonth');
			}
		}

		// Range of Recurrence Script HTML
		$_recurrenceStartValue = DATENOW;
		if ($_TicketRecurrence->Get('startdateline') != '0') {
			$_recurrenceStartValue = $_TicketRecurrence->Get('startdateline');
		}

		if ($_TicketRecurrence->Get('endtype') == SWIFT_TicketRecurrence::END_NOEND) {
			$_recurrenceendNoeend = ' checked ';
		} else if ($_TicketRecurrence->Get('endtype') == SWIFT_TicketRecurrence::END_OCCURENCES) {
			$_recurrenceendEndoccurChecked = ' checked ';
			$_recurrenceEndCountValue      = $_TicketRecurrence->Get('endcount');
		} else if ($_TicketRecurrence->Get('endtype') == SWIFT_TicketRecurrence::END_DATE) {
			$_recurrenceendEnddateChecked = ' checked ';
			$_recurEnddateValue           = gmdate(SWIFT_Date::GetCalendarDateFormat(), $_TicketRecurrence->Get('enddateline'));
		}

		$_recurrenceDataHTML .= '<div id="recurrencecontainer_daily" style="display: none;"><label for="recurdaily_default"><input type="radio" id="recurdaily_default" name="recurrence_daily_type" value="default" ' . $_recurDailyDefaultChecked . ' /> ' . $this->Language->Get('rec_every') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceDailyStepValue . '" name="recurrence_daily_step" id="recurrence_daily_step" onfocus="javascript: $(\'#recurdaily_default\').attr(\'checked\', true);" /> <label for="recurdaily_default">' . $this->Language->Get('rec_days') . '</label><br /><br />';
		$_recurrenceDataHTML .= '<label for="recurdaily_ext"><input type="radio" id="recurdaily_ext" name="recurrence_daily_type" value="extended" ' . $_recurDailyExtDaily . ' /> ' . $this->Language->Get('rec_everyweekday') . '</label>';
		$_recurrenceDataHTML .= '</div>';

		$_recurrenceDataHTML .= '<div id="recurrencecontainer_weekly" style="display: none;"><label for="recurweekly_default"><input type="radio" id="recurweekly_default" name="recurrence_weekly_type" value="default" ' . $_recurWeeklyDefaultChecked . ' /> ' . $this->Language->Get('rec_every') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceWeeklyStepValue . '" name="recurrence_weekly_step" id="recurrence_weekly_step" /> <label for="recurweekly_default">' . $this->Language->Get('rec_weeks') . '</label><br /><br />';
		$_recurrenceDataHTML .= '<label for="recurweekly_monday"><input type="checkbox" id="recurweekly_monday" name="recurrence_weekly_ismonday" value="1" ' . $_recurWeeklyMondayChecked . ' /> ' . $this->Language->Get('rec_monday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_tuesday"><input type="checkbox" id="recurweekly_tuesday" name="recurrence_weekly_istuesday" value="1" ' . $_recurWeeklyTuesdayChecked . ' /> ' . $this->Language->Get('rec_tuesday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_wednesday"><input type="checkbox" id="recurweekly_wednesday" name="recurrence_weekly_iswednesday" value="1" ' . $_recurWeeklyWednesdayChecked . ' /> ' . $this->Language->Get('rec_wednesday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_thursday"><input type="checkbox" id="recurweekly_thursday" name="recurrence_weekly_isthursday" value="1" ' . $_recurWeeklyThursdayChecked . ' /> ' . $this->Language->Get('rec_thursday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_friday"><input type="checkbox" id="recurweekly_friday" name="recurrence_weekly_isfriday" value="1" ' . $_recurWeeklyFridayChecked . ' /> ' . $this->Language->Get('rec_friday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_saturday"><input type="checkbox" id="recurweekly_saturday" name="recurrence_weekly_issaturday" value="1" ' . $_recurWeeklySaturdayChecked . ' /> ' . $this->Language->Get('rec_saturday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '<label for="recurweekly_sunday"><input type="checkbox" id="recurweekly_sunday" name="recurrence_weekly_issunday" value="1" ' . $_recurWeeklySundayChecked . ' /> ' . $this->Language->Get('rec_sunday') . '</label>&nbsp;&nbsp;&nbsp;';
		$_recurrenceDataHTML .= '</div>';

		$_recurrenceDataHTML .= '<div id="recurrencecontainer_monthly" style="display: none;"><label for="recurmonthly_default"><input type="radio" id="recurmonthly_default" name="recurrence_monthly_type" value="default" ' . $_recurMonthlyDefaultChecked . ' /> ' . $this->Language->Get('rec_day') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceMonthlyDayValue . '" name="recurrence_monthly_day" id="recurrence_monthly_day" onfocus="javascript: $(\'#recurmonthly_default\').attr(\'checked\', true);" /> <label for="recurmonthly_default">' . $this->Language->Get('rec_ofevery') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceMonthlyStepValue . '" name="recurrence_monthly_step" id="recurrence_monthly_step" onfocus="javascript: $(\'#recurmonthly_default\').attr(\'checked\', true);" />  <label for="recurmonthly_default">' . $this->Language->Get('rec_months') . '</label> <br /><br />';
		$_recurrenceDataHTML .= '<label for="recurmonthly_ext"><input type="radio" id="recurmonthly_ext" name="recurrence_monthly_type" value="extended" ' . $_recurMonthlyExtChecked . ' /> ' . $this->Language->Get('rec_the') . '</label> ';
		$_recurrenceDataHTML .= '<select name="recurrence_monthly_extdaystep" id="recurrence_monthly_extdaystep" class="swiftselect" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);"><option value="first" ' . IIF($_recurrenceMonthlyExtdaystepValue == "first", "selected") . ' >' . $this->Language->Get('rec_first') . '</option><option value="second"  ' . IIF($_recurrenceMonthlyExtdaystepValue == "second", "selected") . '>' . $this->Language->Get('rec_second') . '</option><option value="third" ' . IIF($_recurrenceMonthlyExtdaystepValue == "third", "selected") . '>' . $this->Language->Get('rec_third') . '</option><option value="fourth"  ' . IIF($_recurrenceMonthlyExtdaystepValue == "fourth", "selected") . '>' . $this->Language->Get('rec_fourth') . '</option><option value="fifth" ' . IIF($_recurrenceMonthlyExtdaystepValue == "fifth", "selected") . '>' . $this->Language->Get('rec_fifth') . '</option></select> ';
		$_recurrenceDataHTML .= '<select name="recurrence_monthly_extday" id="recurrence_monthly_extday" class="swiftselect" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);"><option value="monday" ' . IIF($_recurrenceMonthlyExtdayValue == "monday", "selected") . ' >' . $this->Language->Get('rec_monday') . '</option><option value="tuesday" ' . IIF($_recurrenceMonthlyExtdayValue == "tuesday", "selected") . ' >' . $this->Language->Get('rec_tuesday') . '</option><option value="wednesday" ' . IIF($_recurrenceMonthlyExtdayValue == "wednesday", "selected") . ' >' . $this->Language->Get('rec_wednesday') . '</option><option value="thursday" ' . IIF($_recurrenceMonthlyExtdayValue == "thursday", "selected") . ' >' . $this->Language->Get('rec_thursday') . '</option><option value="friday" ' . IIF($_recurrenceMonthlyExtdayValue == "friday", "selected") . ' >' . $this->Language->Get('rec_friday') . '</option><option value="saturday" ' . IIF($_recurrenceMonthlyExtdayValue == "saturday", "selected") . ' >' . $this->Language->Get('rec_saturday') . '</option><option value="sunday" ' . IIF($_recurrenceMonthlyExtdayValue == "sunday", "selected") . ' >' . $this->Language->Get('rec_sunday') . '</option></select> ';
		$_recurrenceDataHTML .= '<label for="recurmonthly_ext">' . $this->Language->Get('rec_ofevery') . '</label> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceMonthlyStepextValue . '" name="recurrence_monthly_stepext" id="recurrence_monthly_stepext" onfocus="javascript: $(\'#recurmonthly_ext\').attr(\'checked\', true);" />  <label for="recurmonthly_ext">' . $this->Language->Get('rec_months') . '</label> <br /><br />';
		$_recurrenceDataHTML .= '</div>';

		$_yearlyMonthlyOptions = '<option value="1"' . IIF($_recurrenceYearlyMonthValue == '1', ' selected') . '>' . $this->Language->Get('cal_january') . '</option><option value="2"' . IIF($_recurrenceYearlyMonthValue == '2', ' selected') . '>' . $this->Language->Get('cal_february') . '</option><option value="3"' . IIF($_recurrenceYearlyMonthValue == '3', ' selected') . '>' . $this->Language->Get('cal_march') . '</option><option value="4"' . IIF($_recurrenceYearlyMonthValue == '4', ' selected') . '>' . $this->Language->Get('cal_april') . '</option><option value="5"' . IIF($_recurrenceYearlyMonthValue == '5', ' selected') . '>' . $this->Language->Get('cal_may') . '</option><option value="6"' . IIF($_recurrenceYearlyMonthValue == '6', ' selected') . '>' . $this->Language->Get('cal_june') . '</option><option value="7"' . IIF($_recurrenceYearlyMonthValue == '7', ' selected') . '>' . $this->Language->Get('cal_july') . '</option><option value="8"' . IIF($_recurrenceYearlyMonthValue == '8', ' selected') . '>' . $this->Language->Get('cal_august') . '</option><option value="9"' . IIF($_recurrenceYearlyMonthValue == '9', ' selected') . '>' . $this->Language->Get('cal_september') . '</option><option value="10"' . IIF($_recurrenceYearlyMonthValue == '10', ' selected') . '>' . $this->Language->Get('cal_october') . '</option><option value="11"' . IIF($_recurrenceYearlyMonthValue == '11', ' selected') . '>' . $this->Language->Get('cal_november') . '</option><option value="12"' . IIF($_recurrenceYearlyMonthValue == '12', ' selected') . '>' . $this->Language->Get('cal_december') . '</option>';

		$_recurrenceDataHTML .= '<div id="recurrencecontainer_yearly" style="display: none;"><label for="recuryearly_default"><input type="radio" id="recuryearly_default" name="recurrence_yearly_type" value="default" checked /> ' . $this->Language->Get('rec_every') . '</label> <select class="swiftselect" name="recurrence_yearly_month" id="recurrence_yearly_month" onfocus="javascript: $(\'#recuryearly_default\').attr(\'checked\', true);">' . $_yearlyMonthlyOptions . '</select> <input type="text" class="swifttextnumeric" size="3" value="' . $_recurrenceYearlyMonthdayValue . '" name="recurrence_yearly_monthday" id="recurrence_yearly_monthday" onfocus="javascript: $(\'#recuryearly_default\').attr(\'checked\', true);" /> <br /><br />';
		$_recurrenceDataHTML .= '<label for="recuryearly_ext"><input type="radio" id="recuryearly_ext" name="recurrence_yearly_type" value="extended" ' . $_recurYearlyExtChecked . ' /> ' . $this->Language->Get('rec_the') . '</label> ';
		$_recurrenceDataHTML .= '<select name="recurrence_yearly_extdaystep" id="recurrence_yearly_extdaystep" class="swiftselect" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);"><option value="first" ' . IIF($_recurrenceYearlyExtdaystepValue == "first", "selected") . '>' . $this->Language->Get('rec_first') . '</option><option value="second" ' . IIF($_recurrenceYearlyExtdaystepValue == "second", "selected") . '>' . $this->Language->Get('rec_second') . '</option><option value="third" ' . IIF($_recurrenceYearlyExtdaystepValue == "third", "selected") . '>' . $this->Language->Get('rec_third') . '</option><option value="fourth" ' . IIF($_recurrenceYearlyExtdaystepValue == "first", "fourth") . '>' . $this->Language->Get('rec_fourth') . '</option><option value="fifth" ' . IIF($_recurrenceYearlyExtdaystepValue == "fifth", "selected") . '>' . $this->Language->Get('rec_fifth') . '</option></select> ';
		$_recurrenceDataHTML .= '<select name="recurrence_yearly_extday" id="recurrence_yearly_extday" class="swiftselect" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);"><option value="monday" ' . IIF($_recurrenceYearlyExtdayValue == "monday", "selected") . '>' . $this->Language->Get('rec_monday') . '</option><option value="tuesday" ' . IIF($_recurrenceYearlyExtdayValue == "tuesday", "selected") . '>' . $this->Language->Get('rec_tuesday') . '</option><option value="wednesday" ' . IIF($_recurrenceYearlyExtdayValue == "wednesday", "selected") . '>' . $this->Language->Get('rec_wednesday') . '</option><option value="thursday" ' . IIF($_recurrenceYearlyExtdayValue == "thursday", "selected") . '>' . $this->Language->Get('rec_thursday') . '</option><option value="friday" ' . IIF($_recurrenceYearlyExtdayValue == "friday", "selected") . '>' . $this->Language->Get('rec_friday') . '</option><option value="saturday" ' . IIF($_recurrenceYearlyExtdayValue == "saturday", "selected") . '>' . $this->Language->Get('rec_saturday') . '</option><option value="sunday" ' . IIF($_recurrenceYearlyExtdayValue == "sunday", "selected") . '>' . $this->Language->Get('rec_sunday') . '</option></select> ';
		$_recurrenceDataHTML .= '<label for="recuryearly_ext">' . $this->Language->Get('rec_of') . '</label> <select class="swiftselect" name="recurrence_yearly_extmonth" id="recurrence_yearly_extmonth" onfocus="javascript: $(\'#recuryearly_ext\').attr(\'checked\', true);">' . $_yearlyMonthlyOptions . '</select> <br /><br />';
		$_recurrenceDataHTML .= '</div>';

		$_recurrenceRadioHTML .= '<div class="tabletitle"><label for="recurrence_daily"><input type="radio" onclick="javascript: ToggleRecurrence(\'daily\');" id="recurrence_daily" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_DAILY . '" ' . $_recurrenceDailyChecked . ' /> ' . $this->Language->Get('recurrence_daily') . '</label><br />';
		$_recurrenceRadioHTML .= '<label for="recurrence_weekly"><input type="radio" onclick="javascript: ToggleRecurrence(\'weekly\');" id="recurrence_weekly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_WEEKLY . '" ' . $_recurrenceWeeklyChecked . ' /> ' . $this->Language->Get('recurrence_weekly') . '</label><br />';
		$_recurrenceRadioHTML .= '<label for="recurrence_monthly"><input type="radio" onclick="javascript: ToggleRecurrence(\'monthly\');" id="recurrence_monthly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_MONTHLY . '" ' . $_recurrenceMonthlyChecked . ' /> ' . $this->Language->Get('recurrence_monthly') . '</label><br />';
		$_recurrenceRadioHTML .= '<label for="recurrence_yearly"><input type="radio" onclick="javascript: ToggleRecurrence(\'yearly\');" id="recurrence_yearly" name="recurrencetype" value="' . SWIFT_TicketRecurrence::INTERVAL_YEARLY . '" ' . $_recurrenceYearlyChecked . ' /> ' . $this->Language->Get('recurrence_yearly') . '</label><br /></div>';

		$_columnContainer              = array();
		$_columnContainer[0]['value']  = $_recurrenceRadioHTML;
		$_columnContainer[0]['align']  = 'left';
		$_columnContainer[0]['width']  = '150px';
		$_columnContainer[1]['value']  = $_recurrenceDataHTML;
		$_columnContainer[1]['align']  = 'left';
		$_columnContainer[1]['valign'] = 'top';

		$_RecurrenceTab->Row($_columnContainer);
		$_RecurrenceTab->EndContainer();

		// Range of recurrence
		$_RecurrenceTab->StartContainer('recurrencerangecontainer', false);
		$_RecurrenceTab->Title($this->Language->Get('recurrencerange'), 'icon_doublearrows.gif');
		$_RecurrenceTab->Date('recurrence_start', $this->Language->Get('recur_starts'), '', gmdate(SWIFT_Date::GetCalendarDateFormat(), $_recurrenceStartValue), 0, false, true);

		$_recurrenceEndHTML = '';
		$_recurrenceEndHTML .= '<label for="recurrenceend_noeend"><input type="radio" id="recurrenceend_noeend" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_NOEND . '" ' . $_recurrenceendNoeend . ' /> ' . $this->Language->Get('rec_noeenddate') . '</label><br /><br />';
		$_recurrenceEndHTML .= '<label for="recurrenceend_endoccur"><input type="radio" id="recurrenceend_endoccur" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_OCCURENCES . '" ' . $_recurrenceendEndoccurChecked . '/> ' . $this->Language->Get('rec_endafter') . '</label> <input type="text" class="swifttextnumeric" size="3" name="recurrence_endcount" onfocus="javascript: $(\'#recurrenceend_endoccur\').attr(\'checked\', true);" value = "' . $_recurrenceEndCountValue . '" />  <label for="recurrenceend_endoccur">' . $this->Language->Get('rec_occurrences') . '</label><br /><br />';
		$_recurrenceEndHTML .= '<label for="recurrenceend_enddate"><input type="radio" id="recurrenceend_enddate" name="recurrence_endtype" value="' . SWIFT_TicketRecurrence::END_DATE . '" ' . $_recurrenceendEnddateChecked . ' /> ' . $this->Language->Get('rec_endby') . '</label> <input type="text" name="recurrence_enddateline" id="recur_enddate" size="12" onfocus="javascript: $(\'#recurrenceend_enddate\').attr(\'checked\', true);" class="swifttext" value = "' . $_recurEnddateValue . '" /><script language="Javascript">QueueFunction(function(){ $("#recur_enddate").datepicker(datePickerDefaults); });</script><br />';

		$_columnContainer              = array();
		$_columnContainer[0]['value']  = '<span class="tabletitle">' . $this->Language->Get('recur_ends') . '</span>';
		$_columnContainer[0]['align']  = 'left';
		$_columnContainer[0]['width']  = '150px';
		$_columnContainer[0]['valign'] = 'top';
		$_columnContainer[1]['value']  = $_recurrenceEndHTML;
		$_columnContainer[1]['align']  = 'left';
		$_columnContainer[1]['valign'] = 'top';
		$_RecurrenceTab->Row($_columnContainer);
		$_RecurrenceTab->EndContainer();

		// Render the tickets which are created from recurrence
		$_RecurrenceTab->StartContainer('recurrenceticketscontainer');
		$_RecurrenceTab->Title('Recurrence History', 'icon_doublearrows.gif');

		$_departmentCache     = $_SWIFT->Cache->Get('departmentcache');
		$_ticketStatusCache   = $_SWIFT->Cache->Get('statuscache');
		$_ticketPriorityCache = $_SWIFT->Cache->Get('prioritycache');
		$_ticketTypeCache     = $_SWIFT->Cache->Get('tickettypecache');

		$_recurrenceHistoryContainer = SWIFT_Ticket::RetrieveRecurrenceHistory($_Ticket->GetID());
		// If no record found then try to search from its parent id
		if (!count($_recurrenceHistoryContainer) && $_Ticket->Get('recurrencefromticketid') != '0') {
			$_recurrenceParentTicketID   = $_Ticket->Get('recurrencefromticketid');
			$_recurrenceHistoryContainer = SWIFT_Ticket::RetrieveRecurrenceHistory($_recurrenceParentTicketID);

			$_recurrenceHistoryContainer[$_recurrenceParentTicketID] = SWIFT_Ticket::GetObjectOnID($_recurrenceParentTicketID);
		}

		$_renderHTML = '<table width="100%" cellspacing="0" cellpadding="2" border="0">';
		$_renderHTML .= '<tbody><tr class=""><td valign="middle" align="left" class="gridtabletitlerow" width="16">&nbsp;</td><td valign="middle" align="left" class="gridtabletitlerow" width="120">' . $this->Language->Get('history_ticketid') . '</td><td valign="middle" align="left" class="gridtabletitlerow">' . $this->Language->Get('history_subject') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="160">' . $this->Language->Get('history_date') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="120">' . $this->Language->Get('history_department') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="90">' . $this->Language->Get('history_type') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="100">' . $this->Language->Get('history_status') . '</td><td valign="middle" align="center" class="gridtabletitlerow" width="90">' . $this->Language->Get('history_priority') . '</td></tr>';

		$_historyCount = 0;
		foreach ($_recurrenceHistoryContainer as $_ticketID => $_Ticket_History) {

			if ($_Ticket->GetID() == $_ticketID) {
				continue;
			}

			$_historyCount++;

			$_subjectSuffix = $_ticketURLPrefix = $_ticketURLSuffix = $_departmentHTML = $_typeHTML = $_statusHTML = $_priorityHTML = $_statusStyle = $_priorityStyle = '';

			$_ticketIcon = 'icon_ticket.png';
			if (!$_Ticket_History->CanAccess($_SWIFT->Staff)) {
				$_ticketIcon = 'icon_lock.gif';
			} else {
				$_ticketURL       = SWIFT::Get('basename') . '/Tickets/Ticket/View/' . intval($_Ticket_History->GetID());
				$_ticketURLPrefix = '<a href="javascript: void(0);" onclick="javascript: loadViewportData(\'' . $_ticketURL . '\');">';
				$_ticketURLSuffix = '</a>';
				$_subjectSuffix .= '&nbsp;<a href="' . $_ticketURL . '" target="_blank"><img src="' . SWIFT::Get('themepathimages') .
					'icon_newwindow_gray.png' . '" align="absmiddle" border="0" /></a>&nbsp;';
			}
			$_ticketIconHTML = '<img src="' . SWIFT::Get('themepath') . 'images/' . $_ticketIcon . '" align="absmiddle" border="0" />';

			// Department
			if (isset($_departmentCache[$_Ticket_History->Get('departmentid')])) {
				$_departmentHTML = htmlspecialchars(StripName($_departmentCache[$_Ticket_History->Get('departmentid')]['title'], 15));
			} else {
				$_departmentHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Status
			if (isset($_ticketStatusCache[$_Ticket_History->Get('ticketstatusid')])) {
				$_ticketStatusContainer = $_ticketStatusCache[$_Ticket_History->Get('ticketstatusid')];
				$_displayIconImage      = '';
				if (!empty($_ticketStatusContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketStatusContainer['displayicon']) .
						'" align="absmiddle" border="0" /> ';
				}

				$_statusHTML = $_displayIconImage . htmlspecialchars(StripName($_ticketStatusContainer['title'], 15));
			} else {
				$_statusHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Priority
			if (isset($_ticketPriorityCache[$_Ticket_History->Get('priorityid')])) {
				$_ticketPriorityContainer = $_ticketPriorityCache[$_Ticket_History->Get('priorityid')];
				$_displayIconImage        = '';
				if (!empty($_ticketPriorityContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketPriorityContainer['displayicon']) .
						'" align="absmiddle" border="0" /> ';
				}

				$_priorityHTML  = $_displayIconImage . htmlspecialchars(StripName($_ticketPriorityContainer['title'], 15));
				$_priorityStyle = 'background-color: ' . $_ticketPriorityContainer['bgcolorcode'] . '; color: ' .
					$_ticketPriorityContainer['frcolorcode'] . ';';
			} else {
				$_priorityHTML = $_SWIFT->Language->Get('na');
			}

			// Ticket Type
			if (isset($_ticketTypeCache[$_Ticket_History->Get('tickettypeid')])) {
				$_ticketTypeContainer = $_ticketTypeCache[$_Ticket_History->Get('tickettypeid')];
				$_displayIconImage    = '';
				if (!empty($_ticketTypeContainer['displayicon'])) {
					$_displayIconImage = '<img src="' . ProcessDisplayIcon($_ticketTypeContainer['displayicon']) .
						'" align="absmiddle" border="0" /> ';
				}

				$_typeHTML = $_displayIconImage . htmlspecialchars(StripName($_ticketTypeContainer['title'], 15));
			} else {
				$_typeHTML = $_SWIFT->Language->Get('na');
			}

			$_renderHTML .= '<tr class="tablerow1_tr"><td valign="middle" align="center" class="tablerow1">' . $_ticketIconHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_ticketURLPrefix . $_Ticket_History->GetTicketDisplayID() . $_ticketURLSuffix . '</td>';
			$_renderHTML .= '<td valign="middle" align="left" class="tablerow1">' . $_ticketURLPrefix . htmlspecialchars($_Ticket_History->Get('subject')) . $_ticketURLSuffix . '<span style="float: right;">' . $_subjectSuffix . '</span></td>';
			$_renderHTML .= '<td valign="middle" align="center" class="tablerow1">' . SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_Ticket_History->Get('dateline')) . '</td>';
			$_renderHTML .= '<td valign="middle" align="center" class="tablerow1">' . $_departmentHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="center" class="tablerow1">' . $_typeHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="center" class="tablerow1">' . $_statusHTML . '</td>';
			$_renderHTML .= '<td valign="middle" align="center" class="tablerow1" style="' . $_priorityStyle . '">' . $_priorityHTML . '</td>';
			$_renderHTML .= '</tr>';
		}

		if ($_historyCount == 0) {
			$_renderHTML .= '<tr class="tablerow1_tr"><td valign="middle" align="left" class="tablerow1" colspan="8">' . $this->Language->Get('noinfoinview') . '</td></tr>';
		}
		$_renderHTML .= '</tbody></table>';

		$_columnContainer              = array();
		$_columnContainer[0]['value']  = $_renderHTML;
		$_columnContainer[0]['align']  = 'left';
		$_columnContainer[0]['valign'] = 'top';
		$_RecurrenceTab->Row($_columnContainer);
		$_RecurrenceTab->EndContainer();

		$_renderHTML = $_RecurrenceTab->GetDisplayHTML(true);

		$_recurrenceScriptHTML = '';
		if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_DAILY) {
			$_recurrenceScriptHTML = 'ToggleRecurrence(\'daily\');';
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_WEEKLY) {
			$_recurrenceScriptHTML = 'ToggleRecurrence(\'weekly\');';
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_MONTHLY) {
			$_recurrenceScriptHTML = 'ToggleRecurrence(\'monthly\');';
		} else if ($_TicketRecurrence->Get('intervaltype') == SWIFT_TicketRecurrence::INTERVAL_YEARLY) {
			$_recurrenceScriptHTML = 'ToggleRecurrence(\'yearly\');';
		}

		$_renderHTML .= '<script language="Javascript" type="text/javascript">';
		$_renderHTML .= 'ClearFunctionQueue();';
		$_renderHTML .= $_recurrenceScriptHTML;
		$_renderHTML .= '</script>';

		echo $_renderHTML;


		return true;
	}

	/**
	 * Get the XML Flag Menu
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function GetFlagMenu(SWIFT_Ticket $_SWIFT_TicketObject) {
		$_SWIFT = SWIFT::GetInstance();

		$_ticketURLSuffix        = SWIFT::Get('ticketurlsuffix');
		$_SWIFT_TicketFlagObject = new SWIFT_TicketFlag();
		$_ticketFlagContainer    = $_SWIFT_TicketFlagObject->GetFlagContainer();

		$_flagHTML = '<ul class="swiftdropdown" id="ticketflagmenu">';

		foreach ($_ticketFlagContainer as $_ticketFlagType => $_ticketFlag) {
			$_flagHTML .= '<li class="swiftdropdownitemparent" onclick="javascript: loadViewportData(\'/Tickets/Ticket/Flag/' . $_SWIFT_TicketObject->GetTicketID() . '/' . $_ticketFlagType . '/' . $_ticketURLSuffix . '\');"><div class="swiftdropdownitem"><div class="swiftdropdownitemimage"><img src="' . SWIFT::Get('themepath') . 'images/' . $_ticketFlag[3] . '" align="absmiddle" border="0" /></div><div class="swiftdropdownitemtext" onclick="javascript: void(0);">' . $_ticketFlag[0] . '</div></div></li>';
		}

		$_flagHTML .= '</ul>';

		return $_flagHTML;
	}

	/**
	 * Render Split/Duplicate dialog box
	 *
	 * @author Simaranjit Singh
	 *
	 * @param int $_ticketID
	 * @param int $_mode Split or duplicate
	 *
	 * @return bool
	 * @throws SWIFT_Exception If the Class is not Loaded OR If Invalid Data is Provided
	 */
	public function RenderSplitOrDuplicate($_ticketID, $_mode)
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
		}

		$this->Language->Load('tickets', SWIFT_LanguageEngine::TYPE_DB);

		$_phrase = IIF($_mode == SWIFT_TICKET::MODE_SPLIT, 'split', 'duplicate');

		$this->UserInterface->Start('ticketsplitform', '/Tickets/Ticket/SplitOrDuplicateSubmit', SWIFT_UserInterface::MODE_INSERT, true, false);

		$_Tab = $this->UserInterface->AddTab($this->Language->Get($_phrase . 'ticket'), 'icon_form.gif', 'general', true);

		// Display the ticket owner, department and title
		$_Ticket = new SWIFT_Ticket(new SWIFT_DataID($_ticketID));

		if (!$_Ticket instanceof SWIFT_Ticket || !$_Ticket->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);
		}

		$_departmentCache = $this->Cache->Get('departmentcache');
		$_departmentTitle = $this->Language->Get('na');

		if ($_Ticket->Get('departmentid') == '0') {
			$_departmentTitle = $this->Language->Get('trash');
		} else if (isset($_departmentCache[$_Ticket->Get('departmentid')])) {
			$_departmentTitle = $_departmentCache[$_Ticket->Get('departmentid')]['title'];
		}

		$_User = $_Ticket->GetUserObject();

		/**
		 * BUG FIX - Ravi Sharma <ravi.sharma@kayako.com>
		 *
		 * SWIFT-4343: Security Issue
		 */
		$_Tab->Title($this->Language->Get('oldticket'));
		$_Tab->DefaultDescriptionRow($this->Language->Get('st_subject'), '', $this->Input->SanitizeForXSS($_Ticket->Get('subject')));
		$_Tab->DefaultDescriptionRow($this->Language->Get('st_fullname'), '', $this->Input->SanitizeForXSS($_User->GetFullName()));
		$_Tab->DefaultDescriptionRow($this->Language->Get('st_department'), '', $_departmentTitle);

		// Display the list of posts in date order
		$_ticketPostContainer = $_Ticket->GetTicketPosts(false, false, 'DESC');

		$_ticketPosts = array();
		foreach ($_ticketPostContainer as $_ticketPostID => $_ticketPostList) {
			$_ticketPosts[] = array(
				"value" => $_ticketPostID,
				"title" => SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_ticketPostList->Get('dateline')) . " (" . $_ticketPostList->Get('fullname') . ")"
			);
		}

		$_Tab->Title($this->Language->Get('newticket'));
		$_Tab->Text('newtitle', $this->Language->Get('st_subject'), '', $_Ticket->Get('subject'));

		if ($_mode == SWIFT_TICKET::MODE_SPLIT && $_Ticket->Get('isresolved') == '0') {
			unset($_ticketPosts[count($_ticketPosts) - 1]);
			$_Tab->YesNo('closeold', $this->Language->Get('closeold'));
		} else {
			$_Tab->Hidden('closeold', 0);
		}

		$_Tab->Select('splitat', $this->Language->Get($_phrase . 'at'), $this->Language->Get($_phrase . 'at_d'), $_ticketPosts);

		$_Tab->Hidden('ticketid', $_ticketID);
		$_Tab->Hidden('operationmode', $_mode);

		return $this->UserInterface->End();
	}
}
