function allowed_organizer_access(&$itechthis)
{
    require_once 'models/table/MultiOptionList.php';
    $allowIds = false;
    if (!$itechthis->hasACL('training_organizer_option_all')) {
        $allowIds = array();
        $user_id = $itechthis->isLoggedIn();
        $training_organizer_array = MultiOptionList::choicesList('user_to_organizer_access', 'user_id', $user_id, 'training_organizer_option', 'training_organizer_phrase', false, false);
        foreach ($training_organizer_array as $orgOption) {
            if ($orgOption['user_id']) {
                $allowIds[] = $orgOption['id'];
            }
        }
    }
    return $allowIds;
}
 protected function _importHelperFindOrCreateMOLT($table, $col, $val, $multiAssignTable = null, $training_id = null, $extra = null)
 {
     require_once 'models/table/MultiOptionList.php';
     $val = $this->sanitize($val);
     // todo check acls
     if (empty($val)) {
         return true;
     }
     $option_id = '';
     $results = array();
     if (!is_array($val)) {
         $val = array($val);
     }
     // handle single values (string input) too
     foreach ($val as $key => $value) {
         $option_id = '';
         $tableCustom = new ITechTable(array('name' => $table));
         $value = trim($value);
         $row = $tableCustom->fetchRow($tableCustom->select()->where("{$col} = ?", $value));
         if (!$row) {
             $row = $tableCustom->createRow();
             $row->{$col} = $value;
             if (isset($row->is_default)) {
                 $row->is_default = 0;
             }
             //unset on import, we prob dont want this.
             $option_id = $row->save();
         } else {
             $option_id = $row->id;
         }
         $results[] = $option_id;
     }
     if (!$training_id) {
         return count($results) ? true : false;
     }
     try {
         switch ($multiAssignTable) {
             case 'funding':
                 MultiOptionList::updateOptions('training_to_training_funding_option', 'training_funding_option', 'training_id', $training_id, 'training_funding_option_id', $results, 'funding_amount', $extra);
                 break;
             case 'pepfar':
                 MultiOptionList::updateOptions('training_to_training_pepfar_categories_option', 'training_pepfar_categories_option', 'training_id', $training_id, 'training_pepfar_categories_option_id', $results, 'duration_days', $extra);
                 break;
             case 'topic':
                 MultiOptionList::updateOptions('training_to_training_topic_option', 'training_topic_option', 'training_id', $training_id, 'training_topic_option_id', $results);
                 break;
             case 'refresher':
                 MultiOptionList::updateOptions('training_to_training_refresher_option', 'training_refresher_option', 'training_id', $training_id, 'training_refresher_option_id', $results);
                 break;
         }
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
 public function editAction()
 {
     if (!$this->hasACL('edit_course')) {
         $this->doNoAccessError();
     }
     $db = Zend_Db_Table_Abstract::getDefaultAdapter();
     $request = $this->getRequest();
     $validateOnly = $request->isXmlHttpRequest();
     $status = ValidationContainer::instance();
     if ($validateOnly) {
         $this->setNoRenderer();
     }
     // populate form
     $allowIds = false;
     // todo test
     if (!$this->hasACL('training_organizer_option_all')) {
         $allowIds = array();
         $user_id = $this->isLoggedIn();
         $training_organizer_array = MultiOptionList::choicesList('user_to_organizer_access', 'user_id', $user_id, 'training_organizer_option', 'training_organizer_phrase', false, false);
         foreach ($training_organizer_array as $orgOption) {
             if ($orgOption['user_id']) {
                 $allowIds[] = $orgOption['id'];
             }
         }
     }
     $id = $this->getSanParam('id');
     if ($id && !empty($id)) {
         $sql = 'select * from organizer_partners where id = ' . $id;
         $partner_row = $db->fetchRow($sql);
         if ($partner_row !== false) {
             $this->view->assign('partner', $partner_row);
         } else {
             $this->view->assign('mode', 'add');
             $status->setStatusMessage(t('That partner could not be found.'));
         }
     } else {
         $this->view->assign('mode', 'add');
     }
     $this->view->assign('dropDownOrg', DropDown::generateHtml('training_organizer_option', 'training_organizer_phrase', isset($partner_row) ? $partner_row['organizer_id'] : '', $this->hasACL('training_organizer_option_all') ? 'training/insert-table' : false, $this->view->viewonly, $this->view->viewonly ? false : $allowIds));
     // form submit?
     if ($request->isPost()) {
         $obj = new TrainingPartner();
         if ($this->view->mode == 'add') {
             $obj_id = $this->validateAndSave($obj->createRow(), false);
         } else {
             $partnerRow = $obj->fetchRow('id = ' . $id);
             $obj_id = $this->validateAndSave($partnerRow, false);
         }
         if ($obj_id) {
             // success
             $status->setObjectId($obj_id);
             $id = $obj_id;
             $status->setStatusMessage(t('The partner was saved.'));
             if ($this->view->mode == 'add') {
                 $status->redirect = Settings::$COUNTRY_BASE_URL . '/training-partner/edit/id/' . $id;
             }
             if (!$validateOnly || $this->view->mode == 'add') {
                 // refreshing also
                 $_SESSION['status'] = t('The partner was saved.');
             }
         }
         if (!$obj_id) {
             // fail
             $status->setStatusMessage(t('ERROR: The partner could not be saved.'));
         }
         if ($validateOnly) {
             $this->sendData($status);
         } else {
             $this->view->assign('status', $status);
             $this->_redirect('training-partner/edit/id/' . $id);
         }
     }
 }
 public function editAction()
 {
     if (!$this->hasACL('edit_employee')) {
         $this->doNoAccessError();
     }
     $db = $this->dbfunc();
     $status = ValidationContainer::instance();
     $params = $this->getAllParams();
     $id = $params['id'];
     #// restricted access?? only show partners by organizers that we have the ACL to view // - removed 5/1/13, they dont want this, its used by site-rollup (datashare), and user-restrict by org.
     #$org_allowed_ids = allowed_org_access_full_list($this); // doesnt have acl 'training_organizer_option_all'
     #$site_orgs = allowed_organizer_in_this_site($this); // for sites to host multiple training organizers on one domain
     #$siteOrgsClause = $site_orgs ? " AND partner.organizer_option_id IN ($site_orgs)" : "";
     #if ($org_allowed_ids && $this->view->mode != 'add') {
     #	$validID = $db->fetchCol("SELECT partner.id FROM partner WHERE partner.id = $id AND partner.organizer_option_id in ($org_allowed_ids) $siteOrgsClause");
     #	if(empty($validID))
     #		$this->doNoAccessError ();
     #
     #}
     if ($this->getRequest()->isPost()) {
         //validate then save
         $status->checkRequired($this, 'partner', t('Partner'));
         if ($this->setting('display_partner_type')) {
             $status->checkRequired($this, 'partner_type_option_id', t('Type of Partner'));
         }
         $status->checkRequired($this, 'address1', t('Address 1'));
         $status->checkRequired($this, 'address2', t('Address 2'));
         $status->checkRequired($this, 'province_id', t('Region A (Province)'));
         $status->checkRequired($this, 'phone', t('Phone'));
         $status->checkRequired($this, 'fax', t('Fax'));
         if ($this->setting('display_employee_funder')) {
             $status->checkRequired($this, 'partner_funder_option_id[]', t('Funder'));
         }
         #$status->checkRequired ( $this, 'funding_end_date[]',             t ( 'Funding End Date' ) );
         #if ($this->setting('display_employee_intended_transition'))
         #	$status->checkRequired ( $this, 'employee_transition_option_id',  t ( 'Intended Transition' ) );
         if ($this->setting('display_employee_agreement_end_date')) {
             $status->checkRequired($this, 'agreement_end_date', t('Agreement End Date'));
         }
         if ($this->setting('display_employee_importance')) {
             $status->checkRequired($this, 'partner_importance_option_id', t('Importance'));
         }
         #$status->checkRequired ( $this, 'comments',                       t ( 'Partner Comments' ) );
         #$status->checkRequired ( $this, 'subpartner_id[]',                t ( 'Sub Partner' ) );
         $params['funding_end_date'] = $this->_array_me($params['funding_end_date']);
         foreach ($params['funding_end_date'] as $i => $value) {
             $params['funding_end_date'][$i] = $this->_date_to_sql($value);
         }
         $params['transition_confirmed'] = $params['transition_confirmed'] == 'on' ? 1 : 0;
         $params['agreement_end_date'] = $this->_date_to_sql($params['agreement_end_date']);
         $params['subpartner_id'] = $this->_array_me($params['subpartner_id']);
         foreach ($params['subpartner_id'] as $i => $value) {
             // strip empty values (it breaks MultiOptionList apparently)
             if (empty($value)) {
                 unset($params['subpartner_id'][$i]);
             }
         }
         //location save stuff
         $params['location_id'] = regionFiltersGetLastID(null, $params);
         // formprefix, criteria
         if ($params['city']) {
             $params['location_id'] = Location::insertIfNotFound($params['city'], $params['location_id'], $this->setting('num_location_tiers'));
         }
         if (!$status->hasError()) {
             $id = $this->_findOrCreateSaveGeneric('partner', $params);
             if (!$id) {
                 $status->setStatusMessage(t('That partner could not be saved.'));
             } else {
                 MultiOptionList::updateOptions('partner_to_funder', 'partner_funder_option', 'partner_id', $id, 'partner_funder_option_id', $params['partner_funder_option_id'], 'funder_end_date', $params['funding_end_date']);
                 $db->query("DELETE FROM partner_to_subpartner WHERE partner_id = {$id}");
                 // updateOptions is not clearing the old options, I dont know why... todo
                 MultiOptionList::updateOptions('partner_to_subpartner', 'partner', 'partner_id', $id, 'subpartner_id', $params['subpartner_id']);
                 $status->setStatusMessage(t('The partner was saved.'));
                 $this->_redirect("partner/edit/id/{$id}");
             }
         }
     }
     if ($id) {
         // read data from db
         #// restricted access?? only show partners by organizers that we have the ACL to view
         #$org_allowed_ids = allowed_org_access_full_list($this); // doesnt have acl 'training_organizer_option_all'
         #$orgWhere = ($org_allowed_ids) ? " AND partner.organizer_option_id in ($org_allowed_ids) " : "";
         #// restricted access?? only show organizers that belong to this site if its a multi org site
         #$site_orgs = allowed_organizer_in_this_site($this); // for sites to host multiple training organizers on one domain
         #$allowedWhereClause .= $site_orgs ? " AND partner.organizer_option_id in ($site_orgs) " : "";
         // continue reading data
         $sql = 'SELECT * FROM partner WHERE id = ' . $id . space . $orgWhere;
         $row = $db->fetchRow($sql);
         if (!$row) {
             $status->setStatusMessage(t('Error finding that record in the database.'));
         } else {
             $params = $row;
             // reassign form data
             $region_ids = Location::getCityInfo($params['location_id'], $this->setting('num_location_tiers'));
             $params['city'] = $region_ids[0];
             $region_ids = Location::regionsToHash($region_ids);
             $params = array_merge($params, $region_ids);
             //get linked table data from option tables
             $sql = "SELECT partner_funder_option_id,funder_end_date FROM partner_to_funder WHERE partner_id = {$id}";
             $params['funder'] = $db->fetchAll($sql);
             $sql = "SELECT subpartner_id FROM partner_to_subpartner WHERE partner_id = {$id}";
             $params['subpartners'] = $db->fetchCol($sql);
         }
     }
     // make sure form data is valid for display
     if (empty($params['funder'])) {
         $params['funder'] = array(array());
     }
     if (empty($params['subpartners'])) {
         $params['subpartners'] = array(' ');
     }
     // assign form drop downs
     $this->view->assign('status', $status);
     $this->view->assign('pageTitle', $this->view->mode == 'add' ? t('Add Partner') : t('View Partner'));
     $this->viewAssignEscaped('partner', $params);
     $this->viewAssignEscaped('locations', Location::getAll());
     $this->view->assign('partners', DropDown::generateHtml('partner', 'partner', $params['partner_type_option_id'], false, $this->view->viewonly, false));
     //table, col, selected_value
     $this->view->assign('subpartners', DropDown::generateHtml('partner', 'partner', 0, false, $this->view->viewonly, false, true, array('name' => 'subpartner_id[]'), true));
     $this->view->assign('types', DropDown::generateHtml('partner_type_option', 'type_phrase', $params['partner_type_option_id'], false, $this->view->viewonly, false));
     $this->view->assign('importance', DropDown::generateHtml('partner_importance_option', 'importance_phrase', $params['partner_importance_option_id'], false, $this->view->viewonly, false));
     $this->view->assign('transitions', DropDown::generateHtml('employee_transition_option', 'transition_phrase', $params['employee_transition_option_id'], false, $this->view->viewonly, false));
     $this->view->assign('incomingPartners', DropDown::generateHtml('partner', 'partner', $params['incoming_partner'], false, $this->view->viewonly, false, true, array('name' => 'incoming_partner'), true));
     $this->view->assign('organizers', DropDown::generateHtml('training_organizer_option', 'training_organizer_phrase', $params['organizer_option_id'], false, $this->view->viewonly, false, true, array('name' => 'organizer_option_id'), true));
     $helper = new Helper();
     $this->viewAssignEscaped('facilities', $helper->getFacilities());
 }
 public function myaccountAction()
 {
     if (!$this->isLoggedIn()) {
         $this->doNoAccessError();
     }
     if (!($user_id = $this->isLoggedIn())) {
         $this->doNoAccessError();
     }
     if ($this->view->mode == 'edit') {
         $user_id = $this->getSanParam('id');
     }
     $request = $this->getRequest();
     $validateOnly = $request->isXmlHttpRequest();
     if ($validateOnly) {
         $this->setNoRenderer();
     }
     $user = new User();
     $userRow = $user->find($user_id)->current();
     if ($request->isPost()) {
         $status = ValidationContainer::instance();
         //validate
         $status->checkRequired($this, 'first_name', 'First name');
         $status->checkRequired($this, 'last_name', 'Last name');
         $status->checkRequired($this, 'username', 'Login');
         $status->checkRequired($this, 'email', 'Email');
         //valid email?
         $validator = new Zend_Validate_EmailAddress();
         if (!$validator->isValid($this->_getParam('email'))) {
             $status->addError('email', 'That email address does not appear to be valid.');
         }
         if (strlen($this->_getParam('username')) < 3) {
             $status->addError('username', 'Usernames should be at least 3 characters in length.');
         }
         //changing usernames?
         if ($this->_getParam('username') != $userRow->username) {
             //check unique username and email
             if ($uniqueArray = User::isUnique($this->getSanParam('username'))) {
                 if (isset($uniqueArray['username'])) {
                     $status->addError('username', 'That username is already in use. Please choose another one.');
                 }
             }
         }
         //changing email?
         if ($this->_getParam('email') != $userRow->email) {
             //check unique username and email
             if ($uniqueArray = User::isUnique(false, $this->getSanParam('email'))) {
                 if (isset($uniqueArray['email'])) {
                     $status->addError('email', 'That email address is already in use. Please choose another one.');
                 }
             }
         }
         //changing passwords?
         $passwordChange = false;
         if (strlen($this->_getParam('password')) > 0 and strlen($this->_getParam('confirm_password')) > 0) {
             if (strlen($this->_getParam('password')) < 6) {
                 $status->addError('password', 'Passwords should be at least 6 characters in length.');
             }
             if ($this->_getParam('password') != $this->_getParam('confirm_password')) {
                 $status->addError('password', 'Password fields do not match. Please enter them again.');
             }
             $passwordChange = true;
         }
         if ($status->hasError()) {
             $status->setStatusMessage('Your account information could not be saved.');
         } else {
             $params = $this->_getAllParams();
             if (!$passwordChange) {
                 unset($params['password']);
             }
             self::fillFromArray($userRow, $params);
             if ($userRow->save()) {
                 $status->setStatusMessage('Your account information was saved.');
                 if ($this->view->mode == 'edit') {
                     $this->saveAclCheckboxes($user_id);
                 }
                 if ($passwordChange == true) {
                     $email = $this->_getParam('email');
                     if (trim($email) != '') {
                         $view = new Zend_View();
                         $view->setScriptPath(Globals::$BASE_PATH . '/app/views/scripts/email');
                         $view->assign('first_name', $this->_getParam('first_name'));
                         $view->assign('username', $this->_getParam('username'));
                         $view->assign('password', $this->_getParam('password'));
                         $text = $view->render('text/password_changed.phtml');
                         $html = $view->render('html/password_changed.phtml');
                         $mail = new Zend_Mail();
                         $mail->setBodyText($text);
                         $mail->setBodyHtml($html);
                         $mail->setFrom(Settings::$EMAIL_ADDRESS, Settings::$EMAIL_NAME);
                         $mail->addTo($this->_getParam('email'), $this->getSanParam('first_name') . " " . $this->getSanParam('last_name'));
                         $mail->setSubject('Password Changed');
                         $mail->send();
                     }
                 }
             } else {
                 $status->setStatusMessage('Your account information could not be saved.');
             }
         }
         if ($validateOnly) {
             $this->sendData($status);
         } else {
             $this->view->assign('status', $status);
         }
     }
     $userArray = $userRow->toArray();
     if ($this->view->mode == 'edit') {
         //set acls
         $acls = User::getACLs($user_id);
         $userArray['acls'] = $acls;
     }
     $training_organizer_array = MultiOptionList::choicesList('user_to_organizer_access', 'user_id', $user_id, 'training_organizer_option', 'training_organizer_phrase', false, false);
     $this->viewAssignEscaped('training_organizer', $training_organizer_array);
     $this->viewAssignEscaped('user', $userArray);
     if ($this->hasACL('pre_service')) {
         $helper = new Helper();
         $this->view->assign('showinstitutions', true);
         $this->view->assign('institutions', $helper->getInstitutions());
         // Getting current credentials
         $auth = Zend_Auth::getInstance();
         $identity = $auth->getIdentity();
         $this->view->assign('userinstitutions', $helper->getUserInstitutions($user_id));
     } else {
         $this->view->assign('showinstitutions', false);
     }
 }
 /**
  * Matches as posted set of multiple drop downs or checkboxes with an option list intersection table.
  * May update extra column within linktable
  */
 public static function updateOptions($linktable, $optionLookupTable, $owner_col, $owner_id, $option_col, $valuesFromPost, $extra_col = '', $extra_values = array())
 {
     return MultiOptionList::updateOptions($linktable, $optionLookupTable, $owner_col, $owner_id, $option_col, $valuesFromPost, $extra_col, $extra_values);
 }
 public function assignTrainingAction()
 {
     $id = $this->getSanParam('id');
     $this->view->assign('id', $id);
     require_once 'models/table/Training.php';
     require_once 'models/table/OptionList.php';
     $training = new Training();
     $rows = $training->find($id);
     $row = $rows->current();
     $this->view->assign('training', $row);
     $this->view->assign('training_name', $training->getCourseName($id));
     $evaluations = OptionList::suggestionList('evaluation', array('id', 'title'));
     $this->view->assign('evaluations', $evaluations);
     //find currently selected
     $evalTable = new OptionList(array('name' => 'evaluation_to_training'));
     $select = $evalTable->select()->from('evaluation_to_training', array('evaluation_id'))->where('training_id = ' . $id);
     $row = $evalTable->fetchRow($select);
     if ($row) {
         $this->view->assign('evaluation_id', $row->evaluation_id);
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $status = ValidationContainer::instance();
         $evaluation_id = $this->getSanParam('evaluation_id');
         $status->setStatusMessage(t('The evaluation has been assigned.'));
         $eval_id = $this->getSanParam('evaluation_id');
         require_once 'models/table/MultiOptionList.php';
         MultiOptionList::updateOptions('evaluation_to_training', 'evaluation', 'training_id', $id, 'evaluation_id', array($eval_id => $eval_id));
         $status->setRedirect('/training/edit/id/' . $id);
         $this->sendData($status);
     }
 }
 private function doAddEditView()
 {
     if (!$this->hasACL('edit_course')) {
         $this->view->assign('viewonly', 'disabled="disabled"');
         $this->view->assign('pageTitle', t('View') . ' ' . t('Training'));
     }
     // edittable ajax (remove/update/etc)
     if ($this->_getParam('edittable')) {
         $this->ajaxeditTable();
         return;
     }
     require_once 'models/table/MultiOptionList.php';
     require_once 'models/table/TrainingLocation.php';
     require_once 'models/table/Location.php';
     require_once 'models/table/System.php';
     require_once 'views/helpers/EditTableHelper.php';
     require_once 'views/helpers/DropDown.php';
     require_once 'views/helpers/FileUpload.php';
     // allow multiple pepfars?
     if (!$this->setting('allow_multi_pepfar')) {
         $this->NUM_PEPFAR = 1;
     }
     // get translation labels
     // $this->view->assign('labels', Translation::getAll());
     //validate
     $status = ValidationContainer::instance();
     $request = $this->getRequest();
     $validateOnly = $request->isXmlHttpRequest();
     $training_id = $this->getSanParam('id');
     $is_new = $this->getSanParam('new') || !$training_id;
     // new training -- use defaults
     $this->view->assign('is_new', $is_new);
     $trainingObj = new Training();
     $row = $trainingObj->findOrCreate($training_id);
     $rowRay = @$row->toArray();
     //filter training orgs by user access
     $allowIds = false;
     if (!$this->hasACL('training_organizer_option_all')) {
         $allowIds = array();
         $user_id = $this->isLoggedIn();
         $training_organizer_array = MultiOptionList::choicesList('user_to_organizer_access', 'user_id', $user_id, 'training_organizer_option', 'training_organizer_phrase', false, false);
         foreach ($training_organizer_array as $orgOption) {
             if ($orgOption['user_id']) {
                 $allowIds[] = $orgOption['id'];
             }
         }
     }
     if ($this->_getParam('action') != 'add' and !$this->hasACL('training_organizer_option_all') and (!$allowIds or array_search($rowRay['training_organizer_option_id'], $allowIds) === false)) {
         $this->view->assign('viewonly', 'disabled="disabled"');
         $this->view->assign('pageTitle', t('View') . ' ' . t('Training'));
     }
     if ($row->is_deleted) {
         $this->_redirect('training/deleted');
         return;
     }
     $courseRow = $trainingObj->getCourseInfo($training_id);
     $rowRay['training_title'] = $courseRow ? $courseRow->training_title_phrase : '';
     $rowRay['training_title_option_id'] = $courseRow ? $courseRow->training_title_option_id : 0;
     // does not exist
     if (!$row->id && $this->_getParam('action') != 'add') {
         $this->_redirect('training/index');
     }
     if ($validateOnly) {
         $this->setNoRenderer();
     }
     $age_opts = OptionList::suggestionList('age_range_option', array('id', 'age_range_phrase'), false, 100, false);
     if ($request->isPost() && !$this->getSanParam('edittabledelete')) {
         //$status->checkRequired($this, 'training_title_option_id',t('Training Name'));
         //$status->checkRequired($this, 'training_category_and_title_option_id',t('Training Name'));
         $status->checkRequired($this, 'training_length_value', t('Training') . ' ' . t('Length'));
         $status->checkRequired($this, 'training_length_interval', t('Training') . ' ' . t('Interval'));
         //$status->checkRequired($this, 'training_organizer_option_id',t('Training Organizer'));
         //$status->checkRequired($this, 'training_level_option_id',t('Training Level'));
         //$status->checkRequired($this, 'training_location_id',t('Training Location'));
         //$status->checkRequired($this, 'training_topic_option_id','Training Topic');
         // May be "0" value
         if (!$this->getSanParam('training_length_value')) {
             $status->addError('training_length_value', t('Training length is required.'));
         }
         // validate score averages values
         if ($score = trim($this->getSanParam('pre'))) {
             if (!is_numeric($score)) {
                 $status->addError('pre', $this->view->translation['Pre Test Score'] . ' ' . t('must be numeric.'));
             } elseif ($score < 0 || $score > 100) {
                 $status->addError('pre', $this->view->translation['Pre Test Score'] . ' ' . t('must be between 1-100.'));
             }
         }
         if ($score = trim($this->getSanParam('post'))) {
             if (!is_numeric($score)) {
                 $status->addError('post', $this->view->translation['Post Test Score'] . ' ' . t('must be numeric.'));
             } elseif ($score < 0 || $score > 100) {
                 $status->addError('post', $this->view->translation['Post Test Score'] . ' ' . t('must be between 1-100.'));
             }
         }
         if ($this->getSanParam('start-year') == "" || $this->getSanParam('start-month') == "" || $this->getSanParam('start-day') == "") {
             $status->addError('start-day', t('Start date is required.'));
         }
         $training_start_date = @$this->getSanParam('start-year') . '-' . @$this->getSanParam('start-month') . '-' . @$this->getSanParam('start-day');
         if ($training_start_date !== '--' and $training_start_date !== '0000-00-00') {
             $status->isValidDate($this, 'start-day', t('Training') . ' ' . t('start'), $training_start_date);
         }
         if ($this->setting('display_end_date')) {
             $training_end_date = @$this->getSanParam('end-year') . '-' . @$this->getSanParam('end-month') . '-' . @$this->getSanParam('end-day');
             if ($training_end_date !== '--' and $training_end_date !== '0000-00-00') {
                 $status->isValidDate($this, 'end-day', t('Training') . ' ' . t('end'), $training_end_date);
             }
             if ($training_end_date != '--') {
                 if (strtotime($training_end_date) < strtotime($training_start_date)) {
                     $status->addError('end-day', t('End date must be after start date.'));
                 }
             }
         }
         $pepfarEnabled = @$this->setting('display_training_pepfar');
         if ($training_id) {
             $pepfarCount = 0;
             $pepfar_array = $this->getSanParam('training_pepfar_categories_option_id');
             if ($pepfar_array) {
                 foreach ($pepfar_array as $p) {
                     if ($p) {
                         $pepfarCount++;
                     }
                 }
             }
             //          if (!$pepfarCount) {
             //            $status->addError('training_pepfar_categories_option',t('PEPFAR is required.'));
             //         }
             // pepfar (multiple days)
             if ($this->getSanParam('pepfar_days') && $pepfarEnabled) {
                 $pepfarTotal = 0;
                 foreach ($this->getSanParam('pepfar_days') as $key => $value) {
                     if (!is_numeric($value)) {
                         $value = ereg_replace("/^[.0-9]", "", $value);
                     }
                     //$daysRay [$pepfar_array[$key]] = $value; //set the days key to  the pepfar id
                     $daysRay[$key] = $value;
                     //set the days key to  the pepfar id
                     $pepfarTotal += $value;
                     if ($pepfarCount > 1 && !$value && $pepfarEnabled) {
                         $status->addError('training_pepfar_categories_option', t('Number of days is required.'));
                     }
                     if ($pepfarCount == $key + 1) {
                         break;
                     }
                 }
                 // calculate days
                 switch ($this->getSanParam('training_length_interval')) {
                     case 'week':
                         $days = $this->getSanParam('training_length_value') * 7;
                         break;
                     case 'day':
                         $days = $this->getSanParam('training_length_value');
                         // start day counts as a day?
                         break;
                     default:
                         $days = 0.5;
                         break;
                 }
                 // do days add up to match training length?
                 if ($days != $pepfarTotal && $pepfarCount > 1 && $pepfarEnabled) {
                     $status->addError('training_pepfar_categories_option', sprintf(t("Total") . ' ' . t('Training') . ' ' . t("length is %s, but PEPFAR category total is %d days. "), $days == 1 ? $days . ' ' . t('day') : $days . ' ' . t('days'), $pepfarTotal));
                 }
             }
             // custom fields
             if ($this->getSanParam('custom1_phrase')) {
                 $tableCustom = new ITechTable(array('name' => 'training_custom_1_option'));
                 $row->training_custom_1_option_id = $tableCustom->insertUnique('custom1_phrase', $this->getSanParam('custom1_phrase'), true);
             }
             if ($this->getSanParam('custom2_phrase')) {
                 $tableCustom = new ITechTable(array('name' => 'training_custom_2_option'));
                 $row->training_custom_2_option_id = $tableCustom->insertUnique('custom2_phrase', $this->getSanParam('custom2_phrase'), true);
             }
             $custom3 = $this->getSanParam('custom3_phrase');
             $row->custom_3 = $custom3 ? $custom3 : '';
             $custom4 = $this->getSanParam('custom4_phrase');
             $row->custom_4 = $custom4 ? $custom4 : '';
             // checkbox
             if (!$this->getSanParam('is_tot')) {
                 $row->is_tot = 0;
             }
             if (!$this->getSanParam('is_refresher')) {
                 $row->is_refresher = 0;
             }
             $training_refresher_option_id = $this->getSanParam('training_refresher_option_id');
             if (!empty($training_refresher_option_id)) {
                 $row->is_refresher = 1;
             }
         }
         if ($this->_getParam('action') == 'add' && $this->_countrySettings['module_unknown_participants_enabled'] && !$this->getSanParam('has_known_participants')) {
             $row->has_known_participants = 0;
         } else {
             if ($this->_getParam('action') == 'add') {
                 $row->has_known_participants = 1;
             }
         }
         //approve by default if the approvals modules is not enabled
         if ($this->_getParam('action') == 'add' && $this->_countrySettings['module_approvals_enabled'] && !$this->hasACL('approve_trainings')) {
             $row->is_approved = 0;
         } else {
             if ($this->_getParam('action') == 'add') {
                 $row->is_approved = 1;
             }
         }
         // delete training
         if ($this->getSanParam('specialAction') == 'delete') {
             $partys = PersonToTraining::getParticipants($training_id)->toArray();
             $tranys = TrainingToTrainer::getTrainers($training_id)->toArray();
             if (!$partys && !$tranys) {
                 $row->is_deleted = 1;
                 $trainingObj->delete('id = ' . $row->id);
             } else {
                 $status->setStatusMessage(t('This') . ' ' . t('Training') . ' ' . t('session could not be deleted. Some participants or trainers may still be attached.'));
             }
         }
         if ($status->hasError() && !$row->is_deleted) {
             $status->setStatusMessage(t('This') . ' ' . t('Training') . ' ' . t('session could not be saved.'));
         } else {
             $row = self::fillFromArray($row, $this->_getAllParams());
             // format: categoryid_titleid
             $ct_ids = $this->getSanParam('training_category_and_title_option_id');
             // remove category id and underscore (unless dynamic title insert, which is numeric)
             $training_title_option_id = !is_numeric($ct_ids) ? substr($ct_ids, strpos($ct_ids, '_') + 1) : $ct_ids;
             $row->training_title_option_id = $training_title_option_id;
             $row->training_start_date = @$this->getSanParam('start-year') . '-' . @$this->getSanParam('start-month') . '-' . @$this->getSanParam('start-day');
             if ($this->setting('display_end_date')) {
                 $row->training_end_date = @$this->getSanParam('end-year') . '-' . @$this->getSanParam('end-month') . '-' . @$this->getSanParam('end-day');
             }
             // cannot be null ... set defaults
             if (!$row->comments) {
                 $row->comments = '';
             }
             if (!$row->got_comments) {
                 $row->got_comments = '';
             }
             if (!$row->objectives) {
                 $row->objectives = '';
             }
             if (!$row->is_tot) {
                 $row->is_tot = 0;
             }
             if (!$row->is_refresher) {
                 $row->is_refresher = 0;
             }
             // update related tables
             if ($training_id) {
                 // funding
                 $amount_extra_col = '';
                 $amount_extra_vals = array();
                 $amount_extra_col = 'funding_amount';
                 if ($this->getSanParam('funding_id')) {
                     foreach ($this->getSanParam('funding_id') as $funding_id) {
                         $amount_extra_vals[] = $this->getSanParam('funding_id_amount_' . $funding_id);
                     }
                 }
                 MultiOptionList::updateOptions('training_to_training_funding_option', 'training_funding_option', 'training_id', $training_id, 'training_funding_option_id', $this->getSanParam('funding_id'), $amount_extra_col, $amount_extra_vals);
                 // pepfar
                 if ($pepfarEnabled) {
                     MultiOptionList::updateOptions('training_to_training_pepfar_categories_option', 'training_pepfar_categories_option', 'training_id', $training_id, 'training_pepfar_categories_option_id', $this->getSanParam('training_pepfar_categories_option_id'), 'duration_days', isset($daysRay) ? $daysRay : false);
                 }
                 // method
                 if ($this->setting('display_training_method')) {
                     $row->training_method_option_id = $this->getSanParam('training_method_option_id');
                 }
                 // topics
                 if (!$this->setting('allow_multi_topic')) {
                     // drop-down -- set up faux checkbox array (since table schema uses multiple choices)
                     $_GET['topic_id'][] = $this->getSanParam('training_topic_option_id');
                 }
                 MultiOptionList::updateOptions('training_to_training_topic_option', 'training_topic_option', 'training_id', $training_id, 'training_topic_option_id', $this->getSanParam('topic_id'));
                 // refresher course (if dropdownlist)
                 if ($this->setting('multi_opt_refresher_course')) {
                     MultiOptionList::updateOptions('training_to_training_refresher_option', 'training_refresher_option', 'training_id', $training_id, 'training_refresher_option_id', $this->getSanParam('training_refresher_option_id'));
                 }
                 //Qualifications for unknown participants
                 if (!$row->has_known_participants) {
                     //check for duplicates
                     ///oooh, compound key = qual + age
                     //DELETE EVERYTHING FOR THIS TRAINING
                     //START OVER
                     $quals = $this->getSanParam('person_qualification_option_id');
                     $quantities_na = $this->getSanParam('qualification_quantity_na');
                     $quantities_male = $this->getSanParam('qualification_quantity_male');
                     $quantities_female = $this->getSanParam('qualification_quantity_female');
                     $age_ranges = $this->getSanParam('age_range_option_id');
                     $qualPlusAgeArray = array();
                     //make array of qualifications + age range
                     $qualRows = OptionList::suggestionListHierarchical('person_qualification_option', 'qualification_phrase', false, false);
                     foreach ($qualRows as $qRow) {
                         foreach (array_keys($age_opts) as $age_opt) {
                             $qualPlusAgeArray[$qRow['id']][$age_opt] = array('na' => 0, 'male' => 0, 'female' => 0);
                         }
                     }
                     foreach ($quals as $ix => $item) {
                         if ($item) {
                             $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['na'] = $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['na'] + $quantities_na[$ix];
                             $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['male'] = $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['male'] + $quantities_male[$ix];
                             $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['female'] = $qualPlusAgeArray[$quals[$ix]][$age_ranges[$ix]]['female'] + $quantities_female[$ix];
                         }
                     }
                     $deleteTable = new ITechTable(array('name' => 'training_to_person_qualification_option'));
                     $deleteTable->delete('training_id = ' . $training_id, true);
                     foreach ($qualPlusAgeArray as $qkey => $ageRay) {
                         foreach ($ageRay as $akey => $counts) {
                             if ($counts['na'] || $counts['male'] || $counts['female']) {
                                 MultiOptionList::insertOption('training_to_person_qualification_option', 'training_id', $training_id, 'person_qualification_option_id', $qkey, array('age_range_option_id', 'person_count_na', 'person_count_male', 'person_count_female'), array('age_range_option_id' => $akey, 'person_count_na' => $counts['na'], 'person_count_male' => $counts['male'], 'person_count_female' => $counts['female']));
                             }
                         }
                     }
                 }
             }
             //mark approval status
             $do_save_approval_history = false;
             if ($this->setting('module_approvals_enabled')) {
                 if ($this->getSanParam('approval_status') == 'approved') {
                     $row->is_approved = 1;
                     if ($this->setting('allow_multi_approvers') && !$this->hasACL('master_approver')) {
                         $row->is_approved = 2;
                         // approved, but not approved by master approver, only that user can make this a 1 and have it display aproved!
                     }
                     $rowRay['is_approved'] = 1;
                     $do_save_approval_history = true;
                 } else {
                     if ($this->getSanParam('approval_status') == 'rejected') {
                         $row->is_approved = 0;
                         $rowRay['is_approved'] = 0;
                         if ($this->setting('allow_multi_approvers') && !$this->hasACL('master_approver')) {
                             $row->is_approved = 1;
                             // approved, but not approved by master approver, only that user can make this a 1 and have it display aproved!
                             $rowRay['is_approved'] = 1;
                         }
                         $do_save_approval_history = true;
                     }
                 }
                 if ($this->_getParam('action') == 'add' or !$this->hasACL('approve_trainings')) {
                     $do_save_approval_history = true;
                 }
             }
             if ($this->_getParam('action') == 'add') {
                 $do_save_approval_history = true;
             }
             $row->training_refresher_option_id = 0;
             // refresher / bugfix - this col isnt used anymore
             if ($row->save()) {
                 //save approval history
                 if ($this->getSanParam('approval_comments') || $do_save_approval_history) {
                     require_once 'models/table/TrainingApprovalHistory.php';
                     $history_table = new TrainingApprovalHistory();
                     $approval_status = $this->_countrySettings['module_approvals_enabled'] ? $this->getSanParam('approval_status') : 'approved';
                     if (!$this->hasACL('approve_trainings')) {
                         $approval_status = 'resubmitted';
                     }
                     $history_data = array('training_id' => $row->id, 'approval_status' => $approval_status, 'message' => $this->getSanParam('approval_comments'));
                     $history_table->insert($history_data);
                 }
                 // redirects
                 if ($this->_getParam('action') == 'add') {
                     $status->redirect = Settings::$COUNTRY_BASE_URL . '/training/edit/id/' . $row->id . '/new/1';
                 }
                 if ($this->_getParam('redirectUrl')) {
                     $status->redirect = $this->_getParam('redirectUrl');
                 }
                 // duplicate training
                 if ($this->getSanParam('specialAction') == 'duplicate') {
                     if ($this->hasACL('duplicate_training')) {
                         $dupId = $trainingObj->duplicateTraining($row->id);
                         $status->redirect = Settings::$COUNTRY_BASE_URL . '/training/edit/id/' . $dupId . '/msg/duplicate';
                     }
                 }
                 if (!$status->redirect) {
                     $status->setStatusMessage(t('This') . ' ' . t('Training') . ' ' . t('session has been saved.'));
                 }
             } else {
                 error_log("Couldn't save training {$training_id}");
             }
         }
         if ($validateOnly) {
             $this->sendData($status);
         } else {
             $this->view->assign('status', $status);
         }
     }
     //
     // Init view
     //
     $this->view->assign('custom3_phrase', $row->custom_3);
     $this->view->assign('custom4_phrase', $row->custom_4);
     //split start date fields
     if (!$row->training_start_date) {
         $row->training_start_date = '--';
     }
     // empty
     $parts = explode(' ', $row->training_start_date);
     $parts = explode('-', $parts[0]);
     $rowRay['start-year'] = $parts[0];
     $rowRay['start-month'] = $parts[1];
     $rowRay['start-day'] = $parts[2];
     //split end date fields
     if (!$row->training_end_date) {
         $row->training_end_date = '--';
     }
     // empty
     $parts = explode(' ', $row->training_end_date);
     $parts = explode('-', $parts[0]);
     $rowRay['end-year'] = $parts[0];
     $rowRay['end-month'] = $parts[1];
     $rowRay['end-day'] = $parts[2];
     // Drop downs
     //$this->view->assign('dropDownTitle', DropDown::generateHtml('training_title_option','training_title_phrase',$rowRay['training_title_option_id'],($this->hasACL('training_title_option_all')?'training/insert-table':false), $this->view->viewonly,false));
     $this->view->assign('dropDownOrg', DropDown::generateHtml('training_organizer_option', 'training_organizer_phrase', $rowRay['training_organizer_option_id'], $this->hasACL('training_organizer_option_all') ? 'training/insert-table' : false, $this->view->viewonly, $this->view->viewonly ? false : $allowIds));
     $this->view->assign('dropDownLevel', DropDown::generateHtml('training_level_option', 'training_level_phrase', $rowRay['training_level_option_id'], 'training/insert-table', $this->view->viewonly));
     $this->view->assign('dropDownGotCir', DropDown::generateHtml('training_got_curriculum_option', 'training_got_curriculum_phrase', $rowRay['training_got_curriculum_option_id'], 'training/insert-table', $this->view->viewonly));
     $this->view->assign('dropDownMethod', DropDown::generateHtml('training_method_option', 'training_method_phrase', $rowRay['training_method_option_id'], 'training/insert-table', $this->view->viewonly));
     $this->view->assign('dropDownPrimaryLanguage', DropDown::generateHtml('trainer_language_option', 'language_phrase', $rowRay['training_primary_language_option_id'], false, $this->view->viewonly, false, false, array('name' => 'training_primary_language_option_id')));
     $this->view->assign('dropDownSecondaryLanguage', DropDown::generateHtml('trainer_language_option', 'language_phrase', $rowRay['training_secondary_language_option_id'], false, $this->view->viewonly, false, false, array('name' => 'training_secondary_language_option_id')));
     //$catTitleArray = OptionList::suggestionList('location_district',array('district_name','parent_province_id'),false,false);
     $this->view->assign('age_options', $age_opts);
     // training categories & titles
     $categoryTitle = MultiAssignList::getOptions('training_title_option', 'training_title_phrase', 'training_category_option_to_training_title_option', 'training_category_option');
     $this->view->assign('categoryTitle', $categoryTitle);
     // add title link
     if ($this->hasACL('training_title_option_all')) {
         $this->view->assign('titleInsertLink', " <a href=\"#\" onclick=\"addToSelect('" . str_replace("'", "\\" . "'", t('Please enter your new')) . " " . strtolower($this->view->translation['Training'] . t('Name')) . ":', 'select_training_title_option', '" . Settings::$COUNTRY_BASE_URL . "/training/insert-table/table/training_title_option/column/training_title_phrase/outputType/json'); return false;\">" . t('Insert new') . "</a>");
     }
     //get assigned evaluation
     $ev_id = null;
     $ev_to_t_id = null;
     if ($training_id) {
         $evtableObj = new ITechTable(array('name' => 'evaluation_to_training'));
         $evRow = $evtableObj->fetchRow($evtableObj->select(array('id', 'evaluation_id'))->where('training_id = ' . $training_id));
         if ($evRow) {
             $ev_id = $evRow->evaluation_id;
             $ev_to_t_id = $evRow->id;
         }
         $this->view->assign('evaluation_id', $ev_id);
         $this->view->assign('evaluation_to_training_id', $ev_to_t_id);
     }
     //Qualifications for unknown participants
     if (!$row->has_known_participants) {
         //count primary qualifications.
         //add a dropdown for each
         $tableObj = new ITechTable(array('name' => 'person_qualification_option'));
         $qualRows = OptionList::suggestionListHierarchical('person_qualification_option', 'qualification_phrase', false, false);
         //get values for this training
         $selectedObj = new ITechTable(array('name' => 'training_to_person_qualification_option'));
         $selectedRows = null;
         if ($training_id) {
             $selectedRows = $selectedObj->fetchAll($selectedObj->select(array('person_qualification_option_id', 'id', 'person_count_na', 'person_count_male', 'person_count_female', 'age_range_option_id'))->where('training_id = ' . $training_id));
             $unknownQualDropDowns = array();
             $qual_row_count = 0;
             foreach ($selectedRows as $selectedRow) {
                 $selector = array();
                 $selector['select'] = $this->_generate_hierarchical('select_person_qualification_option_' . $qual_row_count, $qualRows, 'qualification_phrase', $selectedRow->person_qualification_option_id);
                 $selector['age_range_option_id'] = $selectedRow->age_range_option_id;
                 $selector['quantity_na'] = $selectedRow->person_count_na;
                 $selector['quantity_male'] = $selectedRow->person_count_male;
                 $selector['quantity_female'] = $selectedRow->person_count_female;
                 $unknownQualDropDowns[] = $selector;
                 $qual_row_count++;
             }
             $max_rows = count($qualRows) * 3;
             //should be about 30
             for ($i = $selectedRows->count(); $i < $max_rows; $i++) {
                 $selector = array();
                 $selector['select'] = $this->_generate_hierarchical('select_person_qualification_option_' . $qual_row_count, $qualRows, 'qualification_phrase', -1);
                 $selector['age_range_option_id'] = 1;
                 $selector['quantity_na'] = 0;
                 $selector['quantity_male'] = 0;
                 $selector['quantity_female'] = 0;
                 $unknownQualDropDowns[] = $selector;
                 $qual_row_count++;
             }
             $this->view->assign('unknownQualDropDowns', $unknownQualDropDowns);
         }
     }
     // find category based on title
     $catId = 0;
     if ($courseRow && $courseRow->training_title_option_id) {
         foreach ($categoryTitle as $r) {
             if ($r['id'] == $courseRow->training_title_option_id && $r['training_category_option_id'] != 0) {
                 $catId = $r['training_category_option_id'];
                 break;
             }
         }
     }
     $this->view->assign('dropDownCategory', DropDown::generateHtml('training_category_option', 'training_category_phrase', $catId, false, $this->view->viewonly, false));
     //echo '<pre>';
     //print_r($catTitleArray); exit;
     //      $this->view->assign('dropDownProvince', DropDown::generateHtml('location_province','province_name',false,false,$this->view->viewonly));
     //      $this->view->assign('dropDownDistrict', DropDown::generateHtml('location_district','district_name',false,false,$this->view->viewonly));
     $this->viewAssignEscaped('locations', Location::getAll());
     // Topic drop-down
     if ($training_id) {
         if (!$this->setting('allow_multi_topic')) {
             $training_topic_id = $trainingObj->getTrainingSingleTopic($training_id);
             if ($is_new) {
                 $training_topic_id = false;
             }
             // use default
             $this->view->assign('dropDownTopic', DropDown::generateHtml('training_topic_option', 'training_topic_phrase', $training_topic_id, 'training/insert-table', $this->view->viewonly));
         } else {
             // topic checkboxes
             $topicArray = MultiOptionList::choicesList('training_to_training_topic_option', 'training_id', $training_id, 'training_topic_option', 'training_topic_phrase');
             $this->view->assign('topicArray', $topicArray);
             $this->view->assign('topicJsonUrl', Settings::$COUNTRY_BASE_URL . '/training/insert-table/table/training_topic_option/column/training_topic_phrase/outputType/json');
         }
     }
     if ($this->hasACL('acl_editor_training_topic')) {
         $this->view->assign("topicInsertLink", ' <a href="#" onclick="addCheckbox(\'' . t('Please enter the name your new topic item') . '\', \'topic_id\', \'topicContainer\', \'' . $this->view->topicJsonUrl . '\'); return false;">' . t('Insert New') . '</a>');
     }
     // get custom phrases (custom1_phrase, custom2_phrase)
     if ($training_id) {
         $rowRay = array_merge($rowRay, $trainingObj->getCustom($training_id)->toArray());
     }
     // location drop-down
     $tlocations = TrainingLocation::selectAllLocations($this->setting('num_location_tiers'));
     $this->viewAssignEscaped('tlocations', $tlocations);
     if ($this->hasACL('edit_facility')) {
         $this->view->assign("insertLocationLink", '<a href="#" onclick="return false;" id="show">' . t(str_replace(' ', '&nbsp;', t('Insert new'))) . '</a>');
     }
     // pepfar durations
     $pepfarEnabled = @$this->setting('display_training_pepfar');
     if ($training_id && $pepfarEnabled) {
         $pepfarArray = MultiOptionList::choicesList('training_to_training_pepfar_categories_option', 'training_id', $training_id, 'training_pepfar_categories_option', 'pepfar_category_phrase', 'duration_days');
         foreach ($pepfarArray as $item) {
             if (isset($item['training_id']) && $item['training_id']) {
                 $pepfars[] = array('id' => $item['id'], 'duration' => $item['duration_days']);
             }
         }
     }
     // pepfar
     $this->view->assign('NUM_PEPFAR', $this->NUM_PEPFAR);
     // number of Pepfar drop-downs to display
     for ($j = 0; $j < $this->NUM_PEPFAR; $j++) {
         $pepfarid = isset($pepfars[$j]['id']) ? $pepfars[$j]['id'] : '';
         if ($is_new) {
             $pepfarid = false;
         }
         // use default
         $pepfarHtml = DropDown::generateHtml('training_pepfar_categories_option', 'pepfar_category_phrase', $pepfarid, false, $this->view->viewonly, false, false, array(), $j == 0);
         $pepfarHtml = str_replace('training_pepfar_categories_option_id', 'training_pepfar_categories_option_id[]', $pepfarHtml);
         // use array
         $dropDownPepfars[] = $pepfarHtml;
         //$pepfarDurations[] = (isset($pepfars[$j]['duration']) && $pepfars[$j]['duration'] ? $pepfars[$j]['duration'] . ' day' . (($pepfars[$j]['duration'] <= 1) ? '' : 's') : '');
         $pepfarDurations[] = isset($pepfars[$j]['duration']) && $pepfars[$j]['duration'] ? $pepfars[$j]['duration'] : '';
     }
     $this->view->assign('dropDownPepfars', $dropDownPepfars);
     $this->view->assign('pepfarDurations', $pepfarDurations);
     // checkboxes
     $fundingArray = MultiOptionList::choicesList('training_to_training_funding_option', 'training_id', $training_id, 'training_funding_option', array('funding_phrase', 'is_default'));
     if ($training_id) {
         //lame to do another query, but it's easy
         $tableObj = new ITechTable(array('name' => 'training_to_training_funding_option'));
         $amountRows = $tableObj->fetchAll($tableObj->select(array('training_funding_option_id', 'id', 'funding_amount'))->where('training_id = ' . $training_id));
         foreach ($amountRows as $amt_row) {
             foreach ($fundingArray as $k => $funding_row) {
                 if ($funding_row['id'] == $amt_row->training_funding_option_id) {
                     $fundingArray[$k]['funding_amount'] = $amt_row->funding_amount;
                 }
             }
         }
     }
     $this->view->assign('fundingArray', $fundingArray);
     if ($this->hasACL('acl_editor_funding')) {
         $this->view->assign('fundingJsonUrl', Settings::$COUNTRY_BASE_URL . '/training/insert-table/table/training_funding_option/column/funding_phrase/outputType/json');
         $this->view->assign("fundingInsertLink", ' <a href="#" onclick="addCheckbox(\'' . t('Please enter the name your new funding item:') . '\', \'funding_id\', \'fundingContainer\', \'' . $this->view->fundingJsonUrl . '\'); return false;">' . t('Insert New') . '</a>');
     }
     // refresher (if multi)
     if ($training_id) {
         if ($this->setting('multi_opt_refresher_course')) {
             $training_refresher_id = $row->training_refresher_option_id;
             if ($is_new) {
                 $training_refresher_id = false;
             }
             // use default
             #$this->view->assign ( 'dropDownRefresher', DropDown::generateHtml ( 'training_refresher_option', 'refresher_phrase_option', $training_refresher_id, 'training/insert-table', $this->view->viewonly ) );
             $this->view->assign('refresherArray', MultiOptionList::choicesList('training_to_training_refresher_option', 'training_id', $training_id, 'training_refresher_option', 'refresher_phrase_option', false, false));
             if ($this->hasACL('acl_editor_refresher_course')) {
                 $this->view->assign('refresherJsonUrl', Settings::$COUNTRY_BASE_URL . '/training/insert-table/table/training_refresher_option/column/refresher_phrase_option/outputType/json');
                 $this->view->assign("refresherInsertLink", ' <a href="#" onclick="addCheckbox(\'' . t('Please enter the name your new refresher item') . '\', \'training_refresher_option_id\', \'refresherContainer\', \'' . $this->view->refresherJsonUrl . '\'); return false;">' . t('Insert New') . '</a>');
             }
         }
     }
     /****************************************************************************************************************
      * Trainers */
     if ($training_id) {
         $trainers = TrainingToTrainer::getTrainers($training_id)->toArray();
     } else {
         $trainers = array();
     }
     if (!$this->setting('display_middle_name')) {
         $trainerFields = array('first_name' => $this->tr('First Name'), 'last_name' => $this->tr('Last Name'));
         $colStatic = array('first_name', 'last_name');
     } else {
         if ($this->setting('display_middle_name_last')) {
             $trainerFields = array('first_name' => $this->tr('First Name'), 'last_name' => $this->tr('Last Name'), 'middle_name' => $this->tr('Middle Name'));
             $colStatic = array('first_name', 'last_name', 'middle_name');
         } else {
             $trainerFields = array('first_name' => $this->tr('First Name'), 'middle_name' => $this->tr('Middle Name'), 'last_name' => $this->tr('Last Name'));
             $colStatic = array('first_name', 'middle_name', 'last_name');
         }
     }
     if ($this->view->viewonly) {
         $editLinkInfo['disabled'] = 1;
         $linkInfo = array();
         $colStatic = array_keys($trainerFields);
     } else {
         $linkInfo = array('linkFields' => $colStatic, 'linkId' => 'trainer_id', 'linkUrl' => Settings::$COUNTRY_BASE_URL . '/person/edit/id/%trainer_id%');
         $linkInfo['linkUrl'] = "javascript:submitThenRedirect('{$linkInfo['linkUrl']}/trainingredirect/{$training_id}');";
         $editLinkInfo = array();
     }
     $html = EditTableHelper::generateHtmlTraining('Trainer', $trainers, $trainerFields, $colStatic, $linkInfo, $editLinkInfo);
     $this->view->assign('tableTrainers', $html);
     /****************************************************************************************************************
      * Participants */
     $locations = Location::getAll();
     $customColDefs = array();
     if ($training_id) {
         $persons = PersonToTraining::getParticipants($training_id)->toArray();
         foreach ($persons as $pid => $p) {
             $region_ids = Location::getCityInfo($p['location_id'], $this->setting('num_location_tiers'));
             // todo expensive call, getcityinfo loads all locations each time??
             $persons[$pid]['province_name'] = $region_ids[1] ? $locations[$region_ids['1']]['name'] : 'unknown';
             if ($region_ids[2]) {
                 $persons[$pid]['district_name'] = $locations[$region_ids[2]]['name'];
             } else {
                 $persons[$pid]['district_name'] = 'unknown';
             }
             if ($region_ids[3]) {
                 $persons[$pid]['region_c_name'] = $locations[$region_ids[3]]['name'];
             } else {
                 $persons[$pid]['region_c_name'] = 'unknown';
             }
             if ($region_ids[4]) {
                 $persons[$pid]['region_d_name'] = $locations[$region_ids[4]]['name'];
             } else {
                 $persons[$pid]['region_d_name'] = 'unknown';
             }
             if ($region_ids[5]) {
                 $persons[$pid]['region_e_name'] = $locations[$region_ids[5]]['name'];
             } else {
                 $persons[$pid]['region_e_name'] = 'unknown';
             }
             if ($region_ids[6]) {
                 $persons[$pid]['region_f_name'] = $locations[$region_ids[6]]['name'];
             } else {
                 $persons[$pid]['region_f_name'] = 'unknown';
             }
             if ($region_ids[7]) {
                 $persons[$pid]['region_g_name'] = $locations[$region_ids[7]]['name'];
             } else {
                 $persons[$pid]['region_g_name'] = 'unknown';
             }
             if ($region_ids[8]) {
                 $persons[$pid]['region_h_name'] = $locations[$region_ids[8]]['name'];
             } else {
                 $persons[$pid]['region_h_name'] = 'unknown';
             }
             if ($region_ids[9]) {
                 $persons[$pid]['region_i_name'] = $locations[$region_ids[9]]['name'];
             } else {
                 $persons[$pid]['region_i_name'] = 'unknown';
             }
         }
     } else {
         $persons = array();
     }
     if (!$this->setting('display_middle_name')) {
         $personsFields = array('first_name' => $this->tr('First Name'), 'last_name' => $this->tr('Last Name'), 'birthdate' => t('Date of Birth'), 'facility_name' => t('Facility'));
     } else {
         if ($this->setting('display_middle_name_last')) {
             $personsFields = array('first_name' => $this->tr('First Name'), 'last_name' => $this->tr('Last Name'), 'middle_name' => "..." . $this->tr('Middle Name'), 'birthdate' => t('Date of Birth'), 'facility_name' => t('Facility'));
         } else {
             $personsFields = array('first_name' => $this->tr('First Name'), 'middle_name' => "..." . $this->tr('Middle Name'), 'last_name' => $this->tr('Last Name'), 'birthdate' => t('Date of Birth'), 'facility_name' => t('Facility'));
         }
     }
     if ($this->setting('module_attendance_enabled')) {
         $personsFields['duration_days'] = $this->tr('Days Attended');
         $personsFields['award_phrase'] = $this->tr('Complete');
         $rowArray = OptionList::suggestionList('person_to_training_award_option', array('id', 'award_phrase'), false, 9999, false, false);
         $elements = array(0 => array('text' => ' ', 'value' => 0));
         foreach ($rowArray as $i => $tablerow) {
             $elements[$i + 1]['text'] = $tablerow['award_phrase'];
             $elements[$i + 1]['value'] = $tablerow['id'];
         }
         $elements = json_encode($elements);
         // yui data table will enjoy spending time with a json encoded array
         $customColDefs['award_phrase'] = "editor:'dropdown', editorOptions: {dropdownOptions: {$elements} }";
     }
     if ($this->setting('display_viewing_location')) {
         $personsFields['location_phrase'] = $this->tr('Viewing Location');
         $vLocDropDown = OptionList::suggestionList('person_to_training_viewing_loc_option', array('id', 'location_phrase'), false, 9999, false, false);
         $elements = array(0 => array('text' => '', 'value' => 0));
         foreach ($vLocDropDown as $i => $tablerow) {
             $elements[$i + 1]['text'] = $tablerow['location_phrase'];
             $elements[$i + 1]['value'] = $tablerow['id'];
         }
         $elements = json_encode($elements);
         $customColDefs['location_phrase'] = "editor:'dropdown', editorOptions: {dropdownOptions: {$elements} }";
     }
     if ($this->setting('display_budget_code')) {
         $personsFields['budget_code_phrase'] = $this->tr('Budget Code');
         $budgetDropDown = OptionList::suggestionList('person_to_training_budget_option', array('id', 'budget_code_phrase'), false, 9999, false, false);
         $elements = array(0 => array('text' => '', 'value' => 0));
         foreach ($budgetDropDown as $i => $tablerow) {
             $elements[$i + 1]['text'] = $tablerow['budget_code_phrase'];
             $elements[$i + 1]['value'] = $tablerow['id'];
         }
         $elements = json_encode($elements);
         $customColDefs['budget_code_phrase'] = "editor: 'dropdown' , editorOptions:{dropdownOptions: {$elements}} ";
     }
     if ($this->setting('display_region_i')) {
         $personsFields['region_i_name'] = $this->tr('Region I');
     } else {
         if ($this->setting('display_region_h')) {
             $personsFields['region_h_name'] = $this->tr('Region H');
         } else {
             if ($this->setting('display_region_g')) {
                 $personsFields['region_g_name'] = $this->tr('Region G');
             } else {
                 if ($this->setting('display_region_f')) {
                     $personsFields['region_f_name'] = $this->tr('Region F');
                 } else {
                     if ($this->setting('display_region_e')) {
                         $personsFields['region_e_name'] = $this->tr('Region E');
                     } else {
                         if ($this->setting('display_region_d')) {
                             $personsFields['region_d_name'] = $this->tr('Region D');
                         } else {
                             if ($this->setting('display_region_c')) {
                                 $personsFields['region_c_name'] = $this->tr('Region C (Local Region)');
                             } else {
                                 if ($this->setting('display_region_b')) {
                                     $personsFields['district_name'] = $this->tr('Region B (Health District)');
                                 } else {
                                     $personsFields['province_name'] = $this->tr('Region A (Province)');
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     $colStatic = array_keys($personsFields);
     // static calumns (From field keys)
     if ($this->setting('module_attendance_enabled') || $this->setting('display_viewing_location') || $this->setting('display_budget_code')) {
         foreach ($colStatic as $i => $v) {
             if ($v == 'duration_days' || $v == 'award_phrase' || $v == 'budget_code_phrase' || $v == 'location_phrase') {
                 unset($colStatic[$i]);
             }
         }
         // remove 1 so we can edit the field
     }
     if ($this->view->viewonly) {
         $editLinkInfo['disabled'] = 1;
         $linkInfo = array();
     } else {
         $linkInfo = array('linkFields' => $colStatic, 'linkId' => 'person_id', 'linkUrl' => Settings::$COUNTRY_BASE_URL . '/person/edit/id/%person_id%');
         $linkInfo['linkUrl'] = "javascript:submitThenRedirect('{$linkInfo['linkUrl']}/trainingredirect/{$training_id}');";
         $editLinkInfo = array();
         // add link next to "Remove"
         if ($this->setting('display_training_pre_test')) {
             $editLinkInfo[] = array('linkName' => t('Pre-Test'), 'linkId' => 'id', 'linkUrl' => "javascript:updateScore('Pre-Test', %id%, '" . Settings::$COUNTRY_BASE_URL . "/training/scores-update', '%score_pre%');");
             // do not translate label/key
         }
         if ($this->setting('display_training_post_test')) {
             $editLinkInfo[] = array('linkName' => t('Post-Test'), 'linkId' => 'id', 'linkUrl' => "javascript:updateScore('Post-Test', %id%, '" . Settings::$COUNTRY_BASE_URL . "/training/scores-update', '%score_post%');");
             // do not translate label/key
         }
         $editLinkInfo[] = array('linkName' => t('Scores'), 'linkId' => 'id', 'linkUrl' => "javascript:submitThenRedirect('" . Settings::$COUNTRY_BASE_URL . "/training/scores/ptt_id/%id%');");
         // old
         //'linkUrl' => Settings::$COUNTRY_BASE_URL."/training/scores/training/$training_id/person/%person_id%",
         //$editLinkInfo['linkUrl'] = "javascript:submitThenRedirect('{$editLinkInfo['linkUrl']}');";
     }
     $html = EditTableHelper::generateHtmlTraining('Persons', $persons, $personsFields, $colStatic, $linkInfo, $editLinkInfo, $customColDefs);
     $this->view->assign('tablePersons', $html);
     /****************************************************************************************************************/
     /* Attached Files */
     FileUpload::displayFiles($this, 'training', $row->id, !$this->view->viewonly);
     //$this->view->assign('files', 'x' . FileUpload::displayFiles($this, 'training', $row->id));
     // File upload form
     if (!$this->view->viewonly) {
         $this->view->assign('filesForm', FileUpload::displayUploadForm('training', $row->id, FileUpload::$FILETYPES));
     }
     /****************************************************************************************************************/
     /* Approval status */
     if ($this->setting('module_approvals_enabled')) {
         $canApprove = $this->hasACL('master_approver') && $row->is_approved == 2 || $this->hasACL('approve_trainings') && !$row->is_approved;
         $this->view->assign('can_approve', $canApprove);
         if ($canApprove) {
             $this->view->assign('approve_val', '');
         } else {
             $this->view->assign('approve_val', $row->is_approved);
         }
         // disable control
         if (!$canApprove or !$this->hasACL('approve_trainings')) {
             $this->view->assign('approve_disable_str', 'disabled');
         } else {
             $this->view->assign('approve_disable_str', '');
         }
     }
     /****************************************************************************************************************/
     /* Attached Files */
     // mode
     $this->view->assign('mode', $this->_getParam('action'));
     switch ($this->_getParam('msg')) {
         case 'duplicate':
             $this->view->assign('msg', t('Training') . ' ' . t('session has been duplicated.<br>You can edit the duplicate session below.'));
             break;
         default:
             break;
     }
     // edit variables
     if ($this->_getParam('action') != 'add') {
         //audit history
         $creatorObj = new User();
         $updaterObj = new User();
         $creatorrow = $creatorObj->findOrCreate($row->created_by);
         $rowRay['creator'] = $creatorrow->first_name . ' ' . $creatorrow->last_name;
         $updaterrow = $updaterObj->findOrCreate($row->modified_by);
         $rowRay['updater'] = $updaterrow->first_name . ' ' . $updaterrow->last_name;
     }
     if (empty($trainers) || empty($persons)) {
         $this->view->assign('isIncomplete', true);
     }
     // default start date?
     if ($this->getSanParam('start-date')) {
         $parts = explode('/', $this->getSanParam('start-date'));
         if (count($parts) == 3) {
             $rowRay['start-day'] = $parts[0];
             $rowRay['start-month'] = $parts[1];
             $rowRay['start-year'] = $parts[2];
         }
     }
     // row values
     $this->view->assign('row', $rowRay);
 }
 /**
  * Matches as posted set of multiple drop downs or checkboxes with an option list intersection table.
  * May update extra columns within link table
  * 	 *
  * @param unknown_type $linktable
  * @param unknown_type $optionLookupTable
  * @param unknown_type $owner_col
  * @param unknown_type $owner_id
  * @param unknown_type $option_col
  * @param array $valuesFromPost contains the main column values
  * @param array|string $extra_col additional columns to update
  * @param array $extra_values array or array of arrays with values to update ; the indexes must match $valuesFromPost and $extra_col
  */
 public static function updateOptions($linktable, $optionLookupTable, $owner_col, $owner_id, $option_col, $valuesFromPost, $extra_col = '', $extra_values = array())
 {
     if ($valuesFromPost === null) {
         return;
     }
     $optionRowsArray = MultiOptionList::choicesList($linktable, $owner_col, $owner_id, $optionLookupTable, false, $option_col);
     // get extra field value(s) associate drop-down
     if ($extra_col && !is_array($extra_col)) {
         $extra_values = array($extra_values);
         $extra_col = array($extra_col);
     }
     if ($valuesFromPost && is_array($extra_col)) {
         foreach ($extra_col as $colkey => $col) {
             foreach ($valuesFromPost as $key => $id) {
                 if ($id !== '') {
                     $extra[$id][$col] = isset($extra_values[$colkey][$key]) ? $extra_values[$colkey][$key] : 0;
                 }
             }
         }
     }
     foreach ($optionRowsArray as $option_row) {
         $option_id = $option_row['id'];
         //turn off
         if ($option_row[$owner_col] and ($valuesFromPost == null or array_search($option_id, $valuesFromPost) === false and (!isset($valuesFromPost[$option_id]) or !$valuesFromPost[$option_id]))) {
             MultiOptionList::hardDeleteOption($linktable, $owner_col, $owner_id, $option_col, $option_id);
             //turn on
         } else {
             if (!$option_row[$owner_col] and $valuesFromPost and array_search($option_id, $valuesFromPost) !== false) {
                 MultiOptionList::insertOption($linktable, $owner_col, $owner_id, $option_col, $option_id, $extra_col, isset($extra) && is_array($extra[$option_id]) ? $extra[$option_id] : '');
             } else {
                 if ($extra_col) {
                     // update extra field
                     if (isset($extra[$option_id])) {
                         $optionsTable = new MultiOptionList(array('name' => $linktable));
                         $update_fields = array();
                         foreach ($extra_col as $col) {
                             $update_fields[$col] = $extra[$option_id][$col];
                         }
                         $optionsTable->update($update_fields, "{$option_col}={$option_id} AND {$owner_col}={$option_row[$owner_col]}");
                     }
                 }
             }
         }
     }
 }
 public function doAddEditView()
 {
     try {
         //validate
         $status = ValidationContainer::instance();
         require_once 'models/table/OptionList.php';
         require_once 'models/table/MultiOptionList.php';
         require_once 'models/table/Location.php';
         $request = $this->getRequest();
         $validateOnly = $request->isXmlHttpRequest();
         $person_id = $this->getSanParam('id');
         $personObj = new Person();
         $personrow = $personObj->findOrCreate($person_id);
         $personArray = $personrow->toArray();
         $helper = new Helper();
         $ssl = $helper->getSkillSmartLookups();
         $this->view->assign('skillsmart', $ssl);
         // nationality dropdown data
         $this->view->assign('lookupnationalities', $helper->getNationalities());
         $train = $helper->getPersonTraining($person_id);
         $this->view->assign('persontraining', $train);
         //locations
         $locations = Location::getAll();
         $this->viewAssignEscaped('locations', $locations);
         if ($validateOnly) {
             $this->setNoRenderer();
         }
         // Figure out reason code "Other" for checking posted data,
         // and for enabling/disabling reason_other field
         $other_reason_option_id = -1;
         $db = Zend_Db_Table_Abstract::getDefaultAdapter();
         $sql = "SELECT * FROM person_attend_reason_option where LCASE(attend_reason_phrase) LIKE '%other%'";
         $rowArray = $db->fetchAll($sql);
         if ($rowArray) {
             $other_reason_option_id = $rowArray[0]['id'];
         }
         $this->viewAssignEscaped('other_reason_option_id', $other_reason_option_id);
         if ($request->isPost()) {
             $errortext = "";
             if ($dupe_id = $this->getSanParam('dupe_id')) {
                 if ($this->getSanParam('maketrainer')) {
                     // require user to add trainer info
                     $status->setRedirect('/person/edit/id/' . $dupe_id . '/trainingredirect/' . $this->getSanParam('trainingredirect') . '/maketrainer/1');
                 } else {
                     if ($this->_getParam('trainingredirect')) {
                         $status->setStatusMessage(t('The person was saved. Refreshing history...'));
                         $_SESSION['status'] = t('The person was saved.');
                         $this->trainingRedirect($dupe_id);
                     } else {
                         $status->setRedirect('/person/edit/id/' . $dupe_id);
                     }
                 }
                 return;
             }
             $status->checkRequired($this, 'first_name', $this->tr('First Name'));
             $status->checkRequired($this, 'last_name', $this->tr('Last Name'));
             $status->checkRequired($this, 'primary_qualification_option_id', t('Professional qualification'));
             if ($this->setting('display_gender') != '0') {
                 $status->checkRequired($this, 'gender', t('Gender'));
             }
             if ($this->setting('display_mod_skillsmart')) {
                 //$status->checkRequired ( $this, 'occupational_category_id', t ( 'Occupational category' ) );
                 if ($this->getSanParam('govemp_option_id')) {
                     //$status->checkRequired ( $this, 'govemp_option_id', t ( 'Government Employee' ) );
                     //$status->checkRequired ( $this, 'occupational_category_id', t ( 'Occupational category' ) );
                     $status->checkRequired($this, 'persal_number', t('Persal Number'));
                 }
             } else {
                 $status->checkRequired($this, 'primary_qualification_option_id', t('Professional qualification'));
             }
             $birthParam = @$this->getSanParam('birth-year') . '-' . @$this->getSanParam('birth-month') . '-' . @$this->getSanParam('birth-day');
             if ($birthParam !== '--' and $birthParam !== '0000-00-00') {
                 $status->isValidDate($this, 'birth-day', t('Birthdate'), $birthParam);
             }
             //trainer only
             if ($this->getSanParam('is_trainer') || $this->getSanParam('active_trainer_option_id') || $this->getSanParam('trainer_type_option_id')) {
                 $status->checkRequired($this, 'trainer_type_option_id', t('Trainer') . ' ' . t('type'));
                 // 10/02/2011 Sean Smith: Removed at client request.
                 //if ($this->setting ( 'display_trainer_affiliations' )) {
                 //	$status->checkRequired ( $this, 'trainer_affiliation_option_id', t ( 'Trainer').' '.t('affiliation' ) );
                 //}
                 //at least one skill
                 $status->checkRequired($this, 'trainer_skill_id', t('Trainer') . ' ' . t('skill'));
             }
             // Check for manual reason for attending entry (if pulldown reason is 'other')
             if ($this->setting('display_attend_reason')) {
                 //if ($status->checkRequired ( $this, 'attend_reason_option_id', t ( 'Reason For Attending' ))) {
                 $reason_id = $this->getSanParam('attend_reason_option_id');
                 $other_reason = $this->getSanParam('attend_reason_other');
                 if (($reason_id || $reason_id == 0) && $other_reason_option_id >= 0) {
                     if ($reason_id == $other_reason_option_id) {
                         if ($other_reason == "") {
                             $status->addError('attend_reason_other', t('Enter a reason, or select a different reason above.'));
                             $errortext .= "Enter a reason, or select a different reason above.<br>";
                             error_log("Enter a reason, or select a different reason above.");
                         }
                     } else {
                         if ($other_reason != "") {
                             $status->addError('attend_reason_other', t('You can not type in a reason with the reason selected above.'));
                             $errortext .= "You can not type in a reason with the reason selected above.<br>";
                             error_log("You can not type in a reason with the reason selected above.");
                         }
                     }
                 }
                 //}
             }
             //check facility
             if ($status->checkRequired($this, 'facilityInput', t('Facility'))) {
                 $facility_id = $this->getSanParam('facilityInput');
                 if (is_array($facility_id)) {
                     $fac_arr = array();
                     foreach ($facility_id as $fac_id) {
                         if ($strrpos = strrpos($fac_id, '_')) {
                             $fac_arr[] = substr($fac_id, $strrpos + 1);
                         }
                     }
                     $personrow->multi_facility_ids = json_encode($fac_arr);
                     $facility_id = current($facility_id);
                 } else {
                     $personrow->multi_facility_ids = '';
                 }
                 if ($strrpos = strrpos($facility_id, '_')) {
                     $facility_id = array_pop(explode('_', $facility_id));
                 }
                 //find by name
                 if ($facility_id) {
                     $facilityByName = new Facility();
                     $row = $facilityByName->fetchRow('id = ' . $facility_id);
                     //$row = $facilityByName->fetchRow($facilityByName->select()->where('facility_name = ?', $this->getSanParam('facilityInput')));
                 }
                 if (@$row->id) {
                     $personrow->facility_id = $row->id;
                 } else {
                     $status->addError('facilityInput', t('That facility name could not be found.'));
                     $errortext .= "That facility name could not be found.<br>";
                     error_log("That facility name could not be found.");
                 }
             }
             //get home city name
             $city_id = false;
             $criteria = $this->_getAllParams();
             require_once 'views/helpers/Location.php';
             $home_city_parent_id = regionFiltersGetLastID('home', $criteria);
             if ($criteria['home_city'] && !$criteria['is_new_home_city']) {
                 $city_id = Location::verifyHierarchy($criteria['home_city'], $home_city_parent_id, $this->setting('num_location_tiers'));
                 if ($city_id === false) {
                     $status->addError('home_city', t("That city does not appear to be located in the chosen region. If you want to create a new city, check the new city box."));
                     $errortext .= "That city does not appear to be located in the chosen region. If you want to create a new city, check the new city box.<br>";
                     error_log("That city does not appear to be located in the chosen region. If you want to create a new city, check the new city box.");
                 }
             }
             if ($status->hasError()) {
                 foreach ($status->messages as $k => $v) {
                     $errortext .= $v . "<br>";
                 }
                 $status->setStatusMessage(t('The person could not be saved. <br>' . $errortext));
             } else {
                 $personrow = self::fillFromArray($personrow, $this->_getAllParams());
                 if ($city_id === false && $this->getSanParam('is_new_home_city')) {
                     $city_id = Location::insertIfNotFound($criteria['home_city'], $home_city_parent_id, $this->setting('num_location_tiers'));
                     if ($city_id === false) {
                         $status->addError('home_city', t('Could not save that city.'));
                     }
                 }
                 if ($city_id) {
                     $personrow->home_location_id = $city_id;
                 } else {
                     $home_location_id = Location::verifyHierarchy($criteria['home_city'], $home_city_parent_id, $this->setting('num_location_tiers'));
                     if ($home_location_id) {
                         $personrow->home_location_id = $home_location_id;
                     }
                 }
                 //these are transitionary database fields, will go away soon
                 //  $personrow->home_district_id = null;
                 //  $personrow->home_province_id = null;
                 if (!$personrow->home_city) {
                     $personrow->home_city = '';
                 }
                 // bugfix, field cannot be null.
                 if ($this->getSanParam('active')) {
                     $personrow->active = 'active';
                 } else {
                     $personrow->active = 'inactive';
                 }
                 $personrow->birthdate = @$this->getSanParam('birth-year') . '-' . @$this->getSanParam('birth-month') . '-' . @$this->getSanParam('birth-day');
                 //lookup custom 1 and 2
                 if ($this->getSanParam('custom1Input')) {
                     $id = OptionList::insertIfNotFound('person_custom_1_option', 'custom1_phrase', $this->getSanParam('custom1Input'));
                     $personrow->person_custom_1_option_id = $id;
                 } else {
                     $personrow->person_custom_1_option_id = null;
                 }
                 if ($this->getSanParam('custom2Input')) {
                     $id = OptionList::insertIfNotFound('person_custom_2_option', 'custom2_phrase', $this->getSanParam('custom2Input'));
                     $personrow->person_custom_2_option_id = $id;
                 } else {
                     $personrow->person_custom_2_option_id = null;
                 }
                 if ($this->setting('display_mod_skillsmart')) {
                     $personrow->govemp_option_id = $this->getSanParam('govemp_option_id');
                     $personrow->occupational_category_id = $this->getSanParam('occupational_category_id');
                     $personrow->persal_number = $this->getSanParam('persal_number');
                     $personrow->bodies_id = $this->getSanParam('professionalbodies_id');
                     $personrow->race_option_id = $this->getSanParam('race_option_id');
                     $personrow->disability_option_id = $this->getSanParam('disability_option_id');
                     $personrow->professional_reg_number = $this->getSanParam('professional_reg_number');
                     $personrow->nationality_id = $this->getSanParam('nationality_id');
                     $personrow->nurse_training_id = $this->getSanParam('nurse_training_id');
                     $personrow->care_start_year = $this->getSanParam('care_start_year');
                     $personrow->timespent_rank_pregnant = $this->getSanParam('timespent_rank_pregnant');
                     $personrow->timespent_rank_adults = $this->getSanParam('timespent_rank_adults');
                     $personrow->timespent_rank_children = $this->getSanParam('timespent_rank_children');
                     $personrow->timespent_rank_pregnant_pct = $this->getSanParam('timespent_rank_pregnant_pct');
                     $personrow->timespent_rank_adults_pct = $this->getSanParam('timespent_rank_adults_pct');
                     $personrow->timespent_rank_children_pct = $this->getSanParam('timespent_rank_children_pct');
                     $personrow->supervised_id = $this->getSanParam('supervised_id');
                     $personrow->supervision_frequency_id = $this->getSanParam('supervision_frequency_id');
                     $personrow->supervisors_profession = $this->getSanParam('supervisors_profession');
                     $personrow->facilitydepartment_id = $this->getSanParam('facilitydepartment_id');
                     $training_recieved_arr = array();
                     $training_recieved_data = '';
                     $training_recieved_results = array();
                     foreach ($ssl['training'] as $trainingnode) {
                         $training_recieved_arr[$trainingnode['id']] = $trainingnode['label'];
                     }
                     // build and insert training recieved vars in json
                     foreach ($_POST as $postvar => $postval) {
                         if (strstr($postvar, 'trainingrecieved_') && (isset($_POST[$postvar]) && $_POST[$postvar] != '')) {
                             $recv_str = '';
                             $recv_num = explode('_', $postvar);
                             if (isset($training_recieved_arr[intval($recv_num[1])])) {
                                 $recv_str = $training_recieved_arr[intval($recv_num[1])];
                                 $training_recieved_results[$recv_str][$recv_num[2]] = $postval;
                             }
                         }
                     }
                     if (!empty($training_recieved_results)) {
                         $training_recieved_data = json_encode($training_recieved_results);
                     }
                     $personrow->training_recieved_data = $training_recieved_data;
                     //$personrow->comments_skillsmart = $this->getSanParam('govemp_option_id');//0
                     /*
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('custom1Input');//1
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('race_option_id');//2
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('disability_option_id');//3
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('disability');//4
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('custom2Input');//5
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('rank1_option_id');//6
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('rank2_option_id');//7
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('rank3_option_id');//8
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('percent1');//9
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('percent2');//10
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('percent3');//11
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('supervised_option_id');//12
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('sfreq_option_id');//13
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('specifyfreqinput');//14
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('svoccu');//15
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother');//16
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother');//17
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother');//18
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother');//19
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('specifyoccupationinput');//20
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('trainer_type_option_id1');//21
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother0');//22
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother0');//23
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother0');//24
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother0');//25
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother1');//26
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother1');//27
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother1');//28
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother1');//29
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother2');//30
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother2');//31
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother2');//32
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother2');//33
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother3');//34
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother3');//35
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother3');//36
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother3');//37
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother4');//38
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother4');//39
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother4');//40
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother4');//41
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother5');//42
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother5');//43
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother5');//44
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother5');//45
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother6');//46
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother6');//47
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother6');//48
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother6');//49
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother7');//50
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother7');//51
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother7');//52
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother7');//53
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainother8');//54
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('checktrainother8');//55
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('selecttrainother8');//56
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('texttrainotherother8');//57
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('bodies_id');//58
                     $personrow->comments_skillsmart = $personrow->comments_skillsmart."§".$this->getSanParam('nationality_id');//59
                     */
                     if ($person_id) {
                         $trainsaved = array();
                         $train = $this->getSanParam('train');
                         foreach ($train as $key => $t) {
                             if (isset($t['check'])) {
                                 if ($t['originalid'] != 0) {
                                     // UPDATING EXISTING // moving this - cant really use $person_id before $personrow->save on adding a new user... probably should happen later or only on edits... im not sure
                                     $trainid = $t['originalid'];
                                     $query = "UPDATE link_person_training SET\n\t\t\t\t\t\t\t\t\tpersonid = '" . $person_id . "',\n\t\t\t\t\t\t\t\t\tyear = '" . addslashes($t['year']) . "',\n\t\t\t\t\t\t\t\t\tinstitution = '" . addslashes($t['text']) . "',\n\t\t\t\t\t\t\t\t\tothername = '' WHERE id = " . $trainid;
                                     error_log($query);
                                     $db->query($query);
                                 } else {
                                     // ADDING NEW
                                     $query = "INSERT INTO link_person_training SET\n\t\t\t\t\t\t\t\t\t\t\tpersonid = '" . $person_id . "',\n\t\t\t\t\t\t\t\t\t\t\ttrainingid = '" . addslashes($key) . "',\n\t\t\t\t\t\t\t\t\t\t\tyear = '" . addslashes($t['year']) . "',\n\t\t\t\t\t\t\t\t\t\t\tinstitution = '" . addslashes($t['text']) . "',\n\t\t\t\t\t\t\t\t\t\t\tothername = ''";
                                     error_log($query);
                                     $db->query($query);
                                     $trainid = $db->lastInsertId();
                                 }
                                 $trainsaved[] = $trainid;
                             }
                         }
                         if (count($trainsaved) > 0) {
                             // REMOVE ALL NON-SAVED TRAINING IDS FOR PERSON
                             $query = "DELETE FROM link_person_training WHERE personid = " . $person_id . " AND id NOT IN (" . implode(",", $trainsaved) . ")";
                             error_log($query);
                             $db->query($query);
                         } else {
                             // REMOVE ALL TRAINING IDS FOR PERSON
                             $query = "DELETE FROM link_person_training WHERE personid = " . $person_id;
                             error_log($query);
                             $db->query($query);
                         }
                     }
                 }
                 if ($personrow->save()) {
                     $status->setStatusMessage(t('The person was saved. Refreshing change history...'));
                     $_SESSION['status'] = t('The person was saved.');
                     $person_id = $personrow->id;
                     if ($this->setting('display_mod_skillsmart')) {
                         if (strlen($this->getSanParam('Facilities')) > 0) {
                             $db->query('UPDATE `facs` SET `Active`=\'N\' WHERE `person`=' . $person_id . ' AND `Active`=\'Y\';');
                             $Facs = split('\\$', $this->getSanParam('Facilities'));
                             foreach ($Facs as $kys => $vls) {
                                 $Locs = split("~", $vls);
                                 $Fac = $Locs[0];
                                 if ($strrpos = strrpos($Fac, '_')) {
                                     $Fac = substr($Fac, $strrpos + 1);
                                 }
                                 $db->query('INSERT INTO `facs` ( `person`, `facility`, `facstring`, `active`) VALUES (' . $person_id . ', ' . $Fac . ', \'' . $vls . '\', \'Y\');');
                             }
                         }
                         $co = 0;
                         for ($co = 1; $co <= 20; $co++) {
                             $db->query('UPDATE `trans` SET `Active`=\'N\' WHERE `person`=' . $person_id . ' AND `id`=' . $co . ' AND `Active`=\'Y\';');
                             if ($this->getSanParam('checktrain' . $co) == 'on') {
                                 $db->query('INSERT INTO `trans` ( `person`, `id`, `chk`, `yr`, `transstring`, `active`) VALUES (' . $person_id . ', ' . $co . ', \'' . $this->getSanParam('checktrain' . $co) . '\', \'' . $this->getSanParam('selecttrain' . $co) . '\', \'' . $this->getSanParam('texttrain' . $co) . '\', \'Y\');');
                             }
                         }
                     }
                     //get trainer information
                     $trainerTable = new Trainer();
                     $trainerRow = $trainerTable->fetchRow('person_id = ' . $person_id);
                     if (!$trainerRow and ($this->getSanParam('active_trainer_option_id') or $this->getSanParam('trainer_type_option_id'))) {
                         // add trainer
                         $trainerRow = $trainerTable->createRow();
                         $trainerRow->person_id = $personrow->id;
                     }
                     if ($trainerRow) {
                         //trainer info
                         $trainerRow->is_active = 1;
                         //deprecated //($this->getSanParam ( 'is_trainer' ) ? 1 : 0);
                         $trainerRow->active_trainer_option_id = $this->getSanParam('active_trainer_option_id');
                         $trainerRow->type_option_id = $this->getSanParam('trainer_type_option_id');
                         $trainerRow->affiliation_option_id = $this->setting('display_trainer_affiliations') ? $this->getSanParam('trainer_affiliation_option_id') ? $this->getSanParam('trainer_affiliation_option_id') : 0 : 0;
                         if (!$trainerRow->save()) {
                             $status->setStatusMessage(t('The') . ' ' . t('trainer') . ' ' . t('information could not be saved.'));
                         } else {
                             MultiOptionList::updateOptions('trainer_to_trainer_skill_option', 'trainer_skill_option', 'trainer_id', $person_id, 'trainer_skill_option_id', $this->getSanParam('trainer_skill_id'));
                             $language_ids = $this->getSanParam('trainer_language_id');
                             $planguage_id = $this->getSanParam('primary_language_id');
                             $primary_settings = array();
                             $found = false;
                             if ($language_ids) {
                                 foreach ($language_ids as $lid) {
                                     if ($lid == $planguage_id) {
                                         $primary_settings[] = 1;
                                         $found = true;
                                     } else {
                                         $primary_settings[] = 0;
                                     }
                                 }
                             }
                             if (!$found) {
                                 $primary_settings[] = 1;
                                 $language_ids[] = $planguage_id;
                             }
                             MultiOptionList::updateOptions('trainer_to_trainer_language_option', 'trainer_language_option', 'trainer_id', $person_id, 'trainer_language_option_id', $language_ids, 'is_primary', $primary_settings);
                         }
                     }
                     TrainingRecommend::saveRecommendedforPerson($person_id, $this->getSanParam('training_recommend'));
                     if ($this->_getParam('redirectUrl')) {
                         $status->redirect = $this->_getParam('redirectUrl');
                     } else {
                         if ($this->_getParam('trainingredirect')) {
                             // redirect back to training session
                             $this->trainingRedirect($person_id);
                         } else {
                             //if it's an add then redirect to the view page
                             if ($this->setting('display_mod_skillsmart')) {
                                 //$status->setRedirect ( '/person/view/id/' . $person_id );
                                 $qs = OptionList::suggestionListHierarchical('person_qualification_option', 'qualification_phrase', false, false, array('0 AS is_default', 'child.is_default'));
                                 $parent_id = $this->getSanParam('primary_qualification_option_id');
                                 foreach ($qs as $k => $v) {
                                     if ($v['id'] == $parent_id) {
                                         $parent_id = $v['parent_id'];
                                         break;
                                     }
                                 }
                                 $comps = $helper->getPersonCompetenciesDetailed($person_id);
                                 // Disabled redirect to competency page as per Robert's request, 11/19/2012, CDL
                                 //							if (count($comps) > 0){
                                 //								$status->setRedirect ( '/person/editcompetency/id/' . $person_id );
                                 //							} else {
                                 $status->setRedirect('/person/edit/id/' . $person_id);
                                 //							}
                                 /*
                                 							if($parent_id=="6")
                                 							{
                                 								$status->setRedirect ( '/person/addcomc/id/' . $person_id );
                                 							}
                                 							if($parent_id=="7")
                                 							{
                                 								$status->setRedirect ( '/person/addcomd/id/' . $person_id );
                                 							}
                                 							if($parent_id=="8")
                                 							{
                                 								$status->setRedirect ( '/person/addcomn/id/' . $person_id );
                                 							}
                                 							if($parent_id=="9")
                                 							{
                                 								$status->setRedirect ( '/person/addcomp/id/' . $person_id );
                                 							}
                                 */
                             } else {
                                 $status->setRedirect('/person/edit/id/' . $person_id);
                             }
                         }
                     }
                 } else {
                     $status->setStatusMessage(t('ERROR: The person could not be saved. ' . __LINE__));
                 }
             }
             if ($validateOnly) {
                 $this->sendData($status);
             } else {
                 $this->view->assign('status', $status);
             }
         }
         if ($this->setting('display_mod_skillsmart')) {
             if ($person_id) {
                 $rows = $db->fetchAll('SELECT `facstring` FROM `facs` INNER JOIN `facility` ON `facs`.`facility` = `facility`.`id` WHERE `facility`.`is_deleted`=0 AND `facs`.`person`=' . $person_id . ' AND `facs`.`Active`=\'Y\' ORDER BY `facs`.`sno` ASC;');
                 $Fcs = "";
                 foreach ($rows as $rw) {
                     $Fcs = $Fcs . $rw['facstring'] . '$';
                 }
                 $Fcs = trim($Fcs, '$');
                 $this->view->assign('Fcs', $Fcs);
                 $rows = $db->fetchAll('SELECT `id`, `chk`, `yr`, `transstring` FROM `trans` WHERE `person`=' . $person_id . ' AND `Active`=\'Y\' ORDER BY sno ASC;');
                 $Trs = array();
                 $c*k = 0;
                 for ($c*k = 1; $c*k <= 20; $c*k++) {
                     $Trs[$c*k] = NULL;
                 }
                 foreach ($rows as $rw) {
                     $Trs[$rw['id']] = $rw;
                 }
                 $this->view->assign('Trs', $Trs);
             }
         }
         //view it
         $facilityObj = new Facility();
         $facilityrow = $facilityObj->findOrCreate($personrow->facility_id);
         $personArray['facility'] = $facilityrow->toArray();
         //facility location
         $region_ids = Location::getCityInfo($facilityrow->location_id, $this->setting('num_location_tiers'));
         $region_ids = Location::regionsToHash($region_ids, 'person_facility');
         $personArray = array_merge($personArray, $region_ids);
         //audit history
         $creatorObj = new User();
         $updaterObj = new User();
         $creatorrow = $creatorObj->findOrCreate($personrow->created_by);
         $personArray['creator'] = addslashes($creatorrow->first_name . ' ' . $creatorrow->last_name);
         $updaterrow = $updaterObj->findOrCreate($personrow->modified_by);
         $personArray['updater'] = addslashes($updaterrow->first_name . ' ' . $updaterrow->last_name);
         $personArray['birthdate-year'] = '';
         $personArray['birthdate-month'] = '';
         $personArray['birthdate-day'] = '';
         //split birthdate fields
         if ($person_id and $personrow->birthdate) {
             $parts = explode(' ', $personrow->birthdate);
             $parts = explode('-', $parts[0]);
             $personArray['birthdate-year'] = $parts[0];
             $personArray['birthdate-month'] = $parts[1];
             $personArray['birthdate-day'] = $parts[2];
         }
         //custom fields
         if ($person_id) {
             $personArray['custom1'] = ITechTable::getCustomValue('person_custom_1_option', 'custom1_phrase', $personArray['person_custom_1_option_id']);
             $personArray['custom2'] = ITechTable::getCustomValue('person_custom_2_option', 'custom2_phrase', $personArray['person_custom_2_option_id']);
         }
         //qualifications
         $qualificationsArray = OptionList::suggestionListHierarchical('person_qualification_option', 'qualification_phrase', false, false, array('0 AS is_default', 'child.is_default'));
         $personQualificationId = $personArray['primary_qualification_option_id'];
         // get parent qualification id, if user has sub qualification selected
         $personArray['primary_qualification_option_id_parent'] = $personQualificationId;
         foreach ($qualificationsArray as $k => $qualArray) {
             if ($qualArray['parent_phrase'] == 'unknown') {
                 unset($qualificationsArray[$k]);
                 //remove unknown as an option
             }
             if ($qualArray['id'] == $personQualificationId) {
                 $personArray['primary_qualification_option_id_parent'] = $qualArray['parent_id'];
             }
         }
         $this->viewAssignEscaped('qualifications', $qualificationsArray);
         // occupational categories
         $occupationalsArray = OptionList::suggestionListHierarchical('occupational_categories', 'category_phrase', false, false, array('0 AS is_default', 'child.is_default'));
         $personQualificationId = $personArray['primary_qualification_option_id'];
         // get parent occupational category id, if user has sub qualification selected
         $personArray['occupational_category_id_parent'] = $personQualificationId;
         foreach ($occupationalsArray as $k => $catArray) {
             if ($catArray['category_phrase'] == 'unknown') {
                 unset($qualificationsArray[$k]);
                 //remove unknown as an option
             }
             if ($catArray['id'] == $personQualificationId) {
                 $personArray['occupational_category_id'] = $catArray['parent_id'];
             }
         }
         $this->viewAssignEscaped('occupationalcats', $occupationalsArray);
         // get recommended trainings class topics
         $training_recommend = TrainingRecommend::getRecommendedTrainingTopics($personArray['primary_qualification_option_id_parent']);
         $this->viewAssignEscaped('training_recommend', $training_recommend);
         // get saved recommended trainings class titles
         $training_recommend_saved = TrainingRecommend::getRecommendedforPerson($person_id);
         $this->viewAssignEscaped('training_recommend_saved', $training_recommend_saved);
         //$classes = TrainingRecommend::getRecommendedClassesforPerson ( $person_id );
         //responsibilities
         if ($this->setting('display_mod_skillsmart')) {
             $responsibilitiesArray = OptionList::suggestionList('person_responsibility_option', 'responsibility_phrase', false, false);
             $this->viewAssignEscaped('responsibilities', $responsibilitiesArray);
         }
         $primaryResponsibilitiesArray = OptionList::suggestionList('person_primary_responsibility_option', 'responsibility_phrase', false, false);
         $this->viewAssignEscaped('primaryResponsibilities', $primaryResponsibilitiesArray);
         $secondaryResponsibilitiesArray = OptionList::suggestionList('person_secondary_responsibility_option', 'responsibility_phrase', false, false);
         $this->viewAssignEscaped('secondaryResponsibilities', $secondaryResponsibilitiesArray);
         $educationlevelsArray = OptionList::suggestionList('person_education_level_option', 'education_level_phrase', false, false);
         $this->viewAssignEscaped('educationlevels', $educationlevelsArray);
         $attendreasonsArray = OptionList::suggestionList('person_attend_reason_option', 'attend_reason_phrase', false, false);
         $this->viewAssignEscaped('attendreasons', $attendreasonsArray);
         $activeTrainerArray = OptionList::suggestionList('person_active_trainer_option', 'active_trainer_phrase', false, false);
         $this->viewAssignEscaped('active_trainer', $activeTrainerArray);
         $titlesArray = OptionList::suggestionList('person_title_option', 'title_phrase', false, false);
         $this->viewAssignEscaped('titles', $titlesArray);
         $suffixesArray = OptionList::suggestionList('person_suffix_option', 'suffix_phrase', false, false);
         $this->viewAssignEscaped('suffixes', $suffixesArray);
         //training types
         //attach Trainer attributes
         $trainerTable = new Trainer();
         $trainerrow = $trainerTable->findOrCreate($person_id);
         $personArray['trainer_is_active'] = $this->getSanParam('maketrainer') ? 1 : $trainerrow->is_active;
         $personArray['active_trainer_option_id'] = $trainerrow->active_trainer_option_id;
         $personArray['trainer_type_option_id'] = $trainerrow->type_option_id;
         $personArray['trainer_affiliation_option_id'] = $trainerrow->affiliation_option_id;
         $titlesArray = OptionList::suggestionList('person_title_option', 'title_phrase', false, false);
         $this->viewAssignEscaped('titles', $titlesArray);
         $trainerTypesArray = OptionList::suggestionList('trainer_type_option', 'trainer_type_phrase', false, false);
         $this->viewAssignEscaped('trainer_types', $trainerTypesArray);
         $trainerAffiliationArray = OptionList::suggestionList('trainer_affiliation_option', 'trainer_affiliation_phrase', false, false);
         $this->viewAssignEscaped('trainer_affiliations', $trainerAffiliationArray);
         $trainerSkillsArray = MultiOptionList::choicesList('trainer_to_trainer_skill_option', 'trainer_id', $person_id, 'trainer_skill_option', 'trainer_skill_phrase');
         $this->viewAssignEscaped('trainer_skills', $trainerSkillsArray);
         $trainerLanguagesArray = MultiOptionList::choicesList('trainer_to_trainer_language_option', 'trainer_id', $person_id, 'trainer_language_option', 'language_phrase', 'is_primary');
         $this->viewAssignEscaped('trainer_languages', $trainerLanguagesArray);
         foreach ($trainerLanguagesArray as $lang) {
             if ($lang['is_primary']) {
                 $personArray['primary_language_id'] = $lang['id'];
             }
         }
         //has training history
         $hasTrainerHistory = false;
         if ($trainerrow->person_id) {
             $hasTrainerHistory = true;
             //we could also look up any history now, but we'll be lazy
         }
         $this->view->assign('hasTrainerHistory', $hasTrainerHistory);
         //facility types
         $typesArray = OptionList::suggestionList('facility_type_option', 'facility_type_phrase', false, false);
         $this->viewAssignEscaped('facility_types', $typesArray);
         //get home city name
         if ($personrow->home_location_id) {
             $region_ids = Location::getCityInfo($personrow->home_location_id, $this->setting('num_location_tiers'));
             $personArray['home_city'] = $region_ids[0];
             $region_ids = Location::regionsToHash($region_ids, 'home');
             $personArray = array_merge($personArray, $region_ids);
         }
         //sponsor types
         $sponsorsArray = OptionList::suggestionList('facility_sponsor_option', 'facility_sponsor_phrase', false, false);
         $this->viewAssignEscaped('facility_sponsors', $sponsorsArray);
         $this->viewAssignEscaped('person', $personArray);
         //facilities list
         //$rowArray = OptionList::suggestionList('facility',array('facility_name','id'),false,9999);
         $rowArray = Facility::selectAllFacilities($this->setting('num_location_tiers'));
         $this->viewAssignEscaped('facilities', $rowArray);
         if ($this->hasACL('edit_facility')) {
             $this->view->assign('insertFacilityLink', '<a href="#" id="show">' . str_replace(' ', '&nbsp;', t('Insert new facility')) . '</a>');
         }
         //see if it is referenced anywhere
         $this->view->assign('okToDelete', !$person_id or !Person::isReferenced($person_id));
         // create reference for GET paramaters
         if ($this->_getParam('trainingredirect')) {
             $this->view->assign('trainingredirect', $this->_getParam('trainingredirect'));
         }
         if ($this->_getParam('maketrainer')) {
             $this->view->assign('maketrainer', $this->_getParam('maketrainer'));
         }
         if ($this->_getParam('days')) {
             $this->view->assign('days', $this->_getParam('days'));
         }
     } catch (Exception $e) {
         print $e->getMessage();
     }
 }