/**
 * @version  $Id:$
 * @author	 Fabio Pirovano <fabio [at] docebo-com>
 * @package course
 */
function displayCourseList(&$url, $order_type)
{
    require_once _base_ . '/lib/lib.form.php';
    require_once _base_ . '/lib/lib.user_profile.php';
    require_once _base_ . '/lib/lib.navbar.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.preassessment.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.catalogue.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.course.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.coursereport.php';
    require_once $GLOBALS["where_framework"] . "/lib/lib.ajax_comment.php";
    require_once $GLOBALS['where_lms'] . '/lib/lib.classroom.php';
    // cahce classroom
    $classroom_man = new ClassroomManager();
    $classrooms = $classroom_man->getClassroomNameList();
    $lang =& DoceboLanguage::createInstance('catalogue');
    $lang_c =& DoceboLanguage::createInstance('course');
    $nav_bar = new NavBar('ini', Get::sett('visuItem'), 0);
    $man_course = new Man_Course();
    $id_parent = importVar('id_parent', false, 0);
    $nav_url = $id_parent != 0 ? $url->getUrl('id_parent=' . $id_parent) : $url->getUrl();
    $nav_bar->setLink($nav_url);
    $ini = $nav_bar->getSelectedElement();
    $profile = new UserProfile(getLogUserId());
    $profile->init('profile', 'framework', '', 'ap');
    $profile->addStyleSheet('lms');
    // searching courses
    $use_category = $order_type == 'category';
    $select_course = "" . " SELECT c.idCourse, c.course_type, c.idCategory, c.code, c.name, c.description, c.lang_code, c.difficult, " . "\tc.subscribe_method, c.date_begin, c.date_end, c.max_num_subscribe, " . "\tc.selling, c.prize, c.create_date, c.status AS course_status, c.course_edition, " . "\tc.classrooms, c.img_material, c.course_demo, c.course_vote, COUNT(*) as enrolled, " . "\tc.can_subscribe, c.sub_start_date, c.sub_end_date, c.allow_overbooking, c.max_num_subscribe, c.min_num_subscribe, c.direct_play, " . "\tc.valid_time, c.userStatusOp, u.level, u.date_inscr, u.date_first_access, u.date_complete, u.status AS user_status, u.waiting, c.advance ";
    $from_course = " FROM " . $GLOBALS['prefix_lms'] . "_course AS c " . "\tLEFT JOIN " . $GLOBALS['prefix_lms'] . "_courseuser AS u " . "\t\tON ( c.idCourse = u.idCourse ) ";
    $where_course = " c.status <> '" . CST_PREPARATION . "' ";
    if (Get::sett('catalogue_hide_ended') == 'on') {
        $where_course .= " AND ( c.date_end = '0000-00-00'" . " OR c.date_end > '" . date('Y-m-d') . "' ) ";
    }
    $group_by_course = " GROUP BY c.idCourse ";
    switch ($order_type) {
        case "mostscore":
            $order_course = " ORDER BY c.course_vote DESC ";
            break;
        case "popular":
            $order_course = " ORDER BY enrolled DESC ";
            break;
        case "recent":
            $order_course = " ORDER BY c.create_date DESC ";
            break;
        default:
            $order_course = " ORDER BY c.name ";
    }
    $limit_course = " LIMIT " . $ini . ", " . Get::sett('visuItem');
    $where_course .= " AND c.course_type <> 'assessment'";
    if (Docebo::user()->isAnonymous()) {
        $where_course .= " AND c.show_rules = 0";
    } else {
        $where_course .= " AND c.show_rules  <> 2";
    }
    // maybe a must apply some filter to remove from the list some courses --------------
    $cat_man = new Catalogue_Manager();
    $catalogues =& $cat_man->getUserAllCatalogueId(getLogUserId());
    // at least one catalogue is assigned to this user
    if (!empty($catalogues)) {
        $cat_courses = $cat_man->getAllCourseOfUser(getLogUserId());
        if (empty($cat_courses)) {
            $where_course .= " AND 0 ";
        } else {
            $where_course .= " AND c.idCourse IN ( " . implode(',', $cat_courses) . " ) ";
        }
    } elseif (Get::sett('on_catalogue_empty') == 'off') {
        $where_course .= " AND 0 ";
    }
    if (!Docebo::user()->isAnonymous()) {
        if (!isset($_SESSION['cp_assessment_effect'])) {
            $pa_man = new AssessmentList();
            $arr_assessment = $pa_man->getUserAssessmentSubsription(Docebo::user()->getArrSt());
            $report = new CourseReportManager();
            $user_result = $report->getAllUserFinalScore(getLogUserId(), $arr_assessment['course_list']);
            $rule_man = new AssessmentRule();
            $ass_elem = $rule_man->getCompleteEffectListForAssessmentWithUserResult($arr_assessment['course_list'], $user_result);
            $_SESSION['cp_assessment_effect'] = urlencode(serialize($ass_elem));
        } else {
            $ass_elem = unserialize(urldecode($_SESSION['cp_assessment_effect']));
        }
        if (!empty($ass_elem['parsed']['course'])) {
            $where_course = " ( ( " . $where_course . " ) OR c.idCourse IN (" . implode(',', $ass_elem['parsed']['course']) . ") ) ";
        }
    }
    // apply search filter --------------------------------------------------------------
    $s_searched = get_searched('simple_search', '');
    $filter_lang = get_searched('filter_lang', 'all');
    $filter_date_begin = get_searched('filter_date_begin', '');
    if ($filter_date_begin != '') {
        $filter_date_begin = Format::dateDb($filter_date_begin, 'date') . ' 00:00:00';
    }
    $filter_date_end = get_searched('filter_date_end', '');
    if ($filter_date_end != '') {
        $filter_date_end = Format::dateDb($filter_date_end, 'date') . ' 00:00:00';
    }
    $all_lang = Docebo::langManager()->getAllLangCode();
    if (must_search_filter()) {
        if (trim($s_searched) != '') {
            $where_course .= " AND ( c.code LIKE '%" . $s_searched . "%' " . " OR c.name LIKE '%" . $s_searched . "%' " . " OR c.description LIKE '%" . $s_searched . "%' ) ";
        }
        if ($filter_lang != 'all') {
            $where_course .= " AND c.lang_code = '" . $all_lang[$filter_lang] . "' ";
        }
        if ($filter_date_begin != '') {
            $where_course .= " AND ( c.date_begin >= '" . $filter_date_begin . "' OR c.course_edition = 1 ) ";
        }
        if ($filter_date_end != '') {
            $where_course .= " AND ( c.date_end <= '" . $filter_date_end . "' OR c.course_edition = 1 ) ";
        }
    }
    if ($use_category) {
        $where_course .= " AND c.idCategory = '" . (int) $id_parent . "'";
    }
    $re_course = sql_query($select_course . $from_course . " WHERE " . $where_course . $group_by_course . $order_course . $limit_course);
    list($course_number) = sql_fetch_row(sql_query("SELECT COUNT(*) " . " FROM " . $GLOBALS['prefix_lms'] . "_course AS c " . " WHERE " . $where_course));
    $nav_bar->setElementTotal($course_number);
    // retrive editions ----------------------------------------------------------------
    $select_edition = " SELECT e.* ";
    $from_edition = " FROM " . $GLOBALS["prefix_lms"] . "_course_edition AS e";
    $where_edition = " WHERE e.status <> '" . CST_PREPARATION . "' ";
    $where_edition .= " AND (e.date_begin > '" . date("Y-m-d H:i:s") . "' OR e.date_begin = '0000-00-00 00:00:00')";
    $order_edition = " ORDER BY date_begin ";
    if (must_search_filter()) {
        if ($filter_date_begin != '') {
            $where_edition .= " AND date_begin >= '" . $filter_date_begin . "' ";
        }
        if ($filter_date_end != '') {
            $where_edition .= " AND date_end <= '" . $filter_date_end . "' ";
        }
    }
    $re_edition = sql_query($select_edition . $from_edition . $where_edition . $order_edition);
    $editions = array();
    if ($re_edition) {
        while ($edition_elem = mysql_fetch_assoc($re_edition)) {
            $edition_elem['classrooms'] = isset($classrooms[$edition_elem['classrooms']]) ? $classrooms[$edition_elem['classrooms']] : '';
            $edition_elem['waiting'] = 0;
            $edition_elem['user_count'] = 0;
            $edition_elem['theacher_list'] = getSubscribed($edition_elem["idCourse"], false, 6, true, $edition_elem["idCourseEdition"]);
            $editions[$edition_elem["idCourse"]][$edition_elem["idCourseEdition"]] = $edition_elem;
        }
    }
    // retrive editions subscribed -----------------------------------------------------
    $select_ed_count = "SELECT u.idCourse, u.edition_id, sum(u.waiting) as waiting, COUNT(*) as user_count ";
    $from_ed_count = " FROM " . $GLOBALS["prefix_lms"] . "_courseuser AS u";
    $where_ed_count = " WHERE u.edition_id <> 0 " . " AND u.level = '3'" . " AND u.status IN ('" . _CUS_CONFIRMED . "', '" . _CUS_SUBSCRIBED . "', '" . _CUS_BEGIN . "', '" . _CUS_END . "', '" . _CUS_SUSPEND . "', '" . _CUS_WAITING_LIST . "')" . " AND u.absent = '0'";
    $group_ed_count = "GROUP BY u.edition_id ";
    $re_ed_count = sql_query($select_ed_count . $from_ed_count . $where_ed_count . $group_ed_count);
    if ($re_ed_count) {
        while ($ed_count_elem = mysql_fetch_assoc($re_ed_count)) {
            if (isset($editions[$ed_count_elem["idCourse"]][$ed_count_elem["edition_id"]])) {
                $editions[$ed_count_elem["idCourse"]][$ed_count_elem["edition_id"]]['waiting'] = $ed_count_elem['waiting'];
                $editions[$ed_count_elem["idCourse"]][$ed_count_elem["edition_id"]]['user_count'] = $ed_count_elem['user_count'];
            }
        }
    }
    // retrive course subscription -----------------------------------------------------
    $man_courseuser = new Man_CourseUser();
    $usercourses = $man_courseuser->getUserSubscriptionsInfo(getLogUserId(), false);
    $user_score = $man_courseuser->getUserCourseScored(getLogUserId());
    require_once $GLOBALS['where_lms'] . '/lib/lib.orgchart.php';
    $first_is_scorm = OrganizationManagement::objectFilter(array_keys($usercourses), 'scormorg');
    // load search form ----------------------------------------------------------------
    $GLOBALS['page']->add(searchForm($url, $lang), 'content');
    if ($use_category && !must_search_filter()) {
        // show category selection -----------------------------------------------------
        $descendant = $man_course->getCategoryCourseAndSonCount();
        $GLOBALS['page']->add('<p class="category_path">' . '<b>' . $lang->def('_CATEGORY_PATH', 'course') . ' :</b> ' . $man_course->getCategoryPath($id_parent, $lang->def('_MAIN_CATEGORY', 'course'), $lang->def('_TITLE_CATEGORY_JUMP', 'course'), $url->getUrl(), 'id_parent') . '</p>', 'content');
        $categories =& $man_course->getCategoriesInfo($id_parent);
        if (!empty($categories)) {
            $GLOBALS['page']->add('<ul class="category_list">', 'content');
            while (list($id_cat, $cat) = each($categories)) {
                $GLOBALS['page']->add('<li' . (!isset($descendant[$id_cat]) ? ' class="empty_folder"' : '') . '>' . '<a href="' . $url->getUrl('id_parent=' . $id_cat) . '">' . $cat['name'] . '<br />' . '<b>' . str_replace(array('[course]', '[category]'), array(isset($descendant[$id_cat]['course']) ? $descendant[$id_cat]['course'] : 0, isset($descendant[$id_cat]['category']) ? $descendant[$id_cat]['category'] : 0), $lang->def('_COURSE_CONTENT', 'course')) . '</b>' . '</a></li>', 'content');
            }
            $GLOBALS['page']->add('</ul>' . '<div class="nofloat"></div>', 'content');
        }
    }
    if (!$re_course || !mysql_num_rows($re_course)) {
        // no course found for the criteria --------------------------------------------
        $GLOBALS['page']->add('<p class="no_course_found">' . $lang->def('_NO_COURSE_FOUND') . '</p>' . '</div>', 'content');
        return;
    }
    $ax_comm = new AjaxComment('course', 'lms');
    $comment_count = $ax_comm->getResourceCommentCount();
    $GLOBALS['page']->add($nav_bar->getNavBar($ini), 'content');
    $i = 0;
    $direct_play = false;
    while ($cinfo = mysql_fetch_assoc($re_course)) {
        if (must_search_filter()) {
            $s_searched = get_searched('simple_search', '');
            if ($s_searched != '') {
                $cinfo['code'] = preg_replace("/" . $s_searched . "/i", '<b class="filter_evidence">' . $s_searched . '</b>', $cinfo['code']);
                $cinfo['name'] = preg_replace("/" . $s_searched . "/i", '<b class="filter_evidence">' . $s_searched . '</b>', $cinfo['name']);
                $cinfo['description'] = preg_replace("/" . $s_searched . "/i", '<b class="filter_evidence">' . $s_searched . '</b>', $cinfo['description']);
            }
        }
        $cinfo['theacher_list'] = getSubscribed($cinfo['idCourse'], false, 6, true);
        $cinfo['edition_list'] = isset($editions[$cinfo['idCourse']]) ? $editions[$cinfo['idCourse']] : array();
        $cinfo['edition_available'] = count($cinfo['edition_list']);
        $cinfo['user_score'] = isset($user_score[$cinfo['idCourse']]) ? $user_score[$cinfo['idCourse']] : NULL;
        $cinfo['classrooms'] = isset($classrooms[$cinfo['classrooms']]) ? $classrooms[$cinfo['classrooms']] : '';
        if (isset($first_is_scorm[$cinfo['idCourse']])) {
            $cinfo['first_is_scorm'] = $first_is_scorm[$cinfo['idCourse']];
        } else {
            $cinfo['first_is_scorm'] = false;
        }
        if (isset($comment_count[$cinfo['idCourse']])) {
            $cinfo['comment_count'] = $comment_count[$cinfo['idCourse']];
        }
        $view = true;
        if (must_search_filter()) {
            if ($cinfo['course_edition'] == 1 && empty($cinfo['edition_list'])) {
                $view = false;
            }
        }
        if ($view) {
            $GLOBALS['page']->add(dashcourse($url, $lang_c, $cinfo, isset($usercourses[$cinfo['idCourse']]) ? $usercourses[$cinfo['idCourse']] : false, $i++), 'content');
        }
        if ($cinfo['direct_play'] == 1) {
            $direct_play = true;
        }
    }
    if ($direct_play) {
        $GLOBALS['page']->add('' . '	<link href="' . getPathTemplate() . '/style/shadowbox.css" rel="stylesheet" type="text/css" />' . '<script type="text/javascript" src="' . $GLOBALS['where_framework_relative'] . '/addons/shadowbox/shadowbox-yui.js"></script>' . "\n" . '<script type="text/javascript" src="' . $GLOBALS['where_framework_relative'] . '/addons/shadowbox/shadowbox.js"></script>' . "\n", 'page_head');
        $GLOBALS['page']->add('<script type="text/javascript">
	
		YAHOO.util.Event.onDOMReady(function() {
			var options = { listenOverlay:false, overlayOpacity:"0.8", 
				loadingImage:"' . getPathImage('lms') . 'standard/loading.gif", overlayBgImage:"' . getPathImage('lms') . 'standard/overlay-85.png", 
				text: {close: "' . Lang::t('_CLOSE') . '", cancel: "' . Lang::t('_UNDO') . '", loading:"' . Lang::t('_LOADING') . '" },
				onOpen: function (gallery) { window.onbeforeunload = function() { return "' . Lang::t('_CONFIRM_EXIT', 'organization', 'lms') . '"; } }
		    }; 
			Shadowbox.init(options); 
			Shadowbox.close = function() {
				window.onbeforeunload = null;
				window.frames[\'shadowbox_content\'].uiPlayer.closePlayer(true, window);
			}
		});
		</script>');
    }
    $GLOBALS['page']->add($nav_bar->getNavBar($ini), 'content');
}