/**
 * Select milestone category control
 * 
 * Params:
 * 
 * - Commong SELECT attributes
 * - Value - Selected milestone category id
 *
 * @param array $params
 * @return string
 */
function smarty_function_select_milestone_category($params, &$smarty)
{
    $project = array_var($params, 'project');
    $project_id = 0;
    if (instance_of($project, 'Project')) {
        $project_id = $project->getId();
    }
    // if
    $categories = array();
    $categories[] = array('id' => '0', 'text' => '-- select  --');
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    mysql_select_db(DB_NAME);
    $sql = "select id as id, category_name as text from healingcrystals_project_milestone_categories where project_id='" . do_json_encode($project_id) . "' order by category_name";
    $result = mysql_query($sql, $link);
    while ($entry = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $categories[] = $entry;
    }
    mysql_close($link);
    $value = 0;
    if (isset($params['value'])) {
        $value = $params['value'];
        unset($params['value']);
    }
    // if
    $options = array();
    for ($i = 0; $i < count($categories); $i++) {
        $option_attribites = $categories[$i]['id'] == $value ? array('selected' => true) : null;
        $options[] = option_tag($categories[$i]['text'], $categories[$i]['id'], $option_attribites);
    }
    return select_box($options, $params);
}
/**
 * Render select assignees box
 * 
 * Parameters:
 * 
 * - object     - Parent object
 * - project    - Show only users that have access to this project
 * - company    - SHow only users that are members of tis company
 * - exclude    - ID-s of users that need to be excluded
 * - value      - Array of selected users as first element and ID of task 
 *                owner as second
 * - name       - Base name
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_select_assignees($params, &$smarty)
{
    static $counter = 0;
    $name = array_var($params, 'name');
    if ($name == '') {
        return new InvalidParamError('name', $name, '$name is expected to be a valid control name', true);
    }
    // if
    $id = array_var($params, 'id');
    if (empty($id)) {
        $counter++;
        $id = 'select_assignees_' . $counter;
    }
    // if
    $exclude_ids = array_var($params, 'exclude', array());
    if (is_foreachable($exclude_ids) && is_foreachable($selected_user_ids)) {
        foreach ($selected_user_ids as $k => $v) {
            if (in_array($v, $exclude_ids)) {
                unset($selected_user_ids[$k]);
            }
            // if
        }
        // foreach
    }
    // if
    $value = array_var($params, 'value', array(), true);
    if (count($value) == 2) {
        list($selected_user_ids, $owner_id) = $value;
    } else {
        $selected_user_ids = null;
        $owner_id = null;
    }
    // if
    if (is_foreachable($selected_user_ids)) {
        $selected_users = Users::findByIds($selected_user_ids);
    } else {
        $selected_users = null;
    }
    // if
    $company = array_var($params, 'company');
    $project = array_var($params, 'project');
    $company_id = 0;
    if (instance_of($company, 'Company')) {
        $company_id = $company->getId();
    }
    // if
    $project_id = 0;
    if (instance_of($project, 'Project')) {
        $project_id = $project->getId();
    }
    // if
    require_once ANGIE_PATH . '/classes/json/init.php';
    $smarty->assign(array('_select_assignees_id' => $id, '_select_assignees_name' => $name, '_select_assignees_users' => $selected_users, '_select_assignees_owner_id' => $owner_id, '_select_assignees_company_id' => do_json_encode($company_id), '_select_assignees_project_id' => do_json_encode($project_id), '_select_assignees_exclude_ids' => do_json_encode($exclude_ids)));
    return $smarty->fetch(get_template_path('_select_assignees', null, RESOURCES_MODULE));
}
/**
 * Assign template vars to javascript
 * 
 * This function will make available all template vars to JavaScript by 
 * converting them to JSON
 * 
 * Parameters:
 * 
 * - domain - domain where we'll put variables. Default is 'App.data'
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_template_vars_to_js($params, &$smarty)
{
    $vars = gs_get('assigned_to_js');
    if (is_foreachable($vars)) {
        $prefix = array_var($params, 'domain', 'App.data');
        $code = "if(!{$prefix}) { {$prefix} = {}; }\n";
        foreach ($vars as $k => $v) {
            $code .= "{$prefix}.{$k} = " . do_json_encode($v) . ";\n";
        }
        // foreach
        return "<script type=\"text/javascript\">\n{$code}\n</script>";
    }
    // if
    return '';
}
/**
 * Render object assignees list
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_select_departments($params, &$smarty)
{
    $project = array_var($params, 'project');
    $project_id = 0;
    if (instance_of($project, 'Project')) {
        $project_id = $project->getId();
    }
    // if
    $object = array_var($params, 'object');
    $categories = array();
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    mysql_select_db(DB_NAME);
    $sql = "select id as id, category_name as text from healingcrystals_project_milestone_categories where project_id='" . do_json_encode($project_id) . "' order by category_name";
    $result = mysql_query($sql, $link);
    while ($entry = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $categories[] = $entry;
    }
    //$categories[] = array('id' => '0', 'text' => 'None');
    $reg_vals = array();
    if ($object && $object->getId()) {
        $query = "select category_id from healingcrystals_project_object_categories where object_id='" . $object->getId() . "'";
        $result = mysql_query($query, $link);
        while ($info = mysql_fetch_assoc($result)) {
            $reg_vals[] = $info['category_id'];
        }
    }
    mysql_close($link);
    $params['multiple'] = 'true';
    $params['size'] = '5';
    $options = array();
    for ($i = 0; $i < count($categories); $i++) {
        $option_attribites = in_array($categories[$i]['id'], $reg_vals) ? array('selected' => true) : null;
        $options[] = option_tag($categories[$i]['text'], $categories[$i]['id'], $option_attribites);
    }
    return select_box($options, $params);
}
/**
 * Encode data to JSON
 *
 * @param mixed $data
 * @return string
 */
function smarty_modifier_json($data)
{
    require_once ANGIE_PATH . '/classes/json/init.php';
    return do_json_encode($data);
}
 /**
  * Serve data to the client
  *
  * @param mixed $data
  * @param string $as
  * @param string $format
  * @param boolean $die
  * @return null
  */
 function serveData($data, $as = null, $format = null, $die = true)
 {
     if ($format === null) {
         $format = $this->request->getFormat();
     }
     // if
     switch ($format) {
         case FORMAT_JSON:
             header('Content-Type: application/json; charset=utf-8');
             print do_json_encode($data, $as);
             break;
         case FORMAT_XML:
             header('Content-Type: application/xml; charset=utf-8');
             print do_xml_encode($data, $as);
             break;
         default:
             print $data;
     }
     // switch
     if ($die) {
         die;
     }
     // if
 }
 /**
  * Show quick add form
  *
  * @param void
  * @return null
  */
 function quick_add()
 {
     $this->wireframe->current_menu_item = 'quick_add';
     $quick_add_urls = array();
     event_trigger('on_quick_add', array(&$quick_add_urls));
     $all_projects_permissions = array_keys($quick_add_urls);
     $formatted_map = array();
     $projects_roles_map = ProjectUsers::getProjectRolesMap($this->logged_user, array(PROJECT_STATUS_ACTIVE));
     if (!is_foreachable($projects_roles_map)) {
         print lang('There are no active projects that you are involved with');
         die;
     }
     // if
     if (is_foreachable($projects_roles_map)) {
         foreach ($projects_roles_map as $project_id => $project_role_map) {
             $formatted_map[$project_id] = array('name' => array_var($project_role_map, 'name'));
             $project_leader = array_var($project_role_map, 'leader');
             $project_role_permissions = array_var($project_role_map, 'permissions', null);
             if ($this->logged_user->isAdministrator() || $this->logged_user->isProjectManager() || $this->logged_user->getId() == $project_leader) {
                 foreach ($all_projects_permissions as $current_permission) {
                     $formatted_map[$project_id]['permissions'][] = array('title' => lang($current_permission), 'name' => $current_permission);
                 }
                 // if
             } else {
                 foreach ($all_projects_permissions as $current_permission) {
                     if (array_var($project_role_permissions, $current_permission, 0) > 1) {
                         $formatted_map[$project_id]['permissions'][] = array('title' => lang($current_permission), 'name' => $current_permission);
                     }
                     // if
                 }
                 // if
             }
             // if
         }
         // foreach
     }
     // if
     $this->smarty->assign(array('formatted_map' => $formatted_map, 'quick_add_url' => $quick_add_url, 'js_encoded_formatted_map' => do_json_encode($formatted_map), 'js_encoded_quick_add_urls' => do_json_encode($quick_add_urls)));
 }
/**
 * Render select projects widget
 * 
 * Parameters:
 * 
 * - user - Instance of user accesing the page, required
 * - exclude - Single project or array of projects that need to be excluded
 * - value - Array of selected projects
 * - active_only - List only active projects
 * - show_all - If true and user is project manager / administrator, all 
 *   projects will be listed
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_select_projects($params, &$smarty)
{
    static $ids = array();
    $name = array_var($params, 'name');
    if ($name == '') {
        return new InvalidParamError('name', $name, '$name is expected to be a valid control name', true);
    }
    // if
    $user = array_var($params, 'user', null, true);
    if (!instance_of($user, 'User')) {
        return new InvalidParamError('user', $user, '$user is expected to be an instance of User class', true);
    }
    // if
    $id = array_var($params, 'id', null, true);
    if (empty($id)) {
        $counter = 1;
        do {
            $id = "select_projects_{$counter}";
        } while (in_array($id, $ids));
    }
    // if
    $ids[] = $id;
    $show_all = array_var($params, 'show_all', false) && $user->isProjectManager();
    $exclude = array_var($params, 'exclude', array(), true);
    if (!is_array($exclude)) {
        $exclude = array($exclude);
    }
    // if
    $value = array_var($params, 'value', null, true);
    if (is_foreachable($value) && count($exclude)) {
        foreach ($value as $k => $v) {
            if (in_array($v, $exclude)) {
                unset($value[$k]);
            }
            // if
        }
        // foreach
    }
    // if
    $selected_projects = is_foreachable($value) ? Projects::findByIds($value) : null;
    require_once ANGIE_PATH . '/classes/json/init.php';
    $smarty->assign(array('_select_projects_id' => $id, '_select_projects_name' => array_var($params, 'name'), '_select_projects_user' => $user, '_select_projects_projects' => $selected_projects, '_select_projects_exclude_ids' => do_json_encode($exclude), '_select_projects_active_only' => array_var($params, 'active_only', true), '_select_projects_show_all' => $show_all));
    return $smarty->fetch(get_template_path('_select_projects', null, SYSTEM_MODULE));
    // ---------------------------------------------------
    //  Old!
    // ---------------------------------------------------
    $projects_table = TABLE_PREFIX . 'projects';
    $project_users_table = TABLE_PREFIX . 'project_users';
    if ($show_all) {
        $projects = db_execute_all("SELECT {$projects_table}.id, {$projects_table}.name, {$projects_table}.status FROM {$projects_table} WHERE {$projects_table}.type = ? ORDER BY {$projects_table}.name", PROJECT_TYPE_NORMAL);
    } else {
        $projects = db_execute_all("SELECT {$projects_table}.id, {$projects_table}.name, {$projects_table}.status FROM {$projects_table}, {$project_users_table} WHERE {$project_users_table}.user_id = ? AND {$project_users_table}.project_id = {$projects_table}.id AND {$projects_table}.type = ? ORDER BY {$projects_table}.name", $user->getId(), PROJECT_TYPE_NORMAL);
    }
    // if
    $active_options = array();
    $archived_options = array();
    if (is_foreachable($projects)) {
        foreach ($projects as $k => $project) {
            if (in_array($project['id'], $exclude)) {
                continue;
            }
            // if
            $option_attributes = $project['id'] == $value ? array('selected' => true) : null;
            if ($project['status'] == PROJECT_STATUS_ACTIVE) {
                $active_options[] = option_tag($project['name'], $project['id'], $option_attributes);
            } else {
                $archived_options[] = option_tag($project['name'], $project['id'], $option_attributes);
            }
            // if
        }
        // if
    }
    // if
    $optional = array_var($params, 'optional', false, true);
    $options = array();
    if ($optional) {
        $options[] = option_tag(lang(array_var($params, 'optional_caption', '-- Select Project --')), '');
        $options[] = option_tag('', '');
    }
    // if
    if (is_foreachable($active_options)) {
        $options[] = option_group_tag(lang('Active'), $active_options);
    }
    // if
    if (is_foreachable($active_options) && is_foreachable($archived_options)) {
        $options[] = option_tag('', '');
    }
    // if
    if (is_foreachable($archived_options)) {
        $options[] = option_group_tag(lang('Archive'), $archived_options);
    }
    // if
    return select_box($options, $params);
}