<?php
if (!defined('_VALID_MOS') && !defined('_JEXEC')) die('Direct Access to ' . basename(__FILE__) 
        . ' is not allowed.');
/**
 *
 * @package  MediaLibrary
 * @copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com);
 * Homepage: https://ordasoft.com
 * @version: 4.6 Free
 * @license GNU General Public license version 2 or later; see LICENSE.txt
 *
 */

date_default_timezone_set('Europe/Moscow');
include_once (JPATH_SITE . "/components/com_medialibrary/compat.joomla1.5.php");
include_once (JPATH_SITE . "/components/com_medialibrary/functions.php");
if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);

//function t($q) {echo "<pre>"; print_r($q); echo "</pre>"; exit; }
$my = $GLOBALS['my'];

jimport('joomla.html.pagination');
jimport('joomla.application.pathway');
jimport('joomla.filesystem.folder');
$database = JFactory::getDBO();
$css = $mosConfig_live_site . '/components/com_medialibrary/includes/medialibrary.css';
$mainframe = JFactory::getApplication();
require_once ($mosConfig_absolute_path . "/administrator/components/com_medialibrary/medialibrary.html.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.language.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_game.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_music.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_book.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_video.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.lend.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.lend_request.php");
require_once ($mosConfig_absolute_path . 
        "/administrator/components/com_medialibrary/admin.medialibrary.class.ws.php");
require_once ($mosConfig_absolute_path . 
        "/administrator/components/com_medialibrary/admin.medialibrary.class.impexp.php");
require_once ($mosConfig_absolute_path . 
        "/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/functions.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.main.categories.class.php");
global $mosConfig_lang;
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.people.php");
require_once ($mosConfig_absolute_path . 
        "/administrator/components/com_content/models/fields/modal/article.php");
require_once ($mosConfig_absolute_path . 
        "/components/com_medialibrary/medialibrary.class.article.php");
$my = $GLOBALS['my'];
$GLOBALS['medialibrary_configuration'] = $medialibrary_configuration;
$GLOBALS['database'] = $database;
$GLOBALS['my'] = $my;
$GLOBALS['mosConfig_absolute_path'] = $mosConfig_absolute_path;
$GLOBALS['table_prefix'] = $table_prefix = $database->getPrefix();
$GLOBALS['task'] = $task = mosGetParam($_REQUEST, 'task', '');
$GLOBALS['option'] = $option = mosGetParam($_REQUEST, 'option', 'com_medialibrary');

$doc->addScript($mosConfig_live_site . '/components/com_medialibrary/includes/jquery.min.js');

require_once ($mosConfig_absolute_path . "/administrator/components/com_medialibrary/toolbar.medialibrary.php");
// load language
require_once $mosConfig_absolute_path . "/administrator/components/com_medialibrary/language.php";
$bid = mosGetParam($_POST, 'bid', array(0));
$media_type = mosGetParam($_POST, 'media_type', "book");
$section = mosGetParam($_REQUEST, 'section', 'courses');
// --------------- Debug mode ----------------
$medialibrary_configuration['debug'] = 0;



if ($medialibrary_configuration['debug'] == '1') {
    echo "Task: " . $task . "<br />";
    print_r($_POST);
    echo "<hr>";
    print_r($_GET);
    echo "<hr /><br />";
    echo $task;
}

// print_r($task);exit;

if (isset($section) && $section == 'categories') {
    switch ($task) {
        case "edit":
            editCategory($option, $bid[0]);
        break;
        case "add": // J 1.6
            editCategory($option, 0);
        break;
        case "cancel":
            cancelCategory();
        break;
        case "save":
            saveCategory();
        break;
        case "remove":
            removeCategories($option, $bid);
        break;
        case "publish":
            publishCategories("com_medialibrary", $id, $bid, 1);
        break;
        case "unpublish":
            publishCategories("com_medialibrary", $id, $bid, 0);
        break;
        case "orderup":
            orderCategory($bid[0], -1);
        break;
        case "orderdown":
            orderCategory($bid[0], 1);
        break;

        case "show":
        default:
            showCategories();
            break;
    }
} elseif ($section == 'language_manager') {
    $bid = mosGetParam($_POST, 'vid', array(0));
    switch ($task) {
        case "edit":
            editLanguageManager($option, $bid[0]);
        break;
        case "cancel":
            cancelLanguageManager();
        break;
        case "save":
            saveLanguageManager();
        break;
        default:
            showLanguageManager($option);
        break;
    }
} else {
    switch ($task) {
        case "categories":
            echo "now work $section=='categories , this part not work";
            exit;
            mosRedirect("index.php?option=categories&extension=com_medialibrary");
        break;

        case "delProduct":
            delProduct($bid);
            showMedias($option);
        break;
        case "addProduct":
            addProduct($bid, $option);
        break;
        case "add": // J1.6
            editMedia($option, 0, $media_type);
        break;
        case "edit":
            editMedia($option, array_pop($bid), $media_type);
        break;
        case "show_all":
            unsetCatId();
        break;
        case "refetchInfos":
            refetchInfo($option, $bid);
        break;
        case "apply":
        case "save":
            saveMedia($option, $task);
        break;
        case "remove":
            removeMedia($bid, $option);
        break;
        case "publish":
            publishMedias($bid, 1, $option);
        break;
        case "unpublish":
            publishMedias($bid, 0, $option);
        break;
        case "approve":
            approveMedias($bid, 1, $option);
        break;
        case "unapprove":
            approveMedias($bid, 0, $option);
        break;
        case "cancel":
            cancelEditMedia($option);
        break;
        case "bookorderdown":
            orderBooks($bid[0], 1, $option);
        break;
        case "bookorderup":
            orderBooks($bid[0], -1, $option);
        break;
        case "show_import_export":
            importExport($option);
        break;
        case "import":
            import($option);
        break;
        case "export":
            export($option);
        break;
        case "config":
            configure($option);
        break;
        case "randNumber":
             randNumber();
        break;

        // ********************begin userlend history **************************
        case "user_lend_history":
             userLendHistory($option, '');
        break;
        case "sorting_userlend_numer":
            userLendHistory($option, "media_id");
        break;
        case "sorting_userlend_media_type_id":
            userLendHistory($option, "media_type_id");
        break;
        case "sorting_userlend_media_type":
            userLendHistory($option, "type");
        break;
        case "sorting_userlend_media_title":
            userLendHistory($option, "title");
        break;
        case "sorting_userlend_lendfrom":
            userLendHistory($option, "lend_from");
        break;
        case "sorting_userlend_lentuntil":
            userLendHistory($option, "lend_until");
        break;
        case "sorting_userlend_returnmedia":
            userLendHistory($option, "lend_return");
        break;
        case "sorting_userlend_email":
            userLendHistory($option, "user_email");
        break;
        
        //**********************end userlend history *******************************

            //***************   begin for manage reviews   ***********************

        case "manage_review":
            manage_review_s($option, "");
        break;
        case "publish_manage_review":
            publish_manage_review($bid, 1, $option);
        break;
        case "unpublish_manage_review":
            publish_manage_review($bid, 0, $option);
        break;
        case "delete_manage_review":
            delete_manage_review($option, $bid);
            manage_review_s($option, "");
        break;
        case "edit_manage_review":
            edit_manage_review($option, $bid);
        break;
        case "update_edit_manage_review":
            $title = JRequest::getVar('title');
            $comment = JRequest::getVar('comment');
            $rating = JRequest::getVar('rating');
            $book_id = JRequest::getVar('book_id');
            $review_id = JRequest::getVar('review_id');
            update_review($title, $comment, $rating, $review_id);
            manage_review_s($option, "");
        break;
        case "cancel_edit_manage_review":
            manage_review_s($option, "");
        break;
        case "sorting_manage_review_numer":
            manage_review_s($option, "review_id");
        break;
        case "sorting_manage_review_media_type":
            manage_review_s($option, "media_type");
        break;
        case "sorting_manage_review_media_title":
            manage_review_s($option, "media_title");
        break;
        case "sorting_manage_review_title_catigory":
            manage_review_s($option, "title_catigory");
        break;
        case "sorting_manage_review_title_review":
            manage_review_s($option, "title_review");
        break;
        case "sorting_manage_review_user_name":
            manage_review_s($option, "user_name");
        break;
        case "sorting_manage_review_date":
            manage_review_s($option, "date");
        break;
        case "sorting_manage_review_rating":
            manage_review_s($option, "rating");
        break;
        case "sorting_manage_review_published":
            manage_review_s($option, "published");
        break;
            //***************   end for manage reviews   *************************

        case "config_save":
            configure_save($option);
        break;
        case "lend":
            if (JRequest::getVar('save') == 1) {
                saveLend($option, $bid);
            } else {
                lend($option, $bid);
            }
        break;
        case "lend_requests":
            lend_requests($option, $bid);
        break;
        case "accept_lend_requests":
            accept_lend_requests($option, $bid);
        break;
        case "decline_lend_requests":
            decline_lend_requests($option, $bid);
        break;
        case "about":
            HTML_medialibrary::about();
        break;
        case "show_info":
            showInfo($option, $bid);
        break;
        case "lend_return":
            if (JRequest::getVar('save') == 1) {
                saveLend_return($option, $bid);
            } else {
                lend_return($option, $bid);
            }
        break;
        case "delete_review":
            $ids = explode(',', $bid[0]);
            delete_review($option, $ids[1]);
            editMedia($option, $ids[0], $media_type);
        break;
        case "edit_review":
            $ids = explode(',', $bid[0]);
            edit_review($option, $ids[1], $ids[0]);
        break;
        case "update_review":
            $title = JRequest::getVar('title');
            $comment = JRequest::getVar('comment');
            $rating = JRequest::getVar('rating');
            $book_id = JRequest::getVar('book_id');
            $review_id = JRequest::getVar('review_id');
            update_review($title, $comment, $rating, $review_id);
            editMedia($option, $book_id, $media_type);
        break;
        case "cancel_review_edit":
            $book_id = JRequest::getVar('book_id');
            editMedia($option, $book_id, $media_type);
        break;
            //******   begin add for button print in Manager Books   ***********

        case "print_medias":
            print_medias($option);
            showMedias($option);
        break;
        case "print_item":
            print_item($option);
        break;

        case "clone_media":
            $media_type = (JRequest::getVar('media_type',''))? JRequest::getVar('media_type') : 'book';
            cloneMedia($option, $bid[0], $media_type);
            break;
            //******   end add for button print in Manager Books   *************
        case "manage_author":
            manageAuthor($option);
            break;
        case "delete_author":
            deleteAuthor($option);
            break;
        case "publish_author":
        case "unpublish_author"://print_r($_REQUEST);exit;
            publishAuthor($bid[0], $task, $option);
        break;
        case "apply_author":
        case "save_author":
            saveAuthor($option, $task);
        break;

        case "clone_author":
            cloneAuthor($option, $bid[0]);
            break;

        case "edit_author":
        case "add_author":
            editAuthor($bid[0], $option);
            break;
        default:
            showMedias($option);
        break;
    }
} //else
class CAT_Utils {
    static function categoryArray() {
        global $database;
        // get a list of the menu items
        $query = "SELECT c.*, c.parent_id AS parent" .
          "\n FROM #__medialibrary_main_categories c" .
         "\n WHERE section='com_medialibrary'" .
         "\n AND published <> -2" .
         "\n ORDER BY ordering";
        $database->setQuery($query);
        $items = $database->loadObjectList();
        if ($items == null) 
            echo "<strong style='color:red' > Please create categories for Media Library first!</strong>";
        // establish the hierarchy of the menu
        $children = array();
        // first pass - collect children
        foreach($items as $v) {
            $pt = $v->parent;
            @$list = $children[$pt] ? $children[$pt] : array();
            array_push($list, $v);
            $children[$pt] = $list;
        }
        // second pass - get an indent list of the items
        $array = mediaLibraryTreeRecurse(0, '', array(), $children); //for 1.6
        return $array;

    }
}
/**
 * HTML Class
 * Utility class for all HTML drawing classes
 * @desc class General HTML creation class. We use it for back/front ends.
 */
class HTML {
    // TODO :: merge categoryList and categoryParentList
    // add filter option ?
    function categoryList($id, $action, $options = array()) {
        $list = CAT_Utils::categoryArray();
        // assemble menu items to the array
        foreach($list as $item) {
            $options[] = mosHTML::makeOption($item->id, $item->treename);
        }
        $parent = mosHTML::selectList($options, 'catid',
         'id="catid" class="inputbox" size="1" onchange="' . $action . '"', 'value', 'text', $id);
        return $parent;
    }
    static function categoryParentList($id, $action, $is_new, $options = array()) {
        global $database;
        $list = CAT_Utils::categoryArray();
        $cat = new mainMedialibraryCategories($database); //for 1.6
        $cat->load($id);
        $this_treename = '';
        $childs_ids = Array();
        foreach($list as $item) {
            if ($item->id == $cat->id || 
                array_key_exists($item->parent_id, $childs_ids)) $childs_ids[$item->id] = $item->id;
        }
        foreach($list as $item) {
            if ($this_treename) {
                if ($item->id != $cat->id && strpos($item->treename, $this_treename) ===
                 false && array_key_exists($item->id, $childs_ids) === false) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                }
            } else {
                if ($item->id != $cat->id) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                } else {
                    $this_treename = "$item->treename/";
                }
            }
        }
        $parent = null;
        $parent = mosHTML::selectList($options, 'parent_id', 'class="inputbox" size="1"',
         'value', 'text', $cat->parent_id);
        return $parent;
    }
    static function imageList($name, &$active, $javascript = null, $directory = null) {
        global $mosConfig_absolute_path;
        if (!$javascript) {
            $javascript = "onchange=\"javascript:if (document.adminForm." . $name .
             ".options[selectedIndex].value!='') {document.imagelib.src='../images/stories/'+document.adminForm."
             .$name.".options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
        }
        if (!$directory) {
            $directory = '/images/stories';
        }
        // inserted by Wonderer
        if (!file_exists($mosConfig_absolute_path . $directory)) {
            @mkdir($mosConfig_absolute_path . $directory, 0777) or die("Error of directory creating: [" .
             $mosConfig_absolute_path . $directory . "] ");
        } else {
        }
        // --
        $imageFiles = mosReadDirectory($mosConfig_absolute_path . $directory);
        $images = array(mosHTML::makeOption('', _MEDIALIBRARY_A_SELECT_IMAGE));
        foreach($imageFiles as $file) {
            if (preg_match("/bmp|gif|jpeg|jpg|png/i", $file)) {
                $images[] = mosHTML::makeOption($file);
            }
        }
        $images = mosHTML::selectList($images, $name, 'id="' . $name .
         '" class="inputbox" size="1" ' . $javascript, 'value', 'text', $active);
        return $images;
    }
}
/////////////////////////////ST5///////////


function userLendHistory($option, $sorting) {

    global $database, $my, $mainframe;
    //$userId = protectInjectionWithoutQuote('userId', '-1');
    $userId = $mainframe->getUserStateFromRequest("userId{$option}", 'userId', '-1');
   
    if ($userId == NULL) {
        $userId = '-1';
    } 

    $userIdint = (int) $userId;
    
    if ($sorting == '') {
        $sorting = 'title';
    }

    if ($userIdint == 0) {

        $selectstring = "SELECT library.id, library.media_type, library.media_id," .
     "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
     " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
     " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
     " l.user_email AS user_email, l.fk_userid as fk_userid, l.user_mailing as user_mailing, " .
     " other_table.id as media_type_id,  other_table.title as title  " .

     " FROM #__medialibrary AS library " .

     " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
     " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
     " LEFT JOIN #__medialibrary_lend AS l ON l.fk_mediaid = library.id" .
     " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
     " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .

     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" . " WHERE l.user_name = " .$database->Quote($userId) . " ".

     " ORDER BY ".$sorting." ";

    }

    elseif($userIdint ==  -1 ){

        $selectstring = "SELECT library.id, library.media_type, library.media_id," .
     "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
     " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
     " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
     " l.user_email AS user_email, l.fk_userid as fk_userid , l.user_mailing as user_mailing, " .
     " other_table.id as media_type_id,  other_table.title as title  " .

     " FROM #__medialibrary AS library " .

     " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
     " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
     " LEFT JOIN #__medialibrary_lend AS l ON l.fk_mediaid = library.id" .
     " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
     " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .

     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" . 
     " ORDER BY ".$sorting." ";
   
          
 } else {
    
        $selectstring = "SELECT library.id, library.media_type, library.media_id," .
     "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
     " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
     " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
     " l.user_email AS user_email, l.fk_userid as fk_userid, l.user_mailing as user_mailing, " .
     " other_table.id as media_type_id,  other_table.title as title  " .

     " FROM #__medialibrary AS library " .

     " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
     " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
     " LEFT JOIN #__medialibrary_lend AS l ON l.fk_mediaid = library.id" .
     " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
     " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .

     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" . " WHERE l.fk_userid = " .$database->Quote($userIdint) . "  
       OR l.user_name = " .$database->Quote($userId) . " ".
     " ORDER BY ".$sorting." ";
 }    
     
    $database->setQuery($selectstring);
    
    if (!$database->query()) {

        echo "<script> alert('" . addslashes($database->getError()) . "'); window.history.go(-1); </script>\n";
        exit();
    }

    $medias = $database->loadObjectList();
    
    for ($i = 0; $i < count($medias); $i++) {
        $fromcut = explode(' ', $medias[$i]->lend_from);
        $untilcut = explode(' ', $medias[$i]->lend_until);
        $medias[$i]->lend_from = $fromcut[0];  
        $medias[$i]->lend_until = $untilcut[0]; 
    }

    // get list of categories
    $userlist[] = mosHTML::makeOption('-1', _MEDIALIBRARY_ADMIN_PLEASE_SEL);

    //$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
    $database->setQuery("SELECT DISTINCT fk_userid AS value, user_name AS text 
                         from #__medialibrary_lend 
                         ORDER BY user_name");
    $userlist = array_merge($userlist, $database->loadObjectList());
    foreach ($userlist as $value) {
        if(!$value->value)
            $value->value = $value->text;
    } 
    $usermenu = mosHTML::selectList($userlist, 'userId', 'onchange="document.adminForm.submit();" class="inputbox" size="1"', 'value', 'text', $userId);
    HTML_medialibrary::userLendHistory($option,$medias,@$medias_assoc,$usermenu,"lend");

}




function showCategories() {

    global $database, $my, $option, $menutype, $mainframe, $mosConfig_list_limit, $acl;
    $grooups = get_group_children_ml();
    $section = "com_medialibrary";
    $sectionid = $mainframe->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
    $limitstart = $mainframe->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $mainframe->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);
    $query = "SELECT COUNT(DISTINCT m.id) AS cc, c.*, c.checked_out as checked_out_contact_category, " .
     " c.parent_id as parent, c.params, u.name AS editor" .
     "\n FROM #__medialibrary_main_categories AS c" .
     "\n LEFT JOIN #__medialibrary_categories as mc ON mc.catid=c.id" .
     "\n LEFT JOIN #__medialibrary AS m ON m.id=mc.mediaid AND m.published=1 AND m.approved=1".
     "\n LEFT JOIN #__users AS u ON u.id = c.checked_out" .
     "\n WHERE c.section='$section'"
       //. "\n AND c.published = 1" //To display all categories
     . "\n GROUP BY c.id "
     ."\n ORDER BY parent_id DESC, c.ordering";



     //Выборка для отображения Categories
    $database->setQuery($query);
    $rows = $database->loadObjectList();





    //print_r($rows);exit;


    foreach($rows as $k => $v) {
        $rows[$k]->ncourses = 0;
        foreach($rows as $k1 => $v1) {
            if ($v->id == $v1->parent) $rows[$k]->cc+= $v1->cc;
        }
        ($rows[$k]->cc == 0) ? "-" : "<a href=\"?option=com_medialibrary&section=media&catid=" .
         $v->id . "\">" . ($v->cc) . "</a>"; //for 1.6
        $curgroup = array();
        $ss = explode(',', $v->params);
        foreach($ss as $s) {
            if ($s == '') $s = '-2';
            $curgroup[] = $grooups[$s];
        }
        $rows[$k]->groups = implode(', ', $curgroup);
    }
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    }
    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $list = mediaLibraryTreeRecurse(0, '', array(), $children, max(0, $levellimit - 1));
    $total = count($list);
    $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
    $levellist = mosHTML::integerSelectList(1, 20, 1, 'levellimit',
     'size="1" onchange="document.adminForm.submit();"', $levellimit);
    // slice out elements based on limits
    $list = array_slice($list, $pageNav->limitstart, $pageNav->limit);
    $count = count($list);
    // get list of sections for dropdown filter
    $javascript = 'onchange="document.adminForm.submit();"';
    if (version_compare(JVERSION, "3.0.0", "lt")) $lists['sectionid'] =
     mosAdminMenus::SelectSection('sectionid', $sectionid, $javascript);
    HTML_Categories::show($list, $my->id, $pageNav, 'other');
}

function editCategory($section = '', $uid = 0) {
    global $database, $my, $acl;
    global $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
    $type = mosGetParam($_REQUEST, 'type', '');
    $redirect = mosGetParam($_POST, 'section', '');
    $row = new mainMedialibraryCategories($database); //for 1.6
    // load the row from the db table
    $row->load($uid);
    // fail if checked out not by 'me'
    if ($row->checked_out && $row->checked_out <> $my->id) {
        mosRedirect('index.php?option=com_medialibrary&task=categories',
        'The category ' . $row->title . ' is currently being edited by another administrator');
    }
    $is_new = false;



    if ($uid) {
        // existing record
        $row->checkout($my->id);
        // code for Link Menu

    } else {
        // new record
        $is_new = true;
        $row->section = $section;
        $row->published = 1;
    }


    function createAssociateArray($row, $database) {
    $associateArray = array();
    if ($row->id) {
        $query = "SELECT lang_code FROM `#__languages` WHERE 1";
        $database->setQuery($query);
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $allLanguages = array();
            $lang = JFactory::getLanguage();
            foreach($lang->getLocale()  as  $locale) {
                if (mb_strlen($locale) == 5 && $locale[2] == '_'){
                    $locale[2] = '-';
                    $allLanguages[] =  $locale;
                }
            }
        } else {
            $allLanguages = $database->loadColumn();
        }
        $query = "SELECT id,langDescription,title FROM `#__medialibrary_main_categories` WHERE 1";
        $database->setQuery($query);
        $allInCategories = $database->loadObjectlist();

        $query = "select associate_category from `#__medialibrary_main_categories` where id =" . $row->id;
        $database->setQuery($query);
        $categoryAssociateCategory = $database->loadResult();

        if(!empty($categoryAssociateCategory)) {
              $categoryAssociateCategory = unserialize($categoryAssociateCategory);
          } else {
              $categoryAssociateCategory = array();
          }

        foreach($allLanguages as & $oneLang) {
            $associate_category = array();
            $associate_category[] = mosHtml::makeOption(0, 'select');
            $i = 0;
            foreach($allInCategories as & $oneCat) {
                if ($oneLang == $oneCat->langDescription && $oneCat->id != $row->id) {
                    $associate_category[] = mosHtml::makeOption(($oneCat->id), $oneCat->title);
                }
            }
            if (isset($row->langDescription) &&$row->langDescription != $oneLang) {
                $associate_category_list = mosHTML::selectList($associate_category,
                'language_associate_category', 'class="inputbox edit_cat_select" size="1"', 'value', 'text', "");
            } else {
                $associate_category_list = null;
            }

            $associateArray[$oneLang]['list'] = $associate_category_list;
            if (isset($categoryAssociateCategory[$oneLang])) {
                $associateArray[$oneLang]['assocId'] = $categoryAssociateCategory[$oneLang];
            } else {
                $associateArray[$oneLang]['assocId'] = 0;
            }
        }
    }
    return $associateArray;
}

    $associateArray = createAssociateArray($row, $database);

    // make order list
    $order = array();
    $database->setQuery("SELECT COUNT(*) FROM #__medialibrary_main_categories WHERE section='$row->section'");
    $max = intval($database->loadResult()) + 1;
    for ($i = 1;$i < $max;$i++) {
        $order[] = mosHTML::makeOption($i);
    }
    // build the html select list for ordering
    $query = "SELECT ordering AS value, title AS text" .
     "\n FROM #__medialibrary_main_categories" .
     "\n WHERE section = '$row->section'" .
     "\n ORDER BY ordering";
    //$lists['ordering'] = mosAdminMenus::SpecificOrdering($row, $uid, $query);

    $lists['ordering'] = '';

    // build the select list for the image positions
    $active = ($row->image_position ? $row->image_position : 'left');
    //$lists['image_position'] = mosAdminMenus::Positions('image_position', $active, null, 0, 0);
    $lists['image_position'] = version_compare(JVERSION, '3.0', 'ge') ? NUll :
     mosAdminMenus::Positions('image_position', $active, null, 0, 0);
    // Imagelist
    $lists['image'] = HTML::imageList('image', $row->image);
    // build the html radio buttons for published
    $lists['published'] = mosHTML::yesnoRadioList('published', 'class="inputbox"', $row->published);
    // build the html select list for paraent item
    $options = array();
    $options[] = mosHTML::makeOption('0', _MEDIALIBRARY_A_SELECT_TOP);
    $lists['parent'] = HTML::categoryParentList($row->id, "", "", $options);

    if (!isset($row->params2)) $row->params2 = '';
    $params2 = unserialize($row->params2);
    if (empty($params2)) {
        $params2 = new stdClass();
        $params2->alonecategory = '';
        $params2->view_type_display_book = '';
        $params2->view_type_display_video = '';
        $params2->view_type_display_music = '';
        $params2->view_type_display_game = '';
    }
    $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/alonecategory/tmpl');
    $component_layouts = array();
    $options = array();
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, 
            '^[^_]*\.php$', false, true))) {
        $alonecategory[] = JHtml::_('select.option', '', 'Use Global');
        foreach($component_layouts as $i => $file) {
            $select_file_name = pathinfo($file);
            $select_file_name = $select_file_name['filename'];
            $alonecategory[] = JHtml::_('select.option', $select_file_name, $select_file_name);
        }
    }
    $lists['alonecategory'] = mosHTML::selectList($alonecategory, 'alonecategory',
     'size="1" ', 'value', 'text', $params2->alonecategory);
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, 
            '^[^_]*\.php$', false, true))) {


      
      if (version_compare(JVERSION, "1.6.0", "lt")) {
        $allLanguages = array();
        $lang = JFactory::getLanguage();
        foreach($lang->getLocale()  as  $locale) {
            if (mb_strlen($locale) == 5 && $locale[2] == '_'){
                $locale[2] = '-';
                $query = "SELECT title FROM #__medialibrary_languages 
                          WHERE lang_code = '$locale'";
                $database->setQuery($query);
                $language_title = $database->loadResult();
                $language = new ArrayObject;
                $language->lang_code = $locale;
                $language->title = $language_title;
                $languages[] = $language;
            }
        }
      } else {
        $query = "SELECT lang_code, title FROM #__languages";
        $database->setQuery($query);
        $languages = $database->loadObjectList();

      }
      $languages_row[] = mosHTML::makeOption('*', 'All');

      foreach($languages as $language) {
          $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
      }
    }
    if (!isset($row->langDescription)) $row->langDescription = '*';
    $langshow = mosHTML::selectList($languages_row, 'langDescription',
     'class="inputbox" size="1"', 'value', 'text', $row->langDescription);

    //added anoxi
    //var_dump($params2);die();
    $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/displaybook/tmpl');
    $component_layouts = array();
    $options = array();
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path,
     '^[^_]*\.php$', false, true))) {
        $view_type_display_book[] = JHtml::_('select.option', '', 'Use Global');
        foreach($component_layouts as $i => $file) {
            $select_file_name = pathinfo($file);
            $select_file_name = $select_file_name['filename'];
            $view_type_display_book[] = JHtml::_('select.option', $select_file_name, $select_file_name);
        }
    }
    $lists['view_type_display_book'] = mosHTML::selectList($view_type_display_book,
     'view_type_display_book', 'size="1" ', 'value', 'text', $params2->view_type_display_book);
    $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/displayvideo/tmpl');
    $component_layouts = array();
    $options = array();
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, 
            '^[^_]*\.php$', false, true))) {
        $view_type_display_video[] = JHtml::_('select.option', '', 'Use Global');
        foreach($component_layouts as $i => $file) {
            $select_file_name = pathinfo($file);
            $select_file_name = $select_file_name['filename'];
            $view_type_display_video[] = JHtml::_('select.option', $select_file_name, $select_file_name);
        }
    }
    $lists['view_type_display_video'] = mosHTML::selectList($view_type_display_video,
     'view_type_display_video', 'size="1" ', 'value', 'text', $params2->view_type_display_video);
    $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/displaymusic/tmpl');
    $component_layouts = array();
    $options = array();
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path,
     '^[^_]*\.php$', false, true))) {
        $view_type_display_music[] = JHtml::_('select.option', '', 'Use Global');
        foreach($component_layouts as $i => $file) {
            $select_file_name = pathinfo($file);
            $select_file_name = $select_file_name['filename'];
            $view_type_display_music[] = JHtml::_('select.option', $select_file_name, $select_file_name);
        }
    }
    $lists['view_type_display_music'] = mosHTML::selectList($view_type_display_music,
     'view_type_display_music', 'size="1" ', 'value', 'text', $params2->view_type_display_music);
    $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/displaygame/tmpl');
    $component_layouts = array();
    $options = array();
    if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path,
     '^[^_]*\.php$', false, true))) {
        $view_type_display_game[] = JHtml::_('select.option', '', 'Use Global');
        foreach($component_layouts as $i => $file) {
            $select_file_name = pathinfo($file);
            $select_file_name = $select_file_name['filename'];
            $view_type_display_game[] = JHtml::_('select.option', $select_file_name, $select_file_name);
        }
    }
    $lists['view_type_display_game'] = mosHTML::selectList($view_type_display_game,
     'view_type_display_game', 'size="1" ', 'value', 'text', $params2->view_type_display_game);
    //end added anoxi
    HTML_Categories::edit($row, $section, $lists, $redirect, $langshow, $associateArray);
}

function saveCategory() {
    global $database;
    $row = new mainMedialibraryCategories($database); //for 1.6
    $post = JRequest::get('post', JREQUEST_ALLOWHTML);

    function saveAssociateMediaCat($post,$database) {
      $currentId = $post['id'];
      if ($currentId) {
          $i = 1;
          $assocArray = array();
          $assocCategoryId = array();

          while(isset($post['associate_category' . $i])) {
              $langAssoc = $post['associate_category_lang' . $i];
              $valAssoc = $post['associate_category' . $i];
              $assocArray[$langAssoc] = $valAssoc;
              if ($valAssoc) {
                  $assocCategoryId[] = $valAssoc;
              }
              $i++;
          }
          $currentId = $post['id'];
          $currentLang = $post['langDescription'];
          $assocArray[$currentLang] = $currentId;
          $assocStr = serialize($assocArray);
          $query = "select `associate_category` from `#__medialibrary_main_categories` where `id` = " 
            . $currentId . "";
          $database->setQuery($query);
          $oldAssociate = $database->loadResult();
          $oldAssociateArray = unserialize($oldAssociate);
          if ($oldAssociateArray) {
              foreach($oldAssociateArray as $key => $value) {
                  if ($value && !isset($assocCategoryId[$value])) {
                      $assocCategoryId[] = $value;
                  }
              }
          }
          if (!isset($assocCategoryId[$currentId])) {
              $assocCategoryId[] = $currentId;
          }
          $idToChange = implode(',', $assocCategoryId);
          if (count($idToChange) && !empty($idToChange)) {
              $query = "UPDATE #__medialibrary_main_categories SET `associate_category`='" . $assocStr 
                . "' where `id` in ("  
                     . $idToChange . ")";
              $database->setQuery($query);
              $database->query();
          }
      }
  }
    saveAssociateMediaCat($post, $database);

    $params2 = new stdClass();
    $params2->alonecategory = $post['alonecategory'];
    $params2->view_type_display_book = $post['view_type_display_book'];
    $params2->view_type_display_video = $post['view_type_display_video'];
    $params2->view_type_display_music = $post['view_type_display_music'];
    $params2->view_type_display_game = $post['view_type_display_game'];
    $post['params2'] = serialize($params2);
    //var_dump($post['params2']);die();
    if ($_REQUEST['title'] == "") {
        echo "<script> alert('" . 'Please, insert Alias' . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$row->bind($post)) {
        echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
        exit();
    }
    $row->section = 'com_medialibrary';
    $row->parent_id = $_REQUEST['parent_id'];
    if (!$row->check()) {
        echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
        exit();
    }
    //****set access level
    $row->params = implode(',', JRequest::getVar('category_registrationlevel', ''));
    if ($row->params == "") $row->params = "-2";
    //****end set access level
    if (!$row->store()) {
        echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
        exit();
    }
    //exit();
    $row->checkin();
    $row->updateOrder("section='com_medialibrary' AND parent_id='$row->parent_id'");

    mosRedirect('index.php?option=com_medialibrary&section=categories');
}



//this function check - is exist books in this folder and folders under this category
function is_exist_curr_and_subcategory_books($catid) {
    global $database, $my;
    $query = "SELECT *, COUNT(a.id) AS numlinks FROM #__medialibrary_main_categories AS cc" .
     "\n JOIN #__medialibrary_categories AS a ON a.catid = cc.id" .
     "\n WHERE section='com_medialibrary' AND cc.id='$catid' " .
     "\n GROUP BY cc.id" .
     "\n ORDER BY cc.ordering";
    $database->setQuery($query);
    $categories = $database->loadObjectList();
    if (count($categories) != 0) return true;
    $query = "SELECT id " . "FROM #__medialibrary_main_categories AS cc " .
     " WHERE section='com_medialibrary' AND parent_id='$catid' ";
    $database->setQuery($query);
    $categories = $database->loadObjectList();
    if (count($categories) == 0) return false;
    foreach($categories as $k) {
        if (is_exist_curr_and_subcategory_books($k->id)) return true;
    }
    return false;
} //end function


function randNumber() {
    if (isset($_GET["path"])){
        $path = $_GET["path"];
        $filename = basename($_GET["file"]);
        $file = $path . $filename;
        if (file_exists($file)) {
            echo "The file with such name already is!";
        } else {
            echo "";
        }
    }
}


//bch delete category--->


function removeCategoriesFromDB($cid) {
    global $database, $my;
    //
    //    $query = "SELECT id, FROM #__medialibrary_main_categories AS cc  WHERE section='com_medialibrary' 
    //    AND parent_id='$cid' ";
    //
    //                   $database->setQuery( $query );
    //    $categories = $database->loadObjectList();
    //
    //        if ($database->getErrorNum()) {
    //    echo $database->stderr();
    //  }
    //
    //    if( count($categories) != 0 ) {
    //        //delete child
    //        foreach($categories as $k) {
    //            removeCategoriesFromDB($k->id) ;
    //        }
    //    }
    $sql = "DELETE FROM #__medialibrary_main_categories WHERE id = $cid ";
    $database->setQuery($sql);
    if (version_compare(JVERSION, "3.0.0", "lt")) {
        $database->query();
    } else {
        $database->execute();
    }
}
/**
 * Deletes one or more categories from the categories table
 *
 * @param string $ The name of the category section
 * @param array $ An array of unique category id numbers
 */

function removeCategories($section, $cid) {

    global $database;


    //print_r($cid);

    if (count($cid) < 1) {
        echo "<script> alert('Select a category to delete'); window.history.go(-1);</script>\n";
        exit;
    }

    foreach($cid as $catid) {
        
       
        if (is_exist_curr_and_subcategory_books($catid)) {

            echo "<script> alert('Some category from yours select contain media. Please remove media first!')</script>";
            echo "<script> window.history.go(-1) </script>";

            exit;
        }
    }



    foreach($cid as $catid) {
        removeCategoriesFromDB($catid);
    }
    $msg = (count($err) > 1 ? "Categories " : _CATEGORIES_NAME . " ") . _DELETED;
    mosRedirect('index.php?option=com_medialibrary&section=categories&mosmsg=' . $msg);
}
/**
 * Publishes or Unpublishes one or more categories
 *
 * @param string $ The name of the category section
 * @param integer $ A unique category id (passed from an edit form)
 * @param array $ An array of unique category id numbers
 * @param integer $ 0 if unpublishing, 1 if publishing
 * @param string $ The name of the current user
 */


function publishCategories($section, $categoryid = null, $cid = null, $publish = 1) {
    global $database, $my;


    if (!is_array($cid)) {
        $cid = array();
    }
    if ($categoryid) {
        $cid[] = $categoryid;
    }
    if (count($cid) < 1) {
        $action = $publish ? _PUBLISH : _DML_UNPUBLISH;
        echo "<script> alert('" . _DML_SELECTCATTO . " $action'); window.history.go(-1);</script>\n";
        exit;
    }
    $cids = implode(',', $cid);
    $query = "UPDATE #__medialibrary_main_categories SET published='$publish'" .
     "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))";
    $database->setQuery($query);
    if (!$database->query()) {
        echo "<script> alert('" . addslashes($database->stderr()) . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if (count($cid) == 1) {
        $row = new mainMedialibraryCategories($database); //for 1.6
        $row->checkin($cid[0]);
    }
    mosRedirect('index.php?option=com_medialibrary&section=categories');
}
/**
 * Cancels an edit operation
 *
 * @param string $ The name of the category section
 * @param integer $ A unique category id
 */
function cancelCategory() {
    global $database;
    $row = new mainMedialibraryCategories($database); //for 1.6
    $row->bind($_POST);
    $row->checkin();
    mosRedirect('index.php?option=com_medialibrary&section=categories');
}
/**
 * Moves the order of a record
 *
 * @param integer $ The increment to reorder by
 */
function orderCategory($uid, $inc) {
    global $database;
    $row = new mainMedialibraryCategories($database); //for 1.6
    $row->load($uid);
    if ($row->ordering == 1 && $inc == - 1) mosRedirect('index.php?option=com_medialibrary&section=categories');
    $new_order = $row->ordering + $inc;
    //change ordering - for other element
    $query = "UPDATE #__medialibrary_main_categories SET ordering='" . ($row->ordering) .
     "'" . "\nWHERE parent_id = $row->parent_id and ordering=$new_order";
    $database->setQuery($query);
    $database->query();
    //change ordering - for this element
    $query = "UPDATE #__medialibrary_main_categories SET ordering='" . $new_order . "'" . "\nWHERE id = $uid";
    $database->setQuery($query);
    $database->query();
    mosRedirect('index.php?option=com_medialibrary&section=categories');
}


function update_review($title, $comment, $rating, $review_id) {
    global $database;
    $review = new mosMediaLibrary_review($database);
    $review->load($review_id);
    if (!$review->bind($_POST)) {
        echo "<script> alert('" . $review->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$review->check()) {
        echo "<script> alert('" . $review->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$review->store()) {
        echo "<script> alert('" . $review->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
}
function edit_review($option, $review_id, $book_id) {
    global $database;
    $database->setQuery("SELECT * FROM #__medialibrary_review WHERE id=" . $review_id . " ");
    $review = $database->loadObjectList();
    if ($database->getErrorNum()) {
        echo $database->stderr();
    }
    HTML_medialibrary::edit_review($option, $book_id, $review);
}
/*
* Function for delete coment
* (comment for every book)
* in database.
*/
function delete_review($option, $id) {
    global $database;
    //delete review where id =.. ;
    $database->setQuery("DELETE FROM #__medialibrary_review WHERE  id=" . $id . ";");
    $database->query();
    if ($database->getErrorNum()) {
        echo $database->stderr();
    }
}
//*******************   begin for manage reviews   ****************************
function delete_manage_review($option, $id) {
    global $database;
    for ($i = 0;$i < count($id);$i++) {
        $id_del = explode(',', $id[$i]);
        $database->setQuery("DELETE FROM #__medialibrary_review WHERE #__medialibrary_review.id='".$id_del[0]."';");
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
        }
    }
}
function edit_manage_review($option, $review_id) {
    global $database;
    if (count($review_id) > 1) {
        echo "<script> alert('Please select one review for edit!!!'); window.history.go(-1); </script>\n";
    } else {


            $countInfo = count ($review_id);
        for ($i = 0; $i < $countInfo; $i++) {
                $bids[$i] = explode(',', $review_id[$i]);
                $id = $bids[$i][0];
        }

        $database->setQuery("SELECT * FROM #__medialibrary_review WHERE id=" .$id . " ");
        $review = $database->loadObjectList();
        if ($database->getErrorNum()) {
            echo $database->stderr();
        }
        HTML_medialibrary::edit_manage_review($option, $review);
    }
}
//*****************   end for manage reviews   *****************************
function showInfo($option, $bid) {
    if (is_array($bid) && count($bid) > 0) {
        $bid = $bid[0];
    }
    echo "Test: " . $bid;
}
function decline_lend_requests($option, $bids) {
    global $database, $medialibrary_configuration;
    $datas = array();
    foreach($bids as $bid) {
        $lend_request = new mosMediaLibrary_lend_request($database);
        $lend_request->load($bid);
        $tmp = $lend_request->decline();
        if ($tmp != null) {
            echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        foreach($datas as $c => $data) {
            if ($lend_request->user_email == $data['email']) {
                $datas[$c]['ids'][] = $lend_request->fk_mediaid;
                continue2;
            }
        }
        $datas[] = array('email' => $lend_request->user_email,
         'name' => $lend_request->user_name, 'ids' => array($lend_request->fk_mediaid));
    }


    mosRedirect("index.php?option=$option&task=lend_requests");
}
function accept_lend_requests($option, $bids) {
    global $database, $medialibrary_configuration;
    $datas = array();
    foreach($bids as $bid) {
        $lend_request = new mosMediaLibrary_lend_request($database);
        $lend_request->load($bid);
        $tmp = $lend_request->accept();
        if ($tmp != null) {
            echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        foreach($datas as $c => $data) {
            if ($lend_request->user_email == $data['email']) {
                $datas[$c]['ids'][] = $lend_request->fk_mediaid;
                continue2;
            }
        }
        $datas[] = array('email' => $lend_request->user_email, 'name' => $lend_request->user_name,   
                    'ids' => array($lend_request->fk_mediaid));
    }

    mosRedirect("index.php?option=" . $option . "&task=lend_requests");
}


function lend_requests($option, $bid) {
    global $database, $mainframe, $mosConfig_list_limit;
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
    $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    $database->setQuery(" SELECT count(*) FROM #__medialibrary AS a" .
                        " LEFT JOIN #__medialibrary_lend_request AS l" .
                        " ON l.fk_mediaid = a.id" .
                        " WHERE l.status = 0");
    $total = $database->loadResult();
    if ($database->getErrorNum()) {
        echo $database->stderr();
    }

    $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
    $selectstring = "SELECT l.id, library.media_type, library.media_id," .
     "cc.title AS category, mc.catid, "." l.id as lendid, l.fk_mediaid as fk_media_id, l.lend_from as lend_from, ".
     " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
     " l.lend_until as lend_until, l.user_name as user_name ," .
     " l.user_email as user_email, l.user_mailing as user_mailing ," .
     " other_table.id as media_type_id,  other_table.title as title  " .
     " FROM #__medialibrary_lend_request AS l, #__medialibrary AS library " .
     " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
     " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
     " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
     " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
     " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
     " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
     " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
     "  WHERE l.status = 0 and l.fk_mediaid = library.id " .
     " ORDER BY l.lend_from, l.lend_until, l.user_name " .
     " LIMIT $pageNav->limitstart,$pageNav->limit;";



    $database->setQuery($selectstring);
    $lend_requests = $database->loadObjectList();

    if ($database->getErrorNum()) {
        echo $database->stderr();
    }
    HTML_medialibrary::showRequestLendMedias($option, $lend_requests, $pageNav);
}

// ------------------------- by Wonderer
function unsetCatId() {
    $option = 'com_medialibrary';
    $mainframe = JFactory::getApplication();
    $catid = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', '-1');
    unset($catid);
    showBooks($option);
}
/**
 * Compiles a list of records
 * @param database - A database connector object
 * select categories
 */

function showMedias($option) {
    $mainframe = JFactory::getApplication();
    global $database, $mosConfig_list_limit;
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
    $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    $catid = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', '-1'); //old 0
    $lend = $mainframe->getUserStateFromRequest("lend{$option}", 'lend', '-1');
    $owner = $mainframe->getUserStateFromRequest("owner{$option}", 'owner', '-1');
    $pub = $mainframe->getUserStateFromRequest("pub{$option}", 'pub', '-1');
    $app = $mainframe->getUserStateFromRequest("app{$option}", 'app', '-1');
    $type = $mainframe->getUserStateFromRequest("type{$option}", 'type', '-1');
    $srch_for = $mainframe->getUserStateFromRequest("srch_for{$option}", 'srch_for', '0');
    $sequence = $mainframe->getUserStateFromRequest("sequence{$option}", 'sequence', '0');
    $search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
    $select_owner_id = protectInjectionWithoutQuote('select_owner_id',-1) ;
    //var_dump($search); exit();
    //$search = $database->getEscaped(trim(strtolower($search)));
    $where = array();
    if ($select_owner_id !== "-1" && $select_owner_id !== "0") {
        array_push($where, "library.owner_ID = '" . $select_owner_id . "' ");
    }
    if (version_compare(JVERSION, "3.0.0", "lt")) {
        $search = $database->getEscaped(trim(strtolower($search)));
    } else {
        $search = $database->escape(trim(strtolower($search)));
    }
    if ($lend == "lend") {
        array_push($where, "library.fk_lendid <> 0");
    } else if ($lend == "not_lend") {
        array_push($where, "library.fk_lendid = 0");
    }
    if ($pub == "pub") {
        array_push($where, "library.published = 1");
    } else if ($pub == "not_pub") {
        array_push($where, "library.published = 0");
    }
    if ($app == "app") {
        array_push($where, "library.approved = 1");
    } else if ($app == "not_app") {
        array_push($where, "library.approved = 0");
    }
    if ($type == "-1" || $type == "0 ") {;
    } else {
        array_push($where, "library.media_type = '$type' ");
    }
    if ($owner != - 1) array_push($where, "library.owneremail = '$owner'");
    if ($catid > 0) {
        array_push($where, "mc.catid='$catid'");
    }
    $Order = " ";

    if ($sequence == "Title all ascending") {
        $Order = " order by other_table.title ";
    } else if ($sequence == "Title all descending") {
        $Order = " order by other_table.title DESC  ";
    } else if ($sequence == "Music artists ascending") {
        $Order = " order by p.people_name ";
         array_push($where," other_table.type = 'music' ");
    } else if ($sequence == "Music  artists descending") {
        $Order = " ORDER by p.people_name DESC";
         array_push($where, "  other_table.type = 'music' ");
    } else if ($sequence == "Book authors ascending") {
        $Order = " ORDER by p.people_name ";
         array_push($where, "  other_table.type = 'book' ");
    } else if ($sequence == "Book  authors descending") {
        $Order = " ORDER by p.people_name DESC ";
         array_push($where, "  other_table.type = 'book' ");
    }
    $sort_let = mosGetParam($_GET, 'sortlet', '');
    $value = $sort_let;
    if ($sort_let != '' and $sort_let != 'none') {
        switch ($sort_let) {
            case 'lend_out':
                $Order = "";
            break;
            case 'lend_out_desc':
                $Order = "";
            break;
            case 'lend_until':
                $Order = "ORDER by lend_until";
            break;
            case 'lend_until_desc':
                $Order = "ORDER by lend_until DESC";
            break;
            case 'lend_from':
                $Order = "ORDER by lend_from";
            break;
            case 'lend_from_desc':
                $Order = "ORDER by lend_from DESC";
            break;
        }
        $sequence = 0;
    }
    $where_game = "";
    $where_book = "";
    $where_music = "";
    $where_video = "";
    if ($search) {
        switch ($srch_for) {
            case 'id':
                array_push($where, "LOWER(library.media_id) LIKE '%$search%'");
            break;
            case 'title':
                array_push($where, "LOWER(other_table.title) LIKE '%$search%'");
            break;
            case 'isbn':
                array_push($where, "LOWER(other_table.asin) LIKE '%$search%'");
                $where_video = " WHERE id='-1' ";
                $where_music = " WHERE id='-1' ";
                $where_game = " WHERE id='-1' ";
            break;
            case 'asin':
            array_push($where, "LOWER(other_table.asin) LIKE '%$search%'");
                $where_game = " WHERE LOWER(asin) LIKE '%$search%'";
                $where_video = " WHERE LOWER(asin) LIKE '%$search%'";
                $where_music = " WHERE LOWER(asin) LIKE '%$search%'";
                $where_book = " WHERE id='-1' ";
            break;
            case 'label':
            break;
            case 'binding':
                $where_game = "WHERE LOWER(binding) LIKE '%$search%'";
                $where_music = "WHERE LOWER(binding) LIKE '%$search%'";
                $where_book = "WHERE id='-1' ";
                $where_video = "WHERE id='-1' ";
            break;
            case 'track_listing':
                $where_music = "WHERE LOWER(tracklist) LIKE '%$search%'";
                $where_book = "WHERE id='-1' ";
                $where_video = "WHERE id='-1' ";
                $where_game = "WHERE id='-1' ";
            break;
            case 'artist':
                array_push($where, " LOWER(p.type) = 'artist' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'actors':
                array_push($where, " LOWER(p.type) = 'actor' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'authors':
                array_push($where, " LOWER(p.type) = 'author' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'publisher':
                array_push($where, " LOWER(p.type) = 'game_studio' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'description':
                array_push($where, " LOWER(other_table.comment) LIKE '%$search%' ");
            break;
            case 'producer':
                array_push($where, " LOWER(p.type) = 'producer' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'director':
                array_push($where, " LOWER(p.type) = 'director' AND LOWER(p.people_name) LIKE '%$search%' ");
            break;
            case 'studio':
                array_push($where, " ( LOWER(p.type) = 'game_studio' OR LOWER(p.type) = 'video_studio') AND LOWER(p.people_name ) LIKE '%$search%' ");
            break;
            case 'platform':
                array_push($where, " LOWER(p.type) = 'game_studio' AND LOWER(p.people_name) LIKE '%$search%' ");  
            break;
            case 'region':
                $where_video = "WHERE LOWER(region) LIKE '%$search%'";
                $where_book = "WHERE id='-1' ";
                $where_music = "WHERE id='-1' ";
                $where_game = "WHERE id='-1' ";
            break;
            case 'format':
                $where_video = "WHERE LOWER(format) LIKE '%$search%'";
                $where_book = "WHERE id='-1' ";
                $where_music = "WHERE id='-1' ";
                $where_game = "WHERE id='-1' ";
            break;
            case 'category':
                array_push($where, "LOWER(cc.title) LIKE '%$search%'");
            break;

            default:
                array_push($where, "(LOWER(other_table.title) LIKE '%$search%' OR " .
                  " LOWER(other_table.comment) LIKE '%$search%' " .
                  " OR LOWER(other_table.type) LIKE '%$search%' " .
                  " OR LOWER(library.media_type) LIKE '%$search%' " .
                  " OR LOWER(other_table.id) LIKE '%$search%' " .
                  " OR LOWER(other_table.langDescription) LIKE '%$search%' " .
                  " OR LOWER(library.id) LIKE '%$search%' " .
                  " OR LOWER(other_table.asin) LIKE '%$search%' " .
                  " OR LOWER(p.people_name) LIKE '%$search%' )" );
            break;
        }
    }

   	$selectstring = "SELECT count(DISTINCT library.id) ".
           " FROM #__medialibrary AS library " .
         " LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id  ".
         " LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id" .
         " LEFT JOIN  #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
         " LEFT JOIN #__medialibrary_main_categories AS cc on cc.id = mc.catid " .
         " LEFT JOIN #__medialibrary_lend AS l on library.id = l.fk_mediaid and l.lend_return is null  " .
         " LEFT JOIN #__users AS u on u.id = library.owner_ID ".

         " LEFT JOIN (SELECT g.id, g.asin as asin, g.title, g.langDescription, 'game' as type, g.comment " .
         " FROM #__medialibrary_game AS g ".$where_game.

         " UNION all SELECT m.id, m.asin as asin, m.title, m.langDescription, 'music' as type, m.comment " .
         " FROM #__medialibrary_music AS m  ".$where_music.

         " UNION all SELECT b.id, b.isbn, b.title, b.langDescription, 'book' as type, b.comment " .
         " FROM #__medialibrary_book AS b " .$where_book.

         " UNION all SELECT v.id, v.asin as asin, v.title, v.langDescription, 'video' as type, v.comment " .
         " FROM #__medialibrary_video AS v ".$where_video.")".

         " AS other_table ON other_table.id = library.media_id AND other_table.type = library.media_type" .
           (count($where) ? " where " . implode(' AND ', $where) : "") .
         "  ". $Order;

   //print_r($selectstring);exit;
     $database->setQuery($selectstring);
     $total = $database->loadResult();
     //print_r($total);exit;
    if ($database->getErrorNum()) {
        echo $database->stderr();
    }

    $pageNav = new JPagination($total, $limitstart, $limit);
  //  $pageNav = new JPagination(100, $limitstart, $limit);
/*   $selectstring = "SELECT GROUP_CONCAT(distinct cc.title  SEPARATOR ', ') AS category , library.*, mc.catid, ".
     " l.id as lendid, l.lend_from as lend_from, " . " l.lend_return as lend_return, " .
     " l.lend_until as lend_until ," . " u.name AS editor, " . " other_table.id as media_type_id,  
        other_table.title as title  " .
    " FROM #__medialibrary AS library" .
     " LEFT JOIN  #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
     " left join #__medialibrary_main_categories AS cc on cc.id = mc.catid " .
     " left join #__medialibrary_lend AS l on library.fk_lendid = l.id  and l.lend_return is null  " .
     " left join #__users AS u on u.id = library.owner_ID, " .
     "  ( SELECT g.id, g.title, g.langDescription, 'game' as type, g.comment, " .
     "p.people_name, p.type as people_type FROM #__medialibrary_game AS g".
     "\n LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id".
     "\n LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id". $where_game .
     " UNION all SELECT m.id, m.title, m.langDescription, 'music' as type, m.comment, " .
     " p.people_name, p.type as people_type FROM #__medialibrary_music AS m  ".
     "\n LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id".
     "\n LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id". $where_music .
     "\n UNION all SELECT b.id, b.title, b.langDescription, 'book' as type, b.comment, " .
     "\n p.people_name, p.type as people_type FROM #__medialibrary_book AS b" .
     "\n LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id".
     "\n LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id". $where_book .
      " UNION all SELECT v.id, v.title, v.langDescription, 'video' as type, v.comment, " .
      " p.people_name, p.type as people_type FROM #__medialibrary_video AS v".
      "\n LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id".
      "\n LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id". $where_video . " ) " .
      " AS other_table where other_table.id = library.media_id and other_table.type = library.media_type " .
      (count($where) ? " and " . implode(' AND ', $where) : "") . $sql_media_type.
      " GROUP BY mc.mediaid ". $Order." LIMIT $pageNav->limitstart,$pageNav->limit;";
*/
      $selectstring = "SELECT DISTINCT(library.id) as media_id, other_table.title as title, 
                     other_table.type as media_type,  
                     cc.title AS category , mc.catid, library.*, l.id as lendid, l.lend_from as lend_from, 
                     l.lend_return as lend_return,  
                     l.lend_until as lend_until , u.name AS editor, other_table.asin, other_table.langDescription ".

         " FROM #__medialibrary AS library " .
         " LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id  ".
         " LEFT JOIN #__medialibrary_people AS p ON pc.fk_people_id = p.id" .
         " LEFT JOIN  #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
         " LEFT JOIN #__medialibrary_main_categories AS cc on cc.id = mc.catid " .
         " LEFT JOIN #__medialibrary_lend AS l on library.id = l.fk_mediaid and l.lend_return is null  " .

         " LEFT JOIN #__users AS u on u.id = library.owner_ID ".

         " LEFT JOIN (SELECT g.id, g.asin as asin, g.title, g.langDescription, 'game' as type, g.comment " .
         " FROM #__medialibrary_game AS g ".$where_game.
         " UNION all SELECT m.id, m.asin as asin, m.title, m.langDescription, 'music' as type, m.comment " .
         " FROM #__medialibrary_music AS m  ".$where_music.
         "UNION all SELECT b.id, b.isbn as asin, b.title, b.langDescription, 'book' as type, b.comment " .
         " FROM #__medialibrary_book AS b " .$where_book.
         " UNION all SELECT v.id, v.asin as asin, v.title, v.langDescription, 'video' as type, v.comment " .
         " FROM #__medialibrary_video AS v ".$where_video.")".
         " AS other_table ON other_table.id = library.media_id AND other_table.type = library.media_type" .

           (count($where) ? " where " . implode(' AND ', $where) : "") .

           " ". $Order." LIMIT $pageNav->limitstart,$pageNav->limit;";

    $database->setQuery($selectstring);
    $rows = $database->loadObjectList();


//Выборка для отображения Media



    for($i=0;$i<count($rows);$i++){

        $result[$i] = "SELECT name FROM  #__users WHERE id='".$rows[$i]->checked_out."'";
        $database->setQuery($result[$i]);
        $username = $database->loadObjectList();

        if(empty($username)) $rows[$i]->checked_out_user = '';
        else $rows[$i]->checked_out_user = $username[0]->name;
    }
    


 
    // echo '<pre>';
    // print_r($rows);
    // echo '</pre>';


    if (version_compare(JVERSION, "3.0.0", "lt")) {
        jimport('joomla.utilities.date');
        $jdate = new JDate('now');
        $date = $jdate->toMySQL();
        $date = strtotime($date);
    } else {
        $date = strtotime(JFactory::getDate()->toSQL());
    }
    foreach($rows as $row) {
        $check = strtotime($row->checked_out_time);
        $remain = ($check + 7200) - $date;
        if (($remain <= 0) && ($row->checked_out != 0)) {
            $database->setQuery("UPDATE #__medialibrary SET checked_out=0,checked_out_time=0 WHERE id='" 
                . $row->id . "'");
            $database->query();
        }
    }
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    }
    // get list of categories
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $categories[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_CATEGORIES);
    //*************   begin add for sub category in select in manager books   *************
    $options = $categories;
    $id = 0; //$categories_array;
    $list = CAT_Utils::categoryArray();
    $cat = new mainMedialibraryCategories($database); //for 1.6
    $cat->load($id);
    $this_treename = '';
    foreach($list as $item) {
        if ($this_treename) {
            if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            }
        } else {
            if ($item->id != $cat->id) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            } else {
                $this_treename = "$item->treename/";
            }
        }
    }
    $clist = mosHTML::selectList($options, 'catid',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); //new nik edit
    //*****  end add for sub category in select in manager books   **********
    $ownermenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_USERS);
    $selectstring = "SELECT id,name,email FROM  #__users GROUP BY name ORDER BY id ";
    $database->setQuery($selectstring);
    $owner_list = $database->loadObjectList();
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    }
    $i = 2;
    foreach($owner_list as $item) {
        $ownermenu[$i] = mosHTML::makeOption($item->email, $item->name);
        $i++;
    }
    $ownerlist = mosHTML::selectList($ownermenu, 'owner',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $owner);
    $lendmenu[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TO_LEND);
    $lendmenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_LEND);
    $lendmenu[] = mosHTML::makeOption('not_lend', _MEDIALIBRARY_LABEL_SELECT_NOT_LEND);
    $lendmenu[] = mosHTML::makeOption('lend', _MEDIALIBRARY_LABEL_SELECT_LEND);
    $lendlist = mosHTML::selectList($lendmenu, 'lend',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $lend);
    $pubmenu[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TO_PUBLIC);
    $pubmenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_PUBLIC);
    $pubmenu[] = mosHTML::makeOption('not_pub', _MEDIALIBRARY_LABEL_SELECT_NOT_PUBLIC);
    $pubmenu[] = mosHTML::makeOption('pub', _MEDIALIBRARY_LABEL_SELECT_PUBLIC);
    $publist = mosHTML::selectList($pubmenu, 'pub',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);
    $appmenu[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TO_APPROVE);
    $appmenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_APPROVE);
    $appmenu[] = mosHTML::makeOption('not_app', _MEDIALIBRARY_LABEL_SELECT_NOT_APPROVE);
    $appmenu[] = mosHTML::makeOption('app', _MEDIALIBRARY_LABEL_SELECT_APPROVE);
    $applist = mosHTML::selectList($appmenu, 'app',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $app);
    $typemenu[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TYPE);
    $typemenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_TYPE);
    $typemenu[] = mosHTML::makeOption('game', _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME);
    $typemenu[] = mosHTML::makeOption('music', _MEDIALIBRARY_LABEL_MEDIA_TYPE_MUSIC);
    $typemenu[] = mosHTML::makeOption('book', _MEDIALIBRARY_LABEL_MEDIA_TYPE_BOOK);
    $typemenu[] = mosHTML::makeOption('video', _MEDIALIBRARY_LABEL_MEDIA_TYPE_VIDEO);

    //*****  begin drop menu select  user    **********
    $usermenu[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_USER);
    $usermenu[] = mosHTML::makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_USERS);
    $selectstring = "SELECT usr.id,jei.owner_id, jei.owneremail, usr.username 
                     FROM  #__medialibrary AS jei  \n
                     LEFT JOIN #__users AS usr ON usr.id = jei.owner_id" . " 
                     GROUP BY usr.id  " . "\n
                     ORDER BY usr.username ";
    $database->setQuery($selectstring);
    $users_list = $database->loadObjectList();
    $useranonimus = new stdClass();
    $useranonimus->username = 'anonymous';
    $useranonimus->owner_id = 'anonymous';
    if (count($users_list) >=1) {
        $users_list[] = $useranonimus;
    }
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    }
    foreach($users_list as $item) {
        if ($item->owner_id == 0 and $item->username == '') continue;
        $usermenu[] = mosHTML::makeOption($item->owner_id, $item->username);
    }
    // print_r($usermenu);exit;
    $userlist = mosHTML::selectList($usermenu, 'select_owner_id', 'class="inputbox" size="1" 
        onchange="document.adminForm.submit();"', 'value', 'text', $select_owner_id);
    //print_r($userlist);exit;
    //*****  end drop menu select  user    **********
    
    $orderby[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_LINE);
    $orderby[] = mosHTML::makeOption('Title all ascending', _MEDIALIBRARY_LABEL_ALL_TITLE_ASCENDING);
    $orderby[] = mosHTML::makeOption('Title all descending', _MEDIALIBRARY_LABEL_ALL_TITLE_DESCENDING);
    $orderby[] = mosHTML::makeOption('Music artists ascending', _MEDIALIBRARY_LABEL_MUSIC_ARTISTS_ASCENDING);
    $orderby[] = mosHTML::makeOption('Music  artists descending', _MEDIALIBRARY_LABEL_MUSIC_ARTISTS_DESCENDING);
    $orderby[] = mosHTML::makeOption('Book authors ascending', _MEDIALIBRARY_LABEL_BOOK_PEOPLE_ASCENDING);
    $orderby[] = mosHTML::makeOption('Book  authors descending', _MEDIALIBRARY_LABEL_BOOK_PEOPLE_DESCENDING);
    $search_for[] = mosHTML::makeOption('0', _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL);
    $search_for[] = mosHTML::makeOption('id', _MEDIALIBRARY_SHOW_SEARCH_FOR_MEDIA_ID);
    $search_for[] = mosHTML::makeOption('isbn', _MEDIALIBRARY_SHOW_SEARCH_FOR_ISBN);
    $search_for[] = mosHTML::makeOption('asin', _MEDIALIBRARY_SHOW_SEARCH_FOR_ASIN);
    $search_for[] = mosHTML::makeOption('title', _MEDIALIBRARY_SHOW_SEARCH_FOR_TITLE);
    $search_for[] = mosHTML::makeOption('artist', _MEDIALIBRARY_SHOW_SEARCH_FOR_ARTIST);
    $search_for[] = mosHTML::makeOption('binding', _MEDIALIBRARY_SHOW_SEARCH_FOR_BINDING);
    $search_for[] = mosHTML::makeOption('track_listing', _MEDIALIBRARY_SHOW_SEARCH_FOR_TRACK_LISTING);
    $search_for[] = mosHTML::makeOption('description', _MEDIALIBRARY_SHOW_SEARCH_FOR_DESCRIPTION);
    $search_for[] = mosHTML::makeOption('authors', _MEDIALIBRARY_SHOW_SEARCH_FOR_AVTORS);
    $search_for[] = mosHTML::makeOption('publisher', _MEDIALIBRARY_SHOW_SEARCH_FOR_PUBLISHER);
    $search_for[] = mosHTML::makeOption('actors', _MEDIALIBRARY_SHOW_SEARCH_FOR_ACTORS);
    $search_for[] = mosHTML::makeOption('studio', _MEDIALIBRARY_SHOW_SEARCH_FOR_STUDIO);
    $search_for[] = mosHTML::makeOption('producer', _MEDIALIBRARY_SHOW_SEARCH_FOR_PRODUCER);
    $search_for[] = mosHTML::makeOption('director', _MEDIALIBRARY_SHOW_SEARCH_FOR_DIRECTOR);
    $search_for[] = mosHTML::makeOption('region', _MEDIALIBRARY_SHOW_SEARCH_FOR_REGION);
    $search_for[] = mosHTML::makeOption('format', _MEDIALIBRARY_SHOW_SEARCH_FOR_FORMAT);
    $search_for[] = mosHTML::makeOption('platform', _MEDIALIBRARY_SHOW_SEARCH_FOR_PLATFORM);
    $search_for[] = mosHTML::makeOption('category', _MEDIALIBRARY_SHOW_SEARCH_FOR_MEDIALIBRARY_LABEL_CATEGORY);
    $search_for[] = mosHTML::makeOption('langDescription', _MEDIALIBRARY_LABEL_LANGUAGE_DESCRIPTION);
    $search_for_list = mosHTML::selectList($search_for, 'srch_for',
     'class="inputbox" size="1" ', 'value', 'text', $srch_for);
    $typelist = mosHTML::selectList($typemenu, 'type',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $type);
    $mediasequence = mosHTML::selectList($orderby, 'sequence',
     'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $sequence);


    HTML_medialibrary::showMedias($option, $rows, $clist, $ownerlist, $lendlist,
     $publist, $applist, $typelist, $search, $pageNav, $mediasequence, $search_for_list, $value, $userlist);
}
/**
 * Compiles information to add or edit medias type
 * @param integer bid The unique id of the record to edit (0 if new)
 * @param array option the current options
 */







//редактирование медиа



function editMedia($option, $bid, $media_type) {
    if ($_GET) {
        $get_bid = $_GET['bid'];
        $bid = $get_bid[0];
    }
    global $database, $my;
    $medialibrary = new mosMedialibrary($database);
    $medialibrary->load(intval($bid));
    if ($bid === 0) {
        $medialibrary->media_id = 0;
        $medialibrary->media_type = $media_type;
    }


    /*  $currencys = explode(';', $medialibrary_configuration['currency']);
    foreach ($currencys as $row) {
    if ($row != '')
    {
    $row = explode("=", $row);
    if ($media->priceunit == $row[0])
    $media->price /= $row[1];
    $currency[] = mosHTML::makeOption($row[0], $row[0]);
    }
    }*/


    switch ($medialibrary->media_type) {
        case 'book':
            $media_class = new mosMedialibrary_book($database);
            $media_class->load($medialibrary->media_id);
            editing_book($media_class, $medialibrary, $option, $bid);
        break;
        case 'video':
            $media_class = new mosMedialibrary_video($database);
            $media_class->load($medialibrary->media_id);
            editing_video($media_class, $medialibrary, $option, $bid);
        break;
        case 'music':
            $media_class = new mosMedialibrary_music($database);
            $media_class->load($medialibrary->media_id);
            editing_music($media_class, $medialibrary, $option, $bid);
        break;
        case 'game':
            $media_class = new mosMedialibrary_game($database);
            $media_class->load($medialibrary->media_id);
            editing_game($media_class, $medialibrary, $option, $bid);
        break;
    }
}

/**
 * Saves the record on an edit form submit
 * @param database A database connector object
 */


function saveMedia($option, $task) {
    global $database, $my, $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
    $media = new mosMediaLibrary($database);
    $post = JRequest::get('post', JREQUEST_ALLOWHTML);
    if ($medialibrary_configuration['publish_on_add']['show']) {
        $media->published = 1;
    } else {
        $media->published = 0;
    }
    if ($medialibrary_configuration['approve_on_add']['show']) {
        $media->approved = 1;
    } else {
        $media->approved = 0;
    }

    if (!is_numeric(JRequest::getVar('media_type_id')) &&
     $medialibrary_configuration['mediaid']['auto-increment']['boolean'] == 1) {
        echo "<script> alert('You set no numeric BookID. Please set option " .
         _MEDIALIBRARY_ADMIN_CONFIG_BOOKID_AUTO_INCREMENT .
          " to \'No\' or change BookID to numeric '); window.history.go(-1); </script>\n";
        exit();
    }
    $price = $post['price'];//print_r($_REQUEST);exit;
    $priceunit = $post['priceunit'];
    $currencys = explode(';', $medialibrary_configuration['currency']);
    foreach($currencys as $currency) {
        $currency = explode("=", $currency);
        if ($priceunit == $currency[0]) {
            //$post['price'] = $price * $currency[1];
            break;
        }
    }
    if (!$media->bind($_REQUEST)) {
        echo "<script> alert('" . $media->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }

    $media_type_class = '';

    switch ($media->media_type) {
        case 'book':
            $media_type_class = new mosMedialibrary_book($database);
            if (!$media_type_class->bind($_REQUEST)) {
                echo "<script> alert('" . $media_type_class->getError() .
                 "'); window.history.go(-1); </script>\n";
                exit();//print_r($media_type_class);exit;
            }
            $media_type_class->id = JRequest::getVar('media_id');
            $media_type_class->book_id = JRequest::getVar('media_type_id');
            $media_type_class->isbn = JRequest::getVar('asin_isbn');
            
            if (JRequest::getVar('OnlineArticle')) {

            $media_type_class->id_article_book = JRequest::getVar('OnlineArticle');
            }

            $article_book_del = JRequest::getVar('article_book_del');

            if (!empty($article_book_del)) {

                $media_type_class->id_article_book = 0;
            }

            //fetch all information from the webservices if necessary
            if (intval($media->informationFrom) != 0) {
                //Amazon WS
                 $media_type_class = mosMedialibraryWS::fetchAmazonInfosBookPaapi5($media, $media_type_class);
            }
            //check error
            if (is_string($media_type_class)) {
                //there was an error while fetching!
                echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
                exit();
            }
//             if (JRequest::getVar('ebook_Url') != '')
//                 $media_class->ebookURL = JRequest::getVar('ebook_Url');
//
//             //delete old ebook file if neccesary
//             $delete_edocument = mosGetParam($_REQUEST, 'delete_edocument', 0);
//             if ($delete_edocument != '0') {
//                 @unlink($mosConfig_absolute_path . $delete_edocument);
//                 $media_type_class->ebookURL = "";
//             }
//
//
//             //storing e-Document
//             $file = $_FILES['edocument_file'];
//             $uid = md5(uniqid(rand(), 1));
//             $file['name'] = $uid . $file['name'];
//             $newpath = JPATH_COMPONENT . '/edocs/' . $file['name'];
//             //check if fileupload is correct
//             if ($medialibrary_configuration['emedias']['allow'] && intval($file['error'])
//                 > 0 && intval($file['error']) < 4) {
//                 echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR .
//                  "'); window.history.go(-1); </script>\n";
//                 exit();
//
//             } else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4) {
//                 $uploaddir = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'];
//                 $file_new = $uploaddir . $uid . $_FILES['edocument_file']['name'];
//                 //
//                 $ext = pathinfo($_FILES['edocument_file']['name'], PATHINFO_EXTENSION);
//                 $ext = strtolower($ext);
//                 $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts']);
//                 foreach($allowed_exts as $key => $allowed_ext) {
//                     $allowed_exts[$key] = strtolower($allowed_ext);
//                 }
//                 if (!in_array($ext, $allowed_exts)) {
//                     echo "<script> alert(' File ext. not allowed to upload! - " .
//                      $_FILES['edocument_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 $file['type'] = $_FILES['edocument_file']['type'];
//                 $db = JFactory::getDbo();
//                 $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " .
//                  $db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
//                 $file_db_mime = $db->loadResult();
//                 if ($file_db_mime != $file['type']) {
//                     echo "<script> alert(' File mime type not match file ext. - " .
//                      $_FILES['edoc_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 ////
//                 if (!copy($_FILES['edocument_file']['tmp_name'], $file_new)) {
//                     echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
//                     exit();
//                 } else {
//                     $media_type_class->ebookURL = $mosConfig_live_site .
//                      $medialibrary_configuration['emedias']['location'] . $file['name'];
//                 }
//             }

            $file = $_FILES['picture_file'];
            //print_r($file);exit;
            //check if fileupload is correct
            if ($file['size'] != 0 && ($file['error'] != 0 || strpos($file['type'], 'image') === false
             || strpos($file['type'], 'image') === "")) {
                echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR .
                 "'); window.history.go(-1); </script>\n";
                exit();
            }
            //if ($media->id == ''){
            //store pictures locally if neccesary, first check remote URL
                $retVal = null; 
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1
                 && trim($media_type_class->imageURL) != "" && $file['size'] == 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                }
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, $file);

                    if ($retVal != null) {
                        echo "<script> alert('" . addslashes($retVal) . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                }
            //}   
            if ($file['size'] == 0) {
                $file = null;
            }

            break;

        case 'video':
            $media_type_class = new mosMedialibrary_video($database);
            if (!$media_type_class->bind($_REQUEST)) {
                echo "<script> alert('" . addslashes($media_type_class->getError()) 
                    . "'); window.history.go(-1); </script>\n";
                exit();
            }

            $media_type_class->id = JRequest::getVar('media_id');
            $media_type_class->video_id = JRequest::getVar('media_type_id');
            $media_type_class->asin = JRequest::getVar('asin_isbn');
            $media_type_class->format = JRequest::getVar('video_format');
            //fetch all information from the webservices if necessary

            if (intval($media->informationFrom) != 0) {
                //Amazon WS
                $media_type_class = mosMedialibraryWS::fetchAmazonInfosVideoPaapi5($media, $media_type_class);
            }
           //print_r($media_type_class);exit;
            //check error
            if (is_string($media_type_class)) {
                //there was an error while fetching!
                echo "<script> alert('" . addslashes($media_type_class) . "'); window.history.go(-1); </script>\n";
                exit();
            }

//             //if ((strlen($media->owneremail) > 0) && ($media->owner_ID == 0)) $media->owner_ID; //???
//             if (JRequest::getVar('evideo_Url') != '') $media_class->evideoURL = JRequest::getVar('evideo_Url');
//             //delete old emusik file if neccesary
//             $delete_edocument = mosGetParam($_REQUEST, 'delete_edocument', 0);
//             if ($delete_edocument != '0') {
//                 @unlink($mosConfig_absolute_path . $delete_edocument);
//                 $media_type_class->evideoURL = "";
//             }
//             //storing e-Document
//             $file = $_FILES['edocument_file'];
//             $uid = md5(uniqid(rand(), 1));
//             $file['name'] = $uid . $file['name'];
//             $newpath = JPATH_COMPONENT . '/edocs/' . $file['name'];
//             //check if fileupload is correct
//             if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 
//              && intval($file['error']) < 4) {
//                 echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); 
//                  window.history.go(-1); </script>\n";
//                 exit();
//
//             } else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4) {
//                 $uploaddir = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'];
//                 $file_new = $uploaddir . $uid . $_FILES['edocument_file']['name'];
//                 //
//                 $ext = pathinfo($_FILES['edocument_file']['name'], PATHINFO_EXTENSION);
//                 $ext = strtolower($ext);
//                 $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts']);
//                 foreach($allowed_exts as $key => $allowed_ext) {
//                     $allowed_exts[$key] = strtolower($allowed_ext);
//                 }
//                 if (!in_array($ext, $allowed_exts)) {
//                     echo "<script> alert(' File ext. not allowed to upload! - " .
//                      $_FILES['edocument_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 $file['type'] = $_FILES['edocument_file']['type'];
//                 $db = JFactory::getDbo();
//                 $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " .
//                  $db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
//                 $file_db_mime = $db->loadResult();
//                 if ($file_db_mime != $file['type']) {
//                     echo "<script> alert(' File mime type not match file ext. - " .
//                      $_FILES['edoc_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 ////
//                 if (!copy($_FILES['edocument_file']['tmp_name'], $file_new)) {
//                     echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
//                     exit();
//                 } else {
//                     $media_type_class->evideoURL = $mosConfig_live_site .
//                      $medialibrary_configuration['emedias']['location'] . $file['name'];
//                 }
//             }
//

            $file = $_FILES['picture_file'];
            //check if fileupload is correct
            if ($file['size'] != 0 && ($file['error'] != 0 || strpos($file['type'], 'image') === false
             || strpos($file['type'], 'image') === "")) {
                echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR .
                 "'); window.history.go(-1); </script>\n";
                exit();
            }
            //if ($media->id == ''){
                //store pictures locally if neccesary, first check remote URL
                $retVal = null;
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1
                 && trim($media_type_class->imageURL) != "" && $file['size'] == 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                }
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, $file);
                    if ($retVal != null) {
                        echo "<script> alert('" . addslashes($retVal) . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                }
            //}
            if ($file['size'] == 0) {
                $file = null;
            }
            break;
        case 'music':
            //  music
            //$people_new =JRequest::getVar('new_artist_select');
            //print_r( $people_new);exit;
            $media_type_class = new mosMedialibrary_music($database);
            if (!$media_type_class->bind($_REQUEST)) {
                echo "<script> alert('" . addslashes($media_type_class->getError()) 
                . "'); window.history.go(-1); </script>\n";
                exit();
            }

            $media_type_class->id = JRequest::getVar('media_id');
            $media_type_class->music_id = JRequest::getVar('media_type_id');
            $media_type_class->asin = JRequest::getVar('asin_isbn');
            $media_type_class->rating = JRequest::getVar('rating');
            //fetch all information from the webservices if necessary
            if (intval($media->informationFrom) != 0) {
                //Amazon WS
                $media_type_class = mosMedialibraryWS::fetchAmazonInfosMusicPaapi5($media, $media_type_class);
            }
            //check error
            if (is_string($media_type_class)) {
                //there was an error while fetching!
                echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
                exit();
            }

//            //if ((strlen($media->owneremail) > 0) && ($media->owner_ID == 0)) $media->owner_ID;
//             if (JRequest::getVar('emusic_Url') != '') $media_class->emusicURL = JRequest::getVar('emusic_Url');
//             //delete old emusik file if neccesary
//             $delete_edocument = mosGetParam($_REQUEST, 'delete_edocument', 0);
//             if ($delete_edocument != '0') {
//                 @unlink($mosConfig_absolute_path . $delete_edocument);
//                 $media_type_class->emusicURL = "";
//             }
//             //storing e-Document
//             $file = $_FILES['edocument_file'];
//             $uid = md5(uniqid(rand(), 1));
//             $file['name'] = $uid . $file['name'];
//             $newpath = JPATH_COMPONENT . '/edocs/' . $file['name'];
//             //check if fileupload is correct
//             if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 
//                    && intval($file['error']) < 4) {
//                 echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR 
//                    . "'); window.history.go(-1); </script>\n";
//                 exit();
//
//             } else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4) {
//                 $uploaddir = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'];
//                 $file_new = $uploaddir . $uid . $_FILES['edocument_file']['name'];
//                 //
//                 $ext = pathinfo($_FILES['edocument_file']['name'], PATHINFO_EXTENSION);
//                 $ext = strtolower($ext);
//                 $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts']);
//                 foreach($allowed_exts as $key => $allowed_ext) {
//                     $allowed_exts[$key] = strtolower($allowed_ext);
//                 }
//                 if (!in_array($ext, $allowed_exts)) {
//                     echo "<script> alert(' File ext. not allowed to upload! - " .
//                      $_FILES['edocument_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 $file['type'] = $_FILES['edocument_file']['type'];
//                 $db = JFactory::getDbo();
//                 $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " .
//                  $db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
//                 $file_db_mime = $db->loadResult();
//                 if ($file_db_mime != $file['type']) {
//                     echo "<script> alert(' File mime type not match file ext. - " .
//                      $_FILES['edoc_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 ////
//                 if (!copy($_FILES['edocument_file']['tmp_name'], $file_new)) {
//                     echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
//                     exit();
//                 } else {
//                     $media_type_class->emusicURL = $mosConfig_live_site .
//                      $medialibrary_configuration['emedias']['location'] . $file['name'];
//                 }
//             }


            $file = $_FILES['picture_file'];
            //check if fileupload is correct
            if ($file['size'] != 0 && ($file['error'] != 0 || strpos($file['type'], 'image') === false
             || strpos($file['type'], 'image') === "")) {
                echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR .
                 "'); window.history.go(-1); </script>\n";
                exit();
            }
            //if ($media->id == ''){
                //store pictures locally if neccesary, first check remote URL
                $retVal = null;
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1
                 && trim($media_type_class->imageURL) != "" && $file['size'] == 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                }
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, $file);
                    if ($retVal != null) {
                        echo "<script> alert('" . addslashes($retVal) . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                }
            //}
            if ($file['size'] == 0) {
                $file = null;
            }
            break;
        case 'game':
            $media_type_class = new mosMedialibrary_game($database);
            if (!$media_type_class->bind($_REQUEST)) {
                echo "<script> alert('" . addslashes($media_type_class->getError()) 
                    . "'); window.history.go(-1); </script>\n";
                exit();
            }
            $media_type_class->id = JRequest::getVar('media_id');
            $media_type_class->game_id = JRequest::getVar('media_type_id');
            $media_type_class->asin = JRequest::getVar('asin_isbn');
            //fetch all information from the webservices if necessary
            if (intval($media->informationFrom) != 0) {
                //Amazon WS
                $media_type_class = mosMedialibraryWS::fetchAmazonInfosGamePaapi5($media, $media_type_class);
            }
            //check error
            if (is_string($media_type_class)) {
                //there was an error while fetching!
                echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
                exit();
            }
            if ((strlen($media->owneremail) > 0) && ($media->owner_ID == 0)) $media->owner_ID;



//             if (JRequest::getVar('egame_Url') != '') $media_class->emusicURL = JRequest::getVar('egame_Url');
//             //delete old emusik file if neccesary
//             $delete_edocument = mosGetParam($_REQUEST, 'delete_edocument', 0);
//             if ($delete_edocument != '0') {
//                 @unlink($mosConfig_absolute_path . $delete_edocument);
//                 $media_type_class->egameURL = "";
//             }
//
//             //storing e-Document
//             $file = $_FILES['edocument_file'];
//             $uid = md5(uniqid(rand(), 1));
//             $file['name'] = $uid . $file['name'];
//             $newpath = JPATH_COMPONENT . '/edocs/' . $file['name'];
//             //check if fileupload is correct
//             if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 
//                && intval($file['error']) < 4) {
//                 echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR 
//                . "'); window.history.go(-1); </script>\n";
//                 exit();
//
//             } else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4) {
//                 $uploaddir = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'];
//                 $file_new = $uploaddir . $uid . $_FILES['edocument_file']['name'];
//                 //
//                 $ext = pathinfo($_FILES['edocument_file']['name'], PATHINFO_EXTENSION);
//                 $ext = strtolower($ext);
//                 $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts']);
//                 foreach($allowed_exts as $key => $allowed_ext) {
//                     $allowed_exts[$key] = strtolower($allowed_ext);
//                 }
//                 if (!in_array($ext, $allowed_exts)) {
//                     echo "<script> alert(' File ext. not allowed to upload! - " .
//                      $_FILES['edocument_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 $file['type'] = $_FILES['edocument_file']['type'];
//                 $db = JFactory::getDbo();
//                 $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " .
//                  $db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
//                 $file_db_mime = $db->loadResult();
//                 if ($file_db_mime != $file['type']) {
//                     echo "<script> alert(' File mime type not match file ext. - " .
//                      $_FILES['edoc_file']['name'] . "'); window.history.go(-1); </script>\n";
//                     exit();
//                 }
//                 ////
//                 if (!copy($_FILES['edocument_file']['tmp_name'], $file_new)) {
//                     echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
//                     exit();
//                 } else {
//                     $media_type_class->egameURL = $mosConfig_live_site .
//                      $medialibrary_configuration['emedias']['location'] . $file['name'];
//                 }
//             }

            $file = $_FILES['picture_file'];
            //check if fileupload is correct
            if ($file['size'] != 0 && ($file['error'] != 0 || strpos($file['type'], 'image') === false
             || strpos($file['type'], 'image') === "")) {
                echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR .
                 "'); window.history.go(-1); </script>\n";
                exit();
            }
            //if ($media->id == ''){
                //store pictures locally if neccesary, first check remote URL
                $retVal = null;
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1
                 && trim($media_type_class->imageURL) != "" && $file['size'] == 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                }
                if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0) {
                    $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, $file);
                    if ($retVal != null) {
                        echo "<script> alert('" . addslashes($retVal) . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                }
            //}
            if ($file['size'] == 0) {
                $file = null;
            }
            break;
        }
        //end of switch
        $media->date = date("Y-m-d H:i:s");

        if (!$media_type_class->check()) {
            echo "<script> alert('" . addslashes($media_type_class->_error) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }

        if (!$media->check()) {
            echo "<script> alert('" . addslashes($media->_error()) . "'); window.history.go(-1); </script>\n";
            exit();
        }

//print_r($media_type_class);exit;
        $people_save = 0;
        $informationFrom = protectInjectionWithoutQuote('informationFrom');
        ///////////////////
        $amazon_authors = array();
        if(isset($media_type_class->authors)){
            $amazon_authors['author'] = explode(',', $media_type_class->authors); 
             unset($media_type_class->authors);
        }
        if(isset($media_type_class->studio)){
          if( $media->media_type == "video")
            $amazon_authors['video_studio']= explode(',', $media_type_class->studio);
          if( $media->media_type == "game")
            $amazon_authors['game_studio']= explode(',', $media_type_class->studio);
          unset($media_type_class->studio);
        } 
        if(isset($media_type_class->artist)){
            $amazon_authors['artist'] = explode(',', $media_type_class->artist);
            unset($media_type_class->artist);
        }
        if(isset($media_type_class->actors)){
            $amazon_authors['actor'] = explode(',', $media_type_class->actors);
            unset($media_type_class->actors);
        }
        if(isset($media_type_class->directors)){
            $amazon_authors['director'] = explode(',', $media_type_class->directors);
            unset($media_type_class->directors);
        }
        if(isset($media_type_class->producers)){
            $amazon_authors['producer'] = explode(',', $media_type_class->producers);
            unset($media_type_class->producers);
        }
        
        if(isset($media_type_class->rating)){
            $media_type_class->rating = protectInjectionWithoutQuote('rating', '0');
        }
//
//print_r($media_type_class);exit;
        if (!$media_type_class->store()) {
            echo "<script> alert('" . addslashes($media_type_class->_error()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        //save book authors
//print_r($media_type_class);exit;

        //save book authors

        //end save authors
        //delete authors

        $media->media_id = $media_type_class->id;
        if (!$media->store()) {
            $media_type_class->delete($media_type_class->id);

            echo "<script> alert('" . addslashes($media->_error()) . "'); window.history.go(-1); </script>\n";
            exit();
        }

//print_r('ok');exit;
        addPeople($media, $media_type_class, $amazon_authors, $people_save);
        //end save authors
        //delete authors

    /*************Call function to Save changes for associated books*******************/
         save_media_associate();
    //********************start saving files*****************************
         med_storeVideo($media);
         med_storeTrack($media);
         med_storeAudio($media);
         med_storeEbook($media);
    //*************end saving files*********************


        $media->catid = JRequest::getVar('catid');
        $query = "delete from #__medialibrary_categories where mediaid='" . (int)$media->id . "'";
        $database->setQuery($query);
        $database->query();
        foreach($media->catid as $catitem) {
            $query = "insert into #__medialibrary_categories (mediaid, catid) VALUES ('" 
                . (int)$media->id . "','" . (int)$catitem . "')";
            $database->setQuery($query);
            $database->query();
        }

/**************delete people********/
        // $del_auth_ids = JRequest::getVar('del_auth_ids', array());
        // foreach ($del_auth_ids as $del_auth_id) {
      // }

/**************************/

        $media->checkin();

    //************start deleting files**************
          med_deleteVideos($media->id);
          med_deleteTracks($media->id);
          med_deleteAudios($media->id);
          med_deleteFiles($media->id);
    //*****************************************************end deleting files****

        switch ($task) {
            case 'apply':
                mosRedirect("index.php?option=" . $option . "&task=edit&bid[]=" . $media->id);
            break;
            case 'save':
                mosRedirect("index.php?option=" . $option);
            break;
        }
    }

    function addPeople ($media, $media_type_class, $amazon_authors, $people_save = 0) {
        global $database, $my;
        $query = "DELETE FROM #__medialibrary_people_connect WHERE fk_media_id = ".(int)$media->id;
        $database->setQuery($query);
        $database->query();
        $author_own = array();
        if (intval($media->informationFrom) != 0){
            //amazon media

          //  if(isset($amazon_authors[0]) && !empty($amazon_authors[0])){
                //book load from amazon
                //print_r('lpk');exit;
                foreach ($amazon_authors as $people_type=> $author_names) {
                    if(!empty($author_names[0])){
                        // print_r($author_names);exit;
                        foreach ($author_names as $author_name) {
                            $query = "SELECT id FROM #__medialibrary_people "
                                    ."\n WHERE people_name=".$database->Quote($author_name)
                                    ."\n AND type=". $database->Quote($people_type);
                            $database->setQuery($query);
                            $author_id = $database->loadResult();
                            //print_r($author_id);exit;
                            if (!$author_id) {
                                $new_author = new mosMediaLibrary_people($database);
                                $new_author->date        = date("Y-m-d H:i:s");
                                $new_author->approved    = 1;
                                $new_author->published   = 1;
                                $new_author->owner_id    = $my->id;
                                $new_author->people_name = $author_name;
                                $new_author->type = $people_type;
                                $new_author->store();
                                $author_id = $new_author->id;
                            }
                            $query = "insert into #__medialibrary_people_connect (fk_media_id, fk_people_id)
                              VALUES ('" . (int)$media->id . "','" . $author_id . "')";
                            $database->setQuery($query);
                            $database->query();
                        }
                    }
                }
        }else{
        //custom media
             switch ($media->media_type) {
                case "book":
                    if (protectInjectionWithoutQuote('new_author_field', '') != ''){
                        $author_own['author']['name'] = protectInjectionWithoutQuote('new_author_field', '');
                    } else {
                        $author_own['author'] = mosGetParam($_REQUEST, 'new_author_select', array());
                    }
                    break;
                case "music":
                    if (protectInjectionWithoutQuote('new_artist_field', '') != ''){
                        $author_own['artist']['name'] = protectInjectionWithoutQuote('new_artist_field', '');
                    } else {
                        $author_own['artist'] = mosGetParam($_REQUEST, 'new_artist_select', array());
                    }
                    //print_r($author_own);exit;
                    break;
                case "video":
                    if (protectInjectionWithoutQuote('new_actor_field', '') != ''){
                        $author_own['actor']['name']= protectInjectionWithoutQuote('new_actor_field', '');
                    } else {
                        if (!empty(mosGetParam($_REQUEST, 'new_actor_select', array()))){
                            $author_own['actor'] = mosGetParam($_REQUEST, 'new_actor_select', array());
                        }
                    }
                    if (protectInjectionWithoutQuote('new_studio_field', '') != ''){
                        $author_own['video_studio']['name']= protectInjectionWithoutQuote('new_studio_field', '');
                    } else {
                        if (!empty(mosGetParam($_REQUEST, 'new_video_studio_select', array()))){
                            $author_own['video_studio'] = mosGetParam($_REQUEST, 'new_video_studio_select', 
                                array());
                        }
                    }
                    if (protectInjectionWithoutQuote('new_producer_field', '') != ''){
                        $author_own['producer']['name']= protectInjectionWithoutQuote('new_producer_field', '');
                    } else {
                        if (!empty(mosGetParam($_REQUEST, 'new_producer_select', array()))){
                            $author_own['producer'] = mosGetParam($_REQUEST, 'new_producer_select', array());
                        }
                    }
                    if (protectInjectionWithoutQuote('new_director_field', '') != ''){
                        $author_own['director']['name']= protectInjectionWithoutQuote('new_director_field', '');
                    } else {
                        if (!empty(mosGetParam($_REQUEST, 'new_director_select', array()))){
                            $author_own['director'] = mosGetParam($_REQUEST, 'new_director_select', array());
                        }
                    } 
                    break;
                case "game":
                    if (protectInjectionWithoutQuote('new_studio_field', '') != ''){
                        $author_own['game_studio']['name']= protectInjectionWithoutQuote(
                                'new_studio_field', '');
                    } else {
                        $author_own['game_studio'] = mosGetParam($_REQUEST, 'new_game_studio_select', array());
                    }
                    break;

                default:
                    $author_own = '';// code...
                    break;
            }
            foreach($author_own as $people_type => $people) {
                foreach ($people as $input => $pearson) {
                    if ($input === 'name') {
                        $query = "SELECT id FROM #__medialibrary_people "
                                ."\n WHERE people_name=".$database->Quote($pearson)
                                ."\n AND type=". $database->Quote($people_type);
                        $database->setQuery($query);
                        $author_id = $database->loadResult();
                        //print_r($author_id);exit;
                        if (!$author_id) {
                            $new_author = new mosMediaLibrary_people($database);
                            $new_author->date        = date("Y-m-d H:i:s");
                            $new_author->approved    = 1;
                            $new_author->published   = 1;
                            $new_author->owner_id    = $my->id;
                            $new_author->people_name = $pearson;
                            $new_author->type = $people_type;
                            $new_author->store();
                            $author_id = $new_author->id;
                        }
                    } else $author_id = $pearson;
                    $query = "insert into #__medialibrary_people_connect (fk_media_id, fk_people_id)
                              VALUES ('" . (int)$media->id . "','" . (int)$author_id . "')";
                    //print_r($query);exit;
                    $database->setQuery($query);
                    $database->query();
                }
            }
        }

    }

    function saveAuthor($option, $task) {



        global $database, $my, $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        $author = new mosMediaLibrary_people($database);
        $idAuthor = JRequest::getVar('people_id', 0);
        //print_r($idAuthor);exit;
        $langshowAuthor = JRequest::getVar('langshow', 0);
        $auto_desc = protectInjectionWithoutQuote('auto_desc','');
        if (!$idAuthor) {
            $aut_name = protectInjectionWithoutQuote('people_name'); //print_r($aut_name);exit;
            //$people_photo = mosGetParam($_POST, 'picture_file_author', '');
            $zap = "SELECT id,langshow FROM #__medialibrary_people WHERE people_name LIKE '%" . $aut_name . "%' ";
            $database->setQuery($zap);
            $idAndLangshowAuthors = $database->loadAssocList();
            if (!empty($idAndLangshowAuthors) && ($langshowAuthor == '*')) {
                echo "<script> alert('" . _MEDIALIBRARY_ADMIN_CONFIG_CHECK_PEOPLE. "');
                    window.history.go(-1); </script>\n";
                exit();
            } else if ($langshowAuthor != '*') {
                foreach ($idAndLangshowAuthors as $value) {
                    if($value['langshow'] == $langshowAuthor) {
                        echo "<script> alert('" . _MEDIALIBRARY_ADMIN_CONFIG_CHECK_PEOPLE_LANGUAGE . "');
                        window.history.go(-1); </script>\n";
                        exit();
                    }
                }
            }
        }else{
            $author->load($idAuthor);
        }
        if (!$author->bind($_POST)) {
            echo "<script> alert('" . addslashes($author->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }

        $zapros = "SELECT people_name FROM #__medialibrary_people WHERE id = '" . $author->id . "';";
        $database->setQuery($zapros);
        $people_name = $database->loadResult();
        if (!empty($author->description) && !empty($people_name)) {
            $selectstring = "SELECT p.people_name , p.id, m.id FROM #__medialibrary_people AS p "
                            ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id"
                            ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                            ."\n WHERE p.people_name LIKE '%" . $author->people_name . "%' ";

            $database->setQuery($selectstring);
            $rows = $database->loadObjectList();
            $database->setQuery("SELECT id FROM #__menu WHERE link LIKE
                                'index.php?option=com_medialibrary&view=categories%'
                                or link LIKE 'index.php?option=com_medialibrary&task=categories%' ");
            $Itebid_tmp_from_db = $database->loadResult();
            $message = $_POST['description'];
            $message = str_replace("{people_name}","{people_name}", $message);
            $message = str_replace("{books_titles}","{books_titles}", $message);
            $author->description = $message;
        }
        $owner_id = protectInjectionWithoutQuote('owner_id', '');
        $database->setQuery("SELECT owneremail, owner_id FROM #__medialibrary_people WHERE id = '" .
                $_POST['owner_id'] . "'");
        $own = $database->loadObjectList();
        if ($own == "" || $own == NUll) {
            if ($owner_id) {
                $author->owner_id = $owner_id;
            } else {  
                $author->owner_id = $my->id;
            }
        }
        if ($medialibrary_configuration['publish_on_add']['show']) {
            $author->published = 1;
        } else {
            $author->published = 0;
        }
        $database->setQuery("SELECT max(id) FROM #__medialibrary_people");
        $max_id = $database->loadResult();
        $max_id = $max_id + 1;
        $file = $_FILES['picture_file_author'];

        //-------------------
        if (intval($file['error']) != 4) {
            $ext = pathinfo($_FILES['picture_file_author']['name'], PATHINFO_EXTENSION);
            $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_img']);
            $ext = strtolower($ext);
            if (!in_array($ext, $allowed_exts)) {
                echo "<script> alert(' File ext. not allowed to upload! - " . $file['name'] . "');
                    window.history.go(-1); </script>\n";
                exit();
            }
        }

        
        //-------------------
        //check if fileupload is correct
        if ($file['size'] != 0 && ($file['error'] != 0 || strpos($file['type'], 'image') === false ||
            strpos($file['type'], 'image') === "")) {
            echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR . "');
                 window.history.go(-1); </script>\n";
            exit();
        }
        $retVal = null;

        $database->setQuery("SELECT imageURL FROM #__medialibrary_people where id = '" . $author->id . "'");
        $imageURL = $database->loadResult();
        if (!empty($file['name']) && !empty($imageURL)) {
            $file_inf = pathinfo($imageURL);
            $file_type = '.' . $file_inf['extension'];
            $file_name = basename($imageURL, $file_type);
            if(!empty($file_name) ){
                $path = $mosConfig_absolute_path . '/components/com_medialibrary/covers';
                $check_files = JFolder::files($path, '^' . $file_name . '.*$', false, true);
                foreach($check_files as $check_file) {
                    unlink($check_file);
                }
            }               
        }

        if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && trim($author->imageURL) != "" &&
            $file['size'] == 0) {
            $retVal = mosMedialibraryOthers::storeImageFileAuthor($author, null, $max_id);
        }
        if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0) {
            $retVal = mosMedialibraryOthers::storeImageFileAuthor($author, $file, $max_id);
            if ($retVal != null) {
                echo "<script> alert('" . addslashes($retVal) . "'); window.history.go(-1); </script>\n";
                exit();
            }
        }
        if ($file['size'] == 0) {
            $file = null;
        }
        $author->date = date("Y-m-d H:i:s");
        $author->auto_gener_description = $auto_desc;
        if (!$author->check()) {
            echo "<script> alert('" . addslashes($book->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }

        if (!$author->store()) {
            echo "<script> alert('" . addslashes($book->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        
        /*************Call function to Save changes for associated books*******************/
        save_author_associate_media();
        $author->checkin();
        /***************************************************************************************************/
        switch ($task) {
            case 'apply_author':
                mosRedirect("index.php?option=" . $option . "&task=manage_author&bid[]=" . $author->id);
            break;
            case 'save_author':
                mosRedirect("index.php?option=" . $option . "&task=manage_author");
            break;
        }

        
        
    }

    function removeMedia($bid, $option) {
        global $database, $mosConfig_absolute_path, $medialibrary_configuration;
        if (!is_array($bid) || count($bid) < 1) {
            echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
            exit;
        }
        foreach($bid as $onebid) {
          $tempbid = explode(',',$onebid);
          $newbid[] = $tempbid[0];
        }
  /***********************************************************************************************/
    for ($i = 0;$i < count($newbid);$i++) {
        $query = "select associate_media from #__medialibrary where id =" . $newbid[$i];
        $database->setQuery($query);
        $mediaAssociateMedia = $database->loadResult();
        $assocMediaObj = unserialize($mediaAssociateMedia);
        $idWhereChange = array();
        if (!empty($assocMediaObj)) {
            foreach($assocMediaObj as $key => $value) {
                if ($value == $newbid[$i]) {
                    $assocMediaObj[$key] = null;
                } else if ($value) {
                    $idWhereChange[] = $value;
                }
            }
            $stringIdWhereChange = implode(',', $idWhereChange);
            $newAssocSerialize = serialize($assocMediaObj);

            if (!empty($stringIdWhereChange)) {
                $query = "update #__medialibrary set associate_media ='$newAssocSerialize' 
                          where id in($stringIdWhereChange)";
                $database->setQuery($query);
                $database->query();
            }
        }
    }
  /***********************************************************************************************/
        for ($i = 0;$i < count($bid);$i++) {
            $medialibrary = new mosMedialibrary($database);
            $media_class = new mosMedialibrary_book($database);
            $medialibrary->load(intval($bid[$i]));
            //print_r($medialibrary);exit;
            $removefile = 1;
            med_deleteVideos($medialibrary->id, $removefile);
            med_deleteTracks($medialibrary->id, $removefile);
            med_deleteAudios($medialibrary->id, $removefile);
            med_deleteFiles($medialibrary->id, $removefile);

            switch ($medialibrary->media_type) {
                case 'book':
                    foreach ($newbid as $one_bid) {
                        $query = "SELECT b.imageURL FROM #__medialibrary_book AS b"
                        ."\n LEFT JOIN #__medialibrary AS m ON b.id = m.media_id"
                        ."\n WHERE m.id = ".$one_bid;
                      //print_r($query);exit;
                        $database->setQuery($query);
                        $images = $database->loadResult();
                        if ($images) {
                            unlink($mosConfig_absolute_path . $images);
                        }

                        $database->setQuery("DELETE FROM #__medialibrary_book WHERE id = " 
                                .$medialibrary->media_id);

                        if (!$database->query()) {
                            echo "<script> alert('" . addcslashes($database->stderr()) 
                                . "'); window.history.go(-1); </script>\n";
                        }

                        $database->setQuery("DELETE FROM #__medialibrary_people_connect
                        WHERE fk_media_id in (  SELECT id FROM  #__medialibrary WHERE (media_id = "
                            .$medialibrary->media_id   
                    .") AND ( media_type = 'book' ));");
                        //$database->setQuery("DELETE FROM #__medialibrary_people_connect WHERE fk_media_id = "
                        // .$medialibrary->media_id);

                        if (!$database->query()) {
                            echo "<script> alert('" . addcslashes($database->stderr()) 
                                . "'); window.history.go(-1); </script>\n";
                    }
                }

                break;
                case 'video':
                foreach ($newbid as $one_bid) {
                        $query = "SELECT v.imageURL FROM #__medialibrary_video AS v"
                        ."\n LEFT JOIN #__medialibrary AS m ON v.id = m.media_id"
                        ."\n WHERE m.id = ".$one_bid;
                      //print_r($query);exit;
                        $database->setQuery($query);
                        $images = $database->loadResult();
                        if ($images) {
                            unlink($mosConfig_absolute_path . $images);
                        }
                    $database->setQuery("DELETE FROM #__medialibrary_video WHERE id = " 
                            .$medialibrary->media_id);
                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                    $database->setQuery("DELETE FROM #__medialibrary_people_connect
                        WHERE fk_media_id in (  SELECT id FROM  #__medialibrary WHERE (media_id = "
                            .$medialibrary->media_id   
                    .") AND ( media_type = 'video' ));");

                     //$database->setQuery("DELETE FROM #__medialibrary_people_connect WHERE fk_media_id = " 
                     //.$medialibrary->media_id);

                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                }
                break;
                case 'music':
                foreach ($newbid as $one_bid) {
                    if ($medialibrary->informationFrom==0){
                        $query = "SELECT mu.imageURL FROM #__medialibrary_music AS mu"
                        ."\n LEFT JOIN #__medialibrary AS m ON mu.id = m.media_id"
                        ."\n WHERE m.id = ".$one_bid;
                        $database->setQuery($query);
                        $images = $database->loadResult();
                        if ($images) {
                            unlink($mosConfig_absolute_path . $images);
                        }
                    }
                    $database->setQuery("DELETE FROM #__medialibrary_music WHERE id = " .$medialibrary->media_id);

                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                    $database->setQuery("DELETE FROM #__medialibrary_people_connect
                        WHERE fk_media_id in (  SELECT id FROM  #__medialibrary WHERE (media_id = "
                            .$medialibrary->media_id   
                    .") AND ( media_type = 'music' ));");
                    // $database->setQuery("DELETE FROM #__medialibrary_people_connect WHERE fk_media_id = " 
                    // .$medialibrary->media_id);

                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                }
                break;
                case 'game':
                foreach ($newbid as $one_bid) {
                        $query = "SELECT g.imageURL FROM #__medialibrary_game AS g"
                        ."\n LEFT JOIN #__medialibrary AS m ON g.id = m.media_id"
                        ."\n WHERE m.id = ".$one_bid;
                      //print_r($query);exit;
                        $database->setQuery($query);
                        $images = $database->loadResult();
                        if ($images) {
                            unlink($mosConfig_absolute_path . $images);
                        }
                    $database->setQuery("DELETE FROM #__medialibrary_game WHERE id = " 
                            .$medialibrary->media_id);
                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                    $database->setQuery("DELETE FROM #__medialibrary_people_connect
                        WHERE fk_media_id in (  SELECT id FROM  #__medialibrary WHERE (media_id = "
                            .$medialibrary->media_id   
                    .") AND ( media_type = 'game' ));");
                    // $database->setQuery("DELETE FROM #__medialibrary_people_connect WHERE fk_media_id = " 
                    // .$medialibrary->media_id);

                    if (!$database->query()) {
                        echo "<script> alert('" . addcslashes($database->stderr()) 
                            . "'); window.history.go(-1); </script>\n";
                    }
                }
                break;
            }
            $database->setQuery("DELETE FROM #__medialibrary_categories WHERE mediaid = " 
                .$medialibrary->id);
            if (!$database->query()) {
                echo "<script> alert('" . addslashes($database->getErrorMsg()) 
                    . "'); window.history.go(-1); </script>\n";
            }
            $medialibrary->delete();
        }
        mosRedirect("index.php?option=$option");
    }

    /**
     * Publishes or Unpublishes one or more records
     * @param array - An array of unique category id numbers
     * @param integer - 0 if unpublishing, 1 if publishing
     * @param string - The current author option
     */
    function publishMedias($bid, $publish, $option) {
        global $database, $my;
      //  print_r($bid);exit;
        $catid = mosGetParam($_POST, 'catid', array(0));
        if (!is_array($bid) || count($bid) < 1) {
            $action = $publish ? 'publish' : 'unpublish';
            echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
            exit;
        }

 /*
UPDATE `j1jsm_medialibrary` SET `published`= CASE
WHEN `media_id`=1 and `media_type`='video' THEN '0'
WHEN `media_id`=2 and `media_type`='game' THEN '0'
WHEN `media_id`=1 and `media_type`='book' THEN '0'  ELSE `published`
 END
 */

        $countInfo = count ($bid);
        $whenThen = '';
        for ($i = 0; $i < $countInfo; $i++) {
            $bids[$i] = explode(',', $bid[$i]);
            $media_id = $bids[$i][1];
            $media_type = $bids[$i][2];
            $whenThen .= "  WHEN media_id=$media_id AND media_type='$media_type' THEN '$publish' ";
        }
       // print_r($whenThen);exit;
        $query = "UPDATE #__medialibrary SET published= CASE $whenThen ELSE published END ";
        $database->setQuery($query);

        if (!$database->query()) {
            echo "<script> alert('" . addcslashes($database->stderr()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (count($bid) == 1) {
            $row = new mosMediaLibrary($database);
            $row->checkin($bid[0]);
        }
        mosRedirect("index.php?option=$option");
    }
    /**
     * Approve or Unapprove one or more records
     * @param array - An array of unique category id numbers
     * @param integer - 0 if unapprove, 1 if approve
     * @param string - The current author option
     */
    function approveMedias($bid, $approve, $option) {

        global $database, $my;
       // print_r($bid);exit;
        $catid = mosGetParam($_POST, 'catid', array(0));
        if (!is_array($bid) || count($bid) < 1) {
            $action = $approve ? 'approve' : 'unapprove';
            echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
            exit;
        }
      //  $vids = implode(',', $bid);

        $countInfo = count ($bid);
        $whenThen = '';
        for ($i = 0; $i < $countInfo; $i++) {
              $bids[$i] = explode(',', $bid[$i]);
              $media_id = $bids[$i][1];
              $media_type = $bids[$i][2];
              $whenThen .= "  WHEN media_id=$media_id AND media_type='$media_type' THEN '$approve' ";
        }

        $database->setQuery("UPDATE #__medialibrary SET approved= CASE $whenThen  ELSE approved END " .
         "   WHERE (checked_out=0 OR (checked_out='$my->id'))");


        if (!$database->query()) {
            echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (count($bid) == 1) {
            $row = new mosMediaLibrary($database);
            $row->checkin($bid[0]);
        }
        mosRedirect("index.php?option=$option");
    }
    /**
     * Moves the order of a record
     * @param integer - The increment to reorder by
     */
    function orderBooks($bid, $inc, $option) {
        global $database;
        $book = new mosMediaLibrary($database);
        $book->load($bid);
        $book->move($inc);
        mosRedirect("index.php?option=$option");
    }
    /**
     * Cancels an edit operation
     * @param string - The current author option
     */
    function cancelEditMedia($option) {
        global $database;
        // $row = new mosMediaLibrary($database);
        // $row->bind($_POST);
        // $row->checkin();
        mosRedirect("index.php?option=$option");
    }
    /**
     * Refetches the book information
     * @param string - The current author option
     */
    function refetchInfo($option, $bid) {
        global $database, $my, $medialibrary_configuration;
        $informationFrom = mosGetParam($_POST, 'informationFrom');
        if (!is_array($bid) || count($bid) < 1) {
            echo "<script> alert('Select an item to refetch'); window.history.go(-1);</script>\n";
            exit;
        }
        $bid2 = array();
        foreach ($bid as $key => $value) {
            $bid2[] = explode(',', $value)[0];
        }
        $bids = implode("','", $bid2);
        $selectstring = "SELECT library.id, library.media_type, library.media_id,"
          . "cc.title AS category, mc.catid, " . " library.informationFrom, "
          . " other_table.id as media_type_id,  other_table.title as title  "
          . " FROM #__medialibrary AS library "
          . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
          . " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid "
          . " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game "
          . " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music "
          . " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book "
          . " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) "
          . " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type"
          . " WHERE library.id IN ('".$bids."') " . " ORDER BY mc.catid, library.ordering ";
        
        $database->setQuery($selectstring);
        $rows = $database->loadObjectList();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            exit();
        }
        // get list of WS
        $retVal = mosMedialibraryWS::getWSArray();
        $ws = null;
        for ($i = 0, $n = count($retVal);$i < $n;$i++) {
            $help = $retVal[$i];
            $ws[] = mosHTML::makeOption($help[0], $help[1]);
        }
        $wslist = mosHTML::selectList($ws, 'informationFrom', 'class="inputbox" size="1"', 'value', 'text');
        if ($informationFrom == null) {
            //show fetching information
            HTML_medialibrary::refetchMedias($option, $rows, $wslist);
        } else {
            //fetching information
            $infos = array();
            $media_id = array_pop($bid);
            while ($media_id != null) {
                $media = new mosMediaLibrary($database);
                $media->load($media_id);
                $media->informationFrom = $informationFrom;
                $media_tmp = $media;
                $media_type_class = '';
                switch ($media->media_type) {
                    case 'book':
                        $media_type_class = new mosMedialibrary_book($database);
                        $media_type_class->load($media->media_id);
                        //fetch all information from the webservices Amazon WS
                        $media_type_class = mosMedialibraryWS::fetchAmazonInfosBookPaapi5($media, 
                                $media_type_class);
                        $media_type_class_tmp = $media_type_class;
                        //check error
                        if (is_string($media_type_class)) {
                            //there was an error while fetching!
                            if (strpos($media_type_class, 'faultcode') !== false){
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 'faultcode', 'faultcode'));   
                            } else {
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 $media_type_class_tmp, $media_type_class));
                            }
                        } else {
                            //storing pictures if neccesary
                            $retVal = null;
                            if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1) {
                                $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                            }
                        }
                    break;
                    case 'video':
                        $media_type_class = new mosMedialibrary_video($database);
                        $media_type_class->load($media->media_id);
                        //fetch all information from the webservices Amazon WS
                        $media_type_class = mosMedialibraryWS::fetchAmazonInfosVideoPaapi5($media, 
                            $media_type_class);
                        $media_type_class_tmp = $media_type_class;
                        //check error
                        if (is_string($media_type_class)) {
                            //there was an error while fetching!
                            if (strpos($media_type_class, 'faultcode') !== false){
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 'faultcode', 'faultcode'));   
                            } else {
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 $media_type_class_tmp, $media_type_class));
                            }
                        } else {
                            //storing pictures if neccesary
                            $retVal = null;
                            if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1) {
                                $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                            }
                        }
                    break;
                    case 'music':
                        $media_type_class = new mosMedialibrary_music($database);
                        $media_type_class->load($media->media_id);
                        //fetch all information from the webservices Amazon WS
                        $media_type_class = mosMedialibraryWS::fetchAmazonInfosMusicPaapi5($media, 
                            $media_type_class);
                        $media_type_class_tmp = $media_type_class;
                        //check error
                        if (is_string($media_type_class)) {
                            //there was an error while fetching!
                            if (strpos($media_type_class, 'faultcode') !== false){
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 'faultcode', 'faultcode'));   
                            } else {
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 $media_type_class_tmp, $media_type_class));
                            }
                        } else {
                            //storing pictures if neccesary
                            $retVal = null;
                            if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1) {
                                $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                            }
                        }
                    break;
                    case 'game':
                        $media_type_class = new mosMedialibrary_game($database);
                        $media_type_class->load($media->media_id);
                        //fetch all information from the webservices Amazon WS
                        $media_type_class = mosMedialibraryWS::fetchAmazonInfosGamePaapi5($media, 
                            $media_type_class);
                        $media_type_class_tmp = $media_type_class;
                        //check error
                        if (is_string($media_type_class)) {
                            //there was an error while fetching!
                            if (strpos($media_type_class, 'faultcode') !== false){
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 'faultcode', 'faultcode'));   
                            } else {
                                array_push($infos, array($media_tmp->id, $media_tmp->media_type,
                                 $media_type_class_tmp, $media_type_class));
                            }
                        } else {
                            //storing pictures if neccesary
                            $retVal = null;
                            if (intval($medialibrary_configuration['fetchImages']['boolean']) == 1) {
                                $retVal = mosMedialibraryOthers::storeImageFile($media, $media_type_class, null);
                            }
                        }
                }
                //fetching was OK!
                $media->date = date("Y-m-d H:i:s");
                if ($retVal != null) {
                    // error storing picture
                    if (is_string($media_type_class)){
                        $media_type_class_t = $media_type_class;
                    } else {
                        $media_type_class_t = $media_type_class->title;
                    }
                    if ($infos[count($infos)-1][0] != $media->id){
                        array_push($infos, array($media->id, $media->media_type, $media_type_class_t, $retVal));
                    }
                } else {
                    if (!$media_type_class->check()) {
                        array_push($infos, array($media->id, $media->media_type,
                         $media_type_class->title, $media_type_class->getError()));
                    } else {
                        if (!$media->check()) {
                            array_push($infos, array($media->id, $media->media_type,
                             $media_type_class->title, $media->getError()));
                        } else {
                            if (!$media_type_class->store()) {
                                array_push($infos, array($media->id, $media->media_type,
                                 $media_type_class->title, $media_type_class->getError()));
                            } else {
                                $media->media_id = $media_type_class->id;
                                if (!$media->store()) {
                                    array_push($infos, array($media->id, $media->media_type,
                                     $media_type_class->title, $media->getError()));
                                }
                                $amazon_authors = array();
                                if(isset($media_type_class->authors)){
                                    $amazon_authors['author'] = $media_type_class->authors;
                                     unset($media_type_class->authors);
                                }
                                if(isset($media_type_class->studio)){
                                  if( $media->media_type == "video")
                                    $amazon_authors['video_studio']= explode(',', $media_type_class->studio);
                                  if( $media->media_type == "game")
                                    $amazon_authors['game_studio']= explode(',', $media_type_class->studio);
                                  unset($media_type_class->studio);
                                } 
                                if(isset($media_type_class->artist)){
                                    $amazon_authors['artist'] = explode(',', $media_type_class->artist);
                                    unset($media_type_class->artist);
                                }
                                if(isset($media_type_class->actors)){
                                    $amazon_authors['actor'] = explode(',', $media_type_class->actors);
                                    unset($media_type_class->actors);
                                }
                                if(isset($media_type_class->directors)){
                                    $amazon_authors['director'] = explode(',', $media_type_class->directors);
                                    unset($media_type_class->directors);
                                }
                                if(isset($media_type_class->producers)){
                                    $amazon_authors['producer'] = explode(',', $media_type_class->producers);
                                    unset($media_type_class->producers);
                                }
                                addPeople($media, $media_type_class, $amazon_authors);
                                array_push($infos, array($media->id, $media->media_type,
                                 $media_type_class->title, "OK"));
                            }
                        }
                    }
                }
                $media->checkin();
                $media_id = array_pop($bid);
            }
            $infos = array_reverse($infos);
            HTML_medialibrary::showInfoRefetchMedias($option, $infos, $wslist);
        }
    }
    function configure_save($option) {
        global $my, $medialibrary_configuration;
        global $mainframe;

        $supArr = array();
        $str = '';
        $supArr = mosGetParam($_POST, 'emedias_registrationlevel', 0);
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['emedias']['registrationlevel'] = $str;
        
        $str = '';
        $supArr = mosGetParam($_POST, 'reviews_registrationlevel', 0);
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['reviews']['registrationlevel'] = $str;
        
        $str = '';
        $supArr = mosGetParam($_POST, 'add_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['add']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'lendrequest_registrationlevel', 0);
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['lendrequest']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'price_registrationlevel', array() );
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['price']['registrationlevel'] = $str;
        //**********   begin add Advance search   *****************************
        $str = '';
        $supArr = mosGetParam($_POST, 'advsearch_registrationlevel', 0);
        //print_r($supArr);
        $str = implode(',', $supArr);
        $medialibrary_configuration['advsearch']['registrationlevel'] = $str;
        $medialibrary_configuration['advsearch']['show'] = mosGetParam($_POST, 'advsearch_show', 0);
        $str = '';
        $supArr = mosGetParam($_POST, 'search_field_registrationlevel', 0);
        $str = implode(',', $supArr);
        $medialibrary_configuration['search_field']['registrationlevel'] = $str;
        $medialibrary_configuration['search_field']['show'] = mosGetParam($_POST, 'search_field_show', 0);
        //*********   end add Advance search   *********
        $str = '';
        $supArr = mosGetParam($_POST, 'add_media_email_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['add_media_email']['registrationlevel'] = $str;
        $medialibrary_configuration['add_media_email']['show'] = mosGetParam($_POST, 'add_media_email_show', 0);
        //***********begin approve on add
        $medialibrary_configuration['approve_on_add']['show'] = mosGetParam($_POST, 'approve_on_add');
        $str = '';
        $supArr = mosGetParam($_POST, 'approve_on_add_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['approve_on_add']['registrationlevel'] = $str;
        //***********end approve on add
        //***********begin publish on add
        $medialibrary_configuration['publish_on_add']['show'] = mosGetParam($_POST, 'publish_on_add');
        $str = '';
        $supArr = mosGetParam($_POST, 'publish_on_add_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['publish_on_add']['registrationlevel'] = $str;
        //***********end publish on add
        $medialibrary_configuration['edit_someone_media']['show'] = mosGetParam($_POST, 'edit_someone_media');
        $str = '';
        $supArr = mosGetParam($_POST, 'edit_someone_media_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
         $medialibrary_configuration['edit_someone_media']['registrationlevel'] = $str;

        //begin approve on review
        $medialibrary_configuration['approve_review']['show'] = mosGetParam($_POST, 'approve_review');
        $str = '';
        $supArr = mosGetParam($_POST, 'approve_review_registrationlevel', array() );
        for ($i = 0;$i < count($supArr);$i++) $str.= $supArr[$i] . ',';
        $str = substr($str, 0, -1);
        $medialibrary_configuration['approve_review']['registrationlevel'] = $str;
        //end approve on review
        //***********begin Owners list
        $medialibrary_configuration['ownerslist']['show'] = mosGetParam($_POST, 'ownerslist_show');
        $str = '';
        $supArr = mosGetParam($_POST, 'ownerslist_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['ownerslist']['registrationlevel'] = $str;
        //***********end Owners list
        //_____cb
        $str = '';
        $supArr = mosGetParam($_POST, 'cb_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['cb']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'cb_mymedia_registrationlevel',array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['cb_mymedia']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'cb_edit_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['cb_edit']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'cb_lend_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['cb_lend']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'cb_history_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['cb_history']['registrationlevel'] = $str;
        $medialibrary_configuration['cb']['show'] = mosGetParam($_POST, 'cb_show', 0);
        $medialibrary_configuration['cb_mymedia']['show'] = mosGetParam($_POST, 'cb_show_mymedia', 0);
        $medialibrary_configuration['cb_edit']['show'] = mosGetParam($_POST, 'cb_show_edit', 0);
        $medialibrary_configuration['cb_lend']['show'] = mosGetParam($_POST, 'cb_show_lend', 0);
        $medialibrary_configuration['cb_history']['show'] = mosGetParam($_POST, 'cb_show_history', 0);
        //___end cb
        //**********   begin add button 'buy now'   *****************************
        $str = '';
        $supArr = mosGetParam($_POST, 'buy_now_allow_categories', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['buy_now']['allow']['categories'] = $str;
        $medialibrary_configuration['buy_now']['show'] = mosGetParam($_POST, 'buy_now_show', 0);
        //*************   end add button 'buy now'   ***********************
        
        $medialibrary_configuration['reviews']['show'] = mosGetParam($_POST, 'reviews_show', 0); //front--1
        $medialibrary_configuration['add']['show'] = mosGetParam($_POST, 'add_show', 0); //front--1
        $medialibrary_configuration['lendstatus']['show'] = mosGetParam($_POST, 'lendstatus_show', 0); //front--3
        $medialibrary_configuration['emedias']['show'] = mosGetParam($_POST, 'emedias_show', 0); //front--5
        $medialibrary_configuration['price']['show'] = mosGetParam($_POST, 'price_show', 0); //front--6
        $medialibrary_configuration['foto']['high'] = mosGetParam($_POST, 'foto_high'); //front--7_high
        $medialibrary_configuration['foto']['width'] = mosGetParam($_POST, 'foto_width'); //front--7_width
        $medialibrary_configuration['page']['items'] = mosGetParam($_POST, 'page_items'); //front--8_page 
        $medialibrary_configuration['people']['items'] = mosGetParam($_POST, 'people_items'); //front--8_page
        $medialibrary_configuration['audio_player']['items'] = mosGetParam($_POST, 'audio_player_items');
         //front--8_page
        $medialibrary_configuration['audio_player']['skin'] = mosGetParam($_POST, 'audio_player_skin'); 
        //front--8_page
        $medialibrary_configuration['video_player']['items'] = mosGetParam($_POST, 'video_player_items');
         //front--8_page
        $medialibrary_configuration['video_player']['skin'] = mosGetParam($_POST, 'video_player_skin'); 
        //front--8_page
        $medialibrary_configuration['author_photo']['show'] = mosGetParam($_POST, 'author_photo_show');
        $medialibrary_configuration['foto']['high_author'] = mosGetParam($_POST, 'foto_high_author');
        $medialibrary_configuration['foto']['width_author'] = mosGetParam($_POST, 'foto_width_author');
        $medialibrary_configuration['license']['show'] = mosGetParam($_POST, 'license_show');
        //$medialibrary_configuration['license']['text']=str_replace("\\","",$_POST['LicenseField']);
        //add for show in category picture
        $medialibrary_configuration['cat_pic']['show'] = mosGetParam($_POST, 'cat_pic_show');
        //add for show subcategory
        $medialibrary_configuration['subcategory']['show'] = mosGetParam($_POST, 'subcategory_show');
        //view type
        $medialibrary_configuration['show_search_media'] = mosGetParam($_POST, 'show_search_media');
        $medialibrary_configuration['view_type'] = mosGetParam($_POST, 'view_type');
        $medialibrary_configuration['view_type_single'] = mosGetParam($_POST, 'view_type_single');
        $medialibrary_configuration['view_type_video'] = mosGetParam($_POST, 'view_type_video');
        $medialibrary_configuration['view_type_music'] = mosGetParam($_POST, 'view_type_music');
        $medialibrary_configuration['view_type_game'] = mosGetParam($_POST, 'view_type_game');
        $medialibrary_configuration['view_type_book'] = mosGetParam($_POST, 'view_type_book');
        $medialibrary_configuration['view_type_all'] = mosGetParam($_POST, 'view_type_all');
        $medialibrary_configuration['view_type_display_book'] = mosGetParam($_POST, 'view_type_display_book');
        $medialibrary_configuration['view_type_display_video'] = mosGetParam($_POST, 'view_type_display_video');
        $medialibrary_configuration['view_type_display_music'] = mosGetParam($_POST, 'view_type_display_music');
        $medialibrary_configuration['view_type_display_game'] = mosGetParam($_POST, 'view_type_display_game');

        $medialibrary_configuration['all_categories'] = mosGetParam($_POST, 'all_categories');

        $str = '';
        $supArr = mosGetParam($_POST, 'litpage_registrationlevel', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['litpage']['registrationlevel'] = $str;
        $str = '';
        $supArr = mosGetParam($_POST, 'litpage_registrationlevel_author', array());
        for ($i = 0;$i < count($supArr);$i++) {
            $str.= $supArr[$i] . ',';
        }
        $str = substr($str, 0, -1);
        $medialibrary_configuration['litpage_author']['registrationlevel'] = $str;
        $medialibrary_configuration['litpage']['show'] = mosGetParam($_POST, 'litpage_show', 0);
        $medialibrary_configuration['litpage_author']['show'] = mosGetParam($_POST, 'litpage_show_author', 0);
            //add date
        //$medialibrary_configuration['date_format'] = mosGetParam($_POST, 'date_format');
        //$medialibrary_configuration['datetime_format'] = mosGetParam($_POST, 'datetime_format');

        //**********   begin add merge description  *****************************
        $str = '';
        $supArr = mosGetParam($_POST, 'merge_description_registrationlevel', 0);
        $str = implode(',', $supArr);
        $medialibrary_configuration['merge_description']['registrationlevel'] = $str;
        $medialibrary_configuration['merge_description']['use'] = mosGetParam($_POST, 'merge_description_use', 0);
        //*********   end add merge description   *********
        $medialibrary_configuration['review_email']['address'] = mosGetParam($_POST, 'review_email_address', "");
         //back--1
        $medialibrary_configuration['lendrequest_email']['address'] = mosGetParam($_POST, 
                'lendrequest_email_address', "");
        $medialibrary_configuration['lend_answer'] = mosGetParam($_POST, 'lend_answer', 0);
        //$medialibrary_configuration['lend_form'] = str_replace("\\", "", $_REQUEST['lend_form']);
        $medialibrary_configuration['add_media_email']['address'] = mosGetParam($_POST, 
            'add_media_email_address', "");
        $medialibrary_configuration['mediaid']['auto-increment']['boolean'] = mosGetParam($_POST, 
            'mediaid_auto_increment_boolean', 0);
        $medialibrary_configuration['fetchImages']['boolean'] = mosGetParam($_POST, 'fetchImages_boolean', 0);
        $medialibrary_configuration['fetchImages']['location'] =
         mosGetParam($_POST, 'fetchImages_location', "/components/com_medialibrary/covers/");

        $medialibrary_configuration['emedias']['allow'] = mosGetParam($_POST, 'emedias_allow', 0);
        $medialibrary_configuration['emedias']['location'] = mosGetParam($_POST, 'emedias_location',
         "/components/com_medialibrary/ebooks/");
        $medialibrary_configuration['videos_tracks']['allow'] = mosGetParam($_POST, 'videos_tracks_allow', 0);
        $medialibrary_configuration['videos']['location'] = mosGetParam($_POST, 'videos_location',
         "/components/com_medialibrary/media/video/");
        $medialibrary_configuration['tracks']['location'] = mosGetParam($_POST, 'track_location',
         "/components/com_medialibrary/media/track/");
        $medialibrary_configuration['audios']['allow'] = mosGetParam($_POST, 'audios_allow', 0);
        $medialibrary_configuration['audios']['location'] = mosGetParam($_POST, 'audios_location',
         "/components/com_medialibrary/media/audio/");

        $medialibrary_configuration['ws']['amazon']['tag'] = mosGetParam($_POST, 'ws_amazon_tag', "gerdsaurer-20");
        $medialibrary_configuration['ws']['amazon']['devtag'] = mosGetParam($_POST, 'ws_amazon_devtag');
        $medialibrary_configuration['ws']['amazon']['secret_key'] = mosGetParam($_POST, 'ws_amazon_secret_key');
        $medialibrary_configuration['editmedia']['check']['isbn_asin'] =
         mosGetParam($_POST, 'editmedia_check_isbn_asin', 0); //back--7
        $medialibrary_configuration['editmedia']['default']['host'] = mosGetParam($_POST, 
            'editmedia_default_host', 0);
        $medialibrary_configuration['editmedia']['default']['lang'] = mosGetParam($_POST, 
            'editmedia_default_lang', 0);
        $medialibrary_configuration['proxy_server']['address'] = mosGetParam($_POST, 'proxy_server_adress', "");
        $medialibrary_configuration['port_proxy_server']['address'] = mosGetParam($_POST, 
            'port_proxy_server_adress', "");
        $medialibrary_configuration['login_proxy_server']['address'] = mosGetParam($_POST, 
            'login_proxy_server_adress', "");
        $medialibrary_configuration['password_proxy_server']['address'] = mosGetParam($_POST, 
            'password_proxy_server_adress', "");
        $medialibrary_configuration['lendrequest_admin_decline_accept'] = mosGetParam($_POST, 
            'lendrequest_admin_decline_accept', "");
        $medialibrary_configuration['update'] = mosGetParam($_POST, 'update', "no");
        // $medialibrary_configuration['currency'] = $_POST['currency'];
        $medialibrary_configuration['price_format'] = $_POST['patern'];
        $medialibrary_configuration['price_unit_show'] = $_POST['price_unit_show'];
        //add date
        $medialibrary_configuration['date_format'] = mosGetParam($_POST, 'date_format');
        $medialibrary_configuration['datetime_format'] = mosGetParam($_POST, 'datetime_format');
        $medialibrary_configuration['allowed_exts'] = mosGetParam($_POST, 'allowed_exts', "");
        $medialibrary_configuration['allowed_exts_img'] = mosGetParam($_POST, 'allowed_exts_img', "");

        $medialibrary_configuration['allowed_exts_video'] = mosGetParam($_POST, 'allowed_exts_video', "");
        $medialibrary_configuration['allowed_exts_audio'] = mosGetParam($_POST, 'allowed_exts_audio', "");
        $medialibrary_configuration['allowed_exts_track'] = mosGetParam($_POST, 'allowed_exts_track', "");

        mosMedialibraryOthers::setParams();
        configure($option);
    }
    
    function configure($option) {
        global $my, $medialibrary_configuration, $acl, $database;
        global $mosConfig_absolute_path;
        $yesno[] = mosHTML::makeOption('1', _MEDIALIBRARY_YES);
        $yesno[] = mosHTML::makeOption('0', _MEDIALIBRARY_NO);
        $gtree[] = mosHTML::makeOption('-2', 'Everyone');
        $gtree = get_group_children_tree_ml();
        $lists = array();

        $f = array();
        $s = explode(',', $medialibrary_configuration['reviews']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['reviews']['show'] = mosHTML::RadioList($yesno, 'reviews_show',
         'class="inputbox"', $medialibrary_configuration['reviews']['show'], 'value', 'text');
        $lists['reviews']['registrationlevel'] = mosHTML::selectList($gtree,
         'reviews_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);

        $f = array();
        $s = explode(',', $medialibrary_configuration['lendrequest']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['lendstatus']['show'] = mosHTML::RadioList($yesno, 'lendstatus_show',
         'class="inputbox"', $medialibrary_configuration['lendstatus']['show'], 'value', 'text');
        $lists['lendrequest']['registrationlevel'] = mosHTML::selectList($gtree,
         'lendrequest_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        $f = array();
        $s = explode(',', $medialibrary_configuration['emedias']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['emedias']['registrationlevel'] = mosHTML::selectList($gtree, 'emedias_registrationlevel[]',
         'size="4" multiple="multiple"', 'value', 'text', $f);
        $lists['emedias']['show'] = mosHTML::RadioList($yesno, 'emedias_show', 'class="inputbox"',
         $medialibrary_configuration['emedias']['show'], 'value', 'text');
        $f = array();
        $s = explode(',', $medialibrary_configuration['price']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['price']['show'] = mosHTML::RadioList($yesno, 'price_show', 'class="inputbox"',
         $medialibrary_configuration['price']['show'], 'value', 'text');

        $f = array();
        $s = explode(',', $medialibrary_configuration['search_field']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['search_field']['show'] = mosHTML::RadioList($yesno, 'search_field_show',
         'class="inputbox"', $medialibrary_configuration['search_field']['show'], 'value', 'text');
        $lists['search_field']['registrationlevel'] = mosHTML::selectList($gtree,
         'search_field_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        $f = array();
        $s = explode(',', $medialibrary_configuration['advsearch']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['advsearch']['show'] = mosHTML::RadioList($yesno, 'advsearch_show',
         'class="inputbox"', $medialibrary_configuration['advsearch']['show'], 'value', 'text');
        $lists['advsearch']['registrationlevel'] = mosHTML::selectList($gtree,
         'advsearch_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        
        //******   begin approve_on_add  *****
        $f = array();
        $s = explode(',', $medialibrary_configuration['approve_on_add']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['approve_on_add']['show'] = mosHTML::RadioList($yesno, 'approve_on_add',
         'class="inputbox"', $medialibrary_configuration['approve_on_add']['show'], 'value', 'text');
        $lists['approve_on_add']['registrationlevel'] = mosHTML::selectList($gtree,
         'approve_on_add_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        //*******   end approve_on_add   *******
        //    //******   begin publish_on_add  *****
        $f = array();
        $s = explode(',', $medialibrary_configuration['publish_on_add']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['publish_on_add']['show'] = mosHTML::RadioList($yesno, 'publish_on_add',
         'class="inputbox"', $medialibrary_configuration['publish_on_add']['show'], 'value', 'text');
        $lists['publish_on_add']['registrationlevel'] = mosHTML::selectList($gtree,
         'publish_on_add_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);

        $f = array();
        $s = explode(',', $medialibrary_configuration['edit_someone_media']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['edit_someone_media']['show'] = mosHTML::RadioList($yesno, 'edit_someone_media',
         'class="inputbox"', $medialibrary_configuration['edit_someone_media']['show'], 'value', 'text');
        $lists['edit_someone_media']['registrationlevel'] = mosHTML::selectList($gtree,
         'edit_someone_media_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        //*******   end publish_on_add   *******
        //******   begin approve_review  *****
        $f = array();
        $s = explode(',', $medialibrary_configuration['approve_review']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['approve_review']['show'] = mosHTML::RadioList($yesno, 'approve_review', 'class="inputbox"', 
            $medialibrary_configuration['approve_review']['show'], 'value', 'text');
        $lists['approve_review']['registrationlevel'] =
         mosHTML::selectList($gtree, 'approve_review_registrationlevel[]',
          'size="4" multiple="multiple"', 'value', 'text', $f);
        //*******   end approve_review   *******
        //********   begin add button 'buy now'   ************************
        $ctree[] = mosHTML::makeOption('-2', 'All Categories');
        $id = 0;
        $list = CAT_Utils::categoryArray();
        $cat = new mainMedialibraryCategories($database); //for 1.6
        $cat->load($id);
        $this_treename = '';
        foreach($list as $item) {
            if ($this_treename) {
                if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                }
            } else {
                if ($item->id != $cat->id) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                } else {
                    $this_treename = "$item->treename/";
                }
            }
        }
        if (count($list) > 0) $ctree = array_merge($ctree, $options);
        $f = array();
        $s = explode(',', $medialibrary_configuration['buy_now']['allow']['categories']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['buy_now']['show'] = mosHTML::RadioList($yesno, 'buy_now_show',
         'class="inputbox"', $medialibrary_configuration['buy_now']['show'], 'value', 'text');
        $lists['buy_now']['allow']['categories'] = mosHTML::selectList($ctree,
         'buy_now_allow_categories[]', 'size="4" multiple="multiple"', 'value', 'text', $f);
        //*************   end add button 'buy now'   ************************
        
        $lists['foto']['high'] = '<input type="text" name="foto_high" value="' .
         $medialibrary_configuration['foto']['high'] . '" class="inputbox" size="4" maxlength="4" title="" />';
        $lists['foto']['width'] = '<input type="text" name="foto_width" value="' .
         $medialibrary_configuration['foto']['width'] . '" class="inputbox" size="4" maxlength="4" title="" />';
        $lists['page']['items'] = '<input type="text" name="page_items" value="' .
         $medialibrary_configuration['page']['items'] . '" class="inputbox" size="2" maxlength="2" title="" />';
        $lists['people']['items'] = '<input type="text" name="people_items" value="' .
         $medialibrary_configuration['people']['items'] . '" class="inputbox" size="2" maxlength="2" title="" />';

        $lists['audio_player']['items'] = '<input type="text" name="audio_player_items" value="' .
         $medialibrary_configuration['audio_player']['items'] 
         . '" class="inputbox" size="2" maxlength="2" title="" />';
        $skins = array(array('text'=>'blue monday', 'value'=>'blue.monday', 'disable'=>''),
                    array('text' => 'pink flag', 'value' => 'pink.flag', 'disable' => ''));
        $lists['audio_player']['skin'] = mosHTML::selectList($skins,
         'audio_player_skin', 'size="2"', 'value', 'text', $medialibrary_configuration['audio_player']['skin']);

        $lists['video_player']['items'] = '<input type="text" name="video_player_items" value="' .
         $medialibrary_configuration['video_player']['items'] 
            . '" class="inputbox" size="2" maxlength="2" title="" />';
        $skins = array(array('text'=>'blue monday', 'value'=>'blue.monday', 'disable'=>''),
                    array('text' => 'pink flag', 'value' => 'pink.flag', 'disable' => ''));
        $lists['video_player']['skin'] = mosHTML::selectList($skins,
         'video_player_skin', 'size="2"', 'value', 'text', $medialibrary_configuration['video_player']['skin']);

        $lists['license']['show'] = mosHTML::RadioList($yesno, 'license_show',
         'class="inputbox"', $medialibrary_configuration['license']['show'], 'value', 'text');
        $txt = $medialibrary_configuration['license']['text'];
        $lists['foto']['high_author'] = '<input type="text" name="foto_high_author" value="' .   
                    $medialibrary_configuration['foto']['high_author'] 
                    . '" class="inputbox" size="4" maxlength="4" title="" />';
        $lists['foto']['width_author'] = '<input type="text" name="foto_width_author" value="' .  
                     $medialibrary_configuration['foto']['width_author'] 
                    . '" class="inputbox" size="4" maxlength="4" title="" />';
        $lists['author_photo']['show'] = mosHTML::RadioList($yesno, 'author_photo_show', 'class="inputbox"',   
                    $medialibrary_configuration['author_photo']['show'], 'value', 'text');
        $txt = $medialibrary_configuration['author_photo']['show'];

        //add for show in category picture
        $lists['cat_pic']['show'] = mosHTML::RadioList($yesno, 'cat_pic_show',
         'class="inputbox"', $medialibrary_configuration['cat_pic']['show'], 'value', 'text');
        //add for show subcategory
        $lists['subcategory']['show'] = mosHTML::RadioList($yesno, 'subcategory_show',
         'class="inputbox"', $medialibrary_configuration['subcategory']['show'], 'value', 'text');
        // show_search_media
        $component_path = JPath::clean(JPATH_SITE . '/components/com_medialibrary/views/show_search_media/tmpl');
        $component_layouts = array();
        $options = array();
        if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, 
                '^[^_]*\.php$', false, true))) {
            foreach($component_layouts as $i => $file) {
                $select_file_name = pathinfo($file);
                $select_file_name = $select_file_name['filename'];
                $show_search_media[] = JHtml::_('select.option', $select_file_name, $select_file_name);
            }
        }
        $lists['show_search_media'] = mosHTML::selectList($show_search_media,
         'show_search_media', 'size="1" ', 'value', 'text', $medialibrary_configuration['show_search_media']);
        //view type
        $component_path = JPath::clean(JPATH_SITE .
         '/components/com_medialibrary/views/alonecategory/tmpl');
        $component_layouts = array();
        $options = array();
        if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, 
                '^[^_]*\.php$', false, true))) {
            foreach($component_layouts as $i => $file) {
                $select_file_name = pathinfo($file);
                $select_file_name = $select_file_name['filename'];
                $view_type_single[] = JHtml::_('select.option', $select_file_name, $select_file_name);
            }
        }


        // ==========backend
        $lists['lend_form'] = $medialibrary_configuration['lend_form'];

        //********   begin add merge description   ************************
        $f = array();
        $s = explode(',', $medialibrary_configuration['merge_description']['registrationlevel']);
        for ($i = 0;$i < count($s);$i++) $f[] = mosHTML::makeOption($s[$i]);
        $lists['merge_description']['use'] = mosHTML::RadioList($yesno,
         'merge_description_use', 'class="inputbox"',
          $medialibrary_configuration['merge_description']['use'], 'value', 'text');
        $lists['merge_description']['registrationlevel'] =
         mosHTML::selectList($gtree, 'merge_description_registrationlevel[]',
          'size="4" multiple="multiple"', 'value', 'text', $f);
        //********   end add merge description  **********************
        $lists['fetchImages']['boolean'] = mosHTML::RadioList($yesno,
         'fetchImages_boolean', 'class="inputbox"',
          $medialibrary_configuration['fetchImages']['boolean'], 'value', 'text');
        $lists['fetchImages']['location'] = '<input type="text" name="fetchImages_location" value="' .
         $medialibrary_configuration['fetchImages']['location'] .
         '" readonly="true" class="inputbox" size="50" maxlength="50" title="" />';

        $lists['emedias']['allow'] = mosHTML::RadioList($yesno, 'emedias_allow', 'class="inputbox"',
         $medialibrary_configuration['emedias']['allow'], 'value', 'text');

        $lists['emedias']['location'] = '<input type="text" name="emedias_location" value="' .
         $medialibrary_configuration['emedias']['location'] .
         '" readonly="true" class="inputbox" size="50" maxlength="50" title="" />';



        $lists['videos_tracks']['allow'] = mosHTML::RadioList($yesno, 'videos_tracks_allow', 'class="inputbox"',
         $medialibrary_configuration['videos_tracks']['allow'], 'value', 'text');

       $lists['videos']['location'] = '<input type="text" name="videos_location" value="' .
         $medialibrary_configuration['videos']['location'] .
         '" readonly="true" class="inputbox" size="50" maxlength="50" title="" />';

        $lists['tracks']['location'] = '<input type="text" name="track_location" value="' .
         $medialibrary_configuration['tracks']['location'] .
         '" readonly="true" class="inputbox" size="50" maxlength="50" title="" />';
        $lists['audios']['allow'] = mosHTML::RadioList($yesno, 'audios_allow', 'class="inputbox"',
         $medialibrary_configuration['audios']['allow'], 'value', 'text');

        $lists['audios']['location'] = '<input type="text" name="audios_location" value="' .
         $medialibrary_configuration['audios']['location'] .
         '" readonly="true" class="inputbox" size="50" maxlength="50" title="" />';

        $lists['ws']['amazon']['tag'] = '<input type="text" name="ws_amazon_tag" value="' .
         $medialibrary_configuration['ws']['amazon']['tag'] .
         '" class="inputbox" size="50" maxlength="50" title="" />';
        $lists['ws']['amazon']['devtag'] = '<input type="text" name="ws_amazon_devtag" value="' .
         $medialibrary_configuration['ws']['amazon']['devtag'] .
         '" class="inputbox" size="50" maxlength="50" title="" />';
        $lists['ws']['amazon']['secret_key'] = '<input type="text" name="ws_amazon_secret_key" value="' .
         $medialibrary_configuration['ws']['amazon']['secret_key'] .
         '" class="inputbox" size="50" maxlength="50" title="" />';
        @$lists['editmedia']['check']['isbn_asin'] = mosHTML::RadioList($yesno,
         'editmedia_check_isbn_asin', 'class="inputbox"',
          $medialibrary_configuration['editmedia']['check']['isbn_asin'], 'value', 'text'); //back--7
        /////////////Proxy Relase
        $lists['proxy_server']['address'] = '<input type="text" name="proxy_server_adress" value="' .
          $medialibrary_configuration['proxy_server']['address'] .
         '"class="inputbox" size="50" maxlength="50" title="" />';
        $lists['port_proxy_server']['address'] = '<input type="text" name="port_proxy_server_adress" value="' .
         $medialibrary_configuration['port_proxy_server']['address'] .
         '"class="inputbox" size="50" maxlength="50" title="" />';
        $lists['login_proxy_server']['address'] = '<input type="text" name="login_proxy_server_adress" value="' .
         $medialibrary_configuration['login_proxy_server']['address'] .
         '"class="inputbox" size="50" maxlength="50" title="" />';
        $lists['password_proxy_server']['address'] =
         '<input type="text" name="password_proxy_server_adress" value="' .
         $medialibrary_configuration['password_proxy_server']['address'] .
         '"class="inputbox" size="50" maxlength="50" title="" />';
        //get language List
        $retVal1 = mosMedialibraryOthers::getLanguageArray();
        $lang = null;
        for ($i = 0, $n = count($retVal1);$i < $n;$i++) {
            $help = $retVal1[$i];
            $lang[] = mosHTML::makeOption($help[0], $help[1]);
        }
        $lists['editmedia']['default']['lang'] = mosHTML::selectList($lang,
         'editmedia_default_lang', 'class="inputbox" size="1"', 'value', 'text',
          $medialibrary_configuration['editmedia']['default']['lang']);
        //get host List
        $retVal = mosMedialibraryWS::getArray();
        $ws = null;
        for ($i = 0, $n = count($retVal);$i < $n;$i++) {
            $help = $retVal[$i];
            $ws[] = mosHTML::makeOption($help[0], $help[1]);
        }
       
        $lists['lendrequest_admin_decline_accept'] = mosHTML::RadioList($yesno,
         'lendrequest_admin_decline_accept', 'class="inputbox"',
          $medialibrary_configuration['lendrequest_admin_decline_accept'], 'value', 'text');
        $lists['update'] = mosHTML::RadioList($yesno, 'update', 'class="inputbox"',
         $medialibrary_configuration['update'], 'value', 'text');

        $lists['currency'] = '<input type="text" name="currency" value="' .
         $medialibrary_configuration['currency'] . '" class="inputbox" size="50" maxlength="500" title=""/>';
        //show sale_separator
        $lists['sale_separator'] = mosHTML::RadioList($yesno, 'sale_separator', 'class="inputbox"',  
                     $medialibrary_configuration['sale_separator'], 'value', 'text');

        $lists['date_format'] = '<input type="text" name="date_format" value="' .
         $medialibrary_configuration['date_format'] . '" class="inputbox"  title="" />';
        $lists['datetime_format'] = '<input type="text" name="datetime_format" value="' .
         $medialibrary_configuration['datetime_format'] . '" class="inputbox" title="" />';
        $money_ditlimer = array();
        $money_ditlimer[] = JHtml::_('select.option', ".", "Point (12.134.123,12)");
        $money_ditlimer[] = JHtml::_('select.option', ",", "Comma (12,134,123.12)");
        $money_ditlimer[] = JHtml::_('select.option', "space", "Space (12 134 123,12)");
        $money_ditlimer[] = JHtml::_('select.option', "other", "Youre ditlimer: ");
        $price_unit_show = array();
        $price_unit_show[] = mosHTML::makeOption('1', _MEDIALIBRARY_PRICE_UNIT_SHOW_AFTER);
        $price_unit_show[] = mosHTML::makeOption('0', _MEDIALIBRARY_PRICE_UNIT_SHOW_BEFORE);
        $selecter = '';
        switch ($medialibrary_configuration['price_format']) {
            case '.':
                $selecter = '.';
            break;
            case ',':
                $selecter = ',';
            break;
            case '&nbsp;':
                $selecter = 'space';
            break;
            default:
                $selecter = 'other';
        }

        $lists['allowed_exts'] = '<input type="text" name="allowed_exts" value="' .
         $medialibrary_configuration['allowed_exts'] . '" class="inputbox" size="50" maxlength="1500" title=""/>';
        $lists['allowed_exts_img'] = '<input type="text" name="allowed_exts_img" value="' .
        $medialibrary_configuration['allowed_exts_img'].'" class="inputbox" size="50" maxlength="1500" title=""/>';



        $lists['allowed_exts_video'] = '<input type="text" name="allowed_exts_video" value="' .
         $medialibrary_configuration['allowed_exts_video'] 
         . '" class="inputbox" size="50" maxlength="1500" title=""/>';
        $lists['allowed_exts_audio'] = '<input type="text" name="allowed_exts_audio" value="' .
         $medialibrary_configuration['allowed_exts_audio'] 
         . '" class="inputbox" size="50" maxlength="1500" title=""/>';
        $lists['allowed_exts_track'] = '<input type="text" name="allowed_exts_track" value="' .
         $medialibrary_configuration['allowed_exts_track'] 
         . '" class="inputbox" size="50" maxlength="1500" title=""/>';




       $lists['price_unit_show'] = mosHTML::RadioList($price_unit_show, 'price_unit_show',
         'class="inputbox"', $medialibrary_configuration['price_unit_show'], 'value', 'text');
        $lists['money_ditlimer'] = mosHTML::selectList($money_ditlimer, 'money_select',
         'size="1"  onchange="set_pricetype(this)"', 'value', 'text', $selecter);
        $lists['patern'] = '<input id="patt" type="hidden" readonly="true" value="' .
         $medialibrary_configuration['price_format'] . '" name="patern" size="2"/>';
         
        HTML_medialibrary::showConfiguration($lists, $option, $txt);
    }
    function cutSlash($S) {
        $S2 = '';
        for ($i = 0;$i < strlen($S);$i++) {
            if ($S[$i] != '\\') {
                $S2.= $S[$i];
            } else {
                $i++;
                if ($S[$i] == '"') {
                    $S2.= '&#34';
                } else {
                    $S2.= $S[$i];
                }
            }
        }
        return $S2;
    }
    //****************   begin for manage reviews   *******************
    function manage_review_s($option, $sorting) {
        global $database, $mainframe, $mosConfig_list_limit;
        global $table_prefix; // for J 1.6
        $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
        $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
        $database->setQuery("SELECT count(*) FROM #__medialibrary_review;");
        $total = $database->loadResult();
        echo $database->getErrorMsg();
        $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
        //********************   begin request for reviews manager   **********************
        //if for sorting
        if ($sorting != "") {
            $query = "SELECT r.id as review_id, r.title as title_review, r.comment," .
             "r.date,r.rating, r.published, library.id as fk_mediaid, library.media_type, library.media_id," .
             " c.title  as title_catigory, " . " e.user_name, " . " other_table.title as media_title," .
             " other_table.isbn " .
             " FROM {$table_prefix}medialibrary_review as r, {$table_prefix}medialibrary_main_categories as c, " .
             " ( SELECT DISTINCT d.name as user_name, a.fk_userid " .
             "    FROM {$table_prefix}medialibrary_review as a, {$table_prefix}users as d " .
             " WHERE d.id = a.fk_userid " . "  union all " .
             "   SELECT DISTINCT 'anonymous' as user_name, a.fk_userid " .
             "    FROM {$table_prefix}medialibrary_review as a  WHERE a.fk_userid = 0) as e, " .
             " {$table_prefix}medialibrary AS library " .
             " LEFT JOIN {$table_prefix}medialibrary_categories AS mc ON mc.mediaid = library.id " .
             " LEFT JOIN (SELECT id,title,rating,asin as isbn,'game' as type 
                    FROM {$table_prefix}medialibrary_game " .
             " UNION all SELECT id,title,rating,asin as isbn,'music' as type 
                    FROM {$table_prefix}medialibrary_music " .
             " UNION all SELECT id,title,rating,isbn,'book' as type FROM {$table_prefix}medialibrary_book " .
             " UNION all SELECT id,title,rating,asin as isbn,'video' as type 
                    FROM {$table_prefix}medialibrary_video) " .
             " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
             " WHERE r.fk_mediaid = library.id AND mc.catid = c.id " .
             " AND r.fk_userid = e.fk_userid ORDER by " . $sorting . " 
                    LIMIT $pageNav->limitstart,$pageNav->limit;";
            $database->setQuery($query);
            $reviews = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
        } else {
            $query = "SELECT r.id as review_id, r.title as title_review, r.comment,r.date,r.rating, r.published,".
             " library.id as fk_mediaid, library.media_type, library.media_id," .
             " c.title   as title_catigory, " . " e.user_name, " .
             " other_table.title as media_title, " . " other_table.isbn " .
             " FROM {$table_prefix}medialibrary_review as r, {$table_prefix}medialibrary_main_categories as c, " .
              " ( SELECT DISTINCT d.name as user_name, a.fk_userid " .
              " FROM {$table_prefix}medialibrary_review as a, {$table_prefix}users as d WHERE d.id = a.fk_userid ".
              "  union all " . "   SELECT DISTINCT 'anonymous' as user_name, a.fk_userid " .
              "    FROM {$table_prefix}medialibrary_review as a  WHERE a.fk_userid = 0) as e, " .
              " {$table_prefix}medialibrary AS library " .
              " LEFT JOIN {$table_prefix}medialibrary_categories AS mc ON mc.mediaid = library.id " .
              " LEFT JOIN (SELECT id,title,rating,asin as isbn,'game' as type 
                FROM {$table_prefix}medialibrary_game " .
              " UNION all SELECT id,title,rating,asin as isbn,'music' as type 
                FROM {$table_prefix}medialibrary_music " .
              " UNION all SELECT id,title,rating,isbn,'book' as type FROM {$table_prefix}medialibrary_book " .
              " UNION all SELECT id,title,rating,asin as isbn,'video' as type 
                FROM {$table_prefix}medialibrary_video) " .
              " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
              " WHERE r.fk_mediaid = library.id AND mc.catid = c.id " 
                . " AND r.fk_userid = e.fk_userid ORDER by date " .
              " LIMIT $pageNav->limitstart,$pageNav->limit;";
        }
        $database->setQuery($query);
        $reviews = $database->loadObjectList();
        //**************   end request for reviews manager   ***************************
        //print_r($reviews); exit;
        HTML_medialibrary::showManageReviews($option, $pageNav, $reviews);
    }
    function publish_manage_review($bid, $publish, $option) {
        global $database;

         $countInfo = count ($bid);
        $whenThen = '';
        for ($i = 0; $i < $countInfo; $i++) {
                $bids[$i] = explode(',', $bid[$i]);
                $id = $bids[$i][0];
                $whenThen .= "  WHEN id=$id THEN '$publish' ";
        }
        $query = "UPDATE #__medialibrary_review SET published= CASE $whenThen ELSE published END ";

        echo __FILE__.": ".__LINE__."<br />";
echo "qwerty1<pre>";
print_r($id);
print_r($query);
echo "</pre>qwerty11";//exit;


        $database->setQuery($query);


        //$database->setQuery("UPDATE #__medialibrary_review SET published = $publish WHERE id  = $bid ");
        if (!$database->query()) {
            echo "<script> alert(\"" . $database->getErrorMsg() . "\"); window.history.go(-1); </script>\n";
            exit();
        }
        mosRedirect("index.php?option=$option&task=manage_review");
    }
    //*********************   end for manage reviews   ****************************

    function lend($option, $bid) {
        global $database, $my;
    if (!is_array($bid) || count($bid) !== 1) {
        echo "<script> alert('" . _MEDIALIBRARY_SELECT_ONE_ITEM_TO_LEND . "'); window.history.go(-1);</script>\n";
        exit;
    }
        $bids = implode(',', $bid);
        $bids = explode(',', $bids);
        $selectstring = "SELECT library.id, library.media_type, library.media_id," .
         "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
         " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
         " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
         " l.user_email AS user_email, l.fk_userid as fk_userid ," .
         " other_table.id as media_type_id,  other_table.title as title  " .
         " FROM #__medialibrary AS library " .
         " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
         " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
         " LEFT JOIN #__medialibrary_lend AS l ON l.id = library.fk_lendid" .
         " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
         " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
         " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
         " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
         " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
         " WHERE library.id = $bids[0]";
        $database->setQuery($selectstring);
        if (!$database->query()) {
            echo "<script> alert('" . addslashes($database->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        $medias = $database->loadObject();

        $bids_assoc = getAssociatMedias($bids[0]);
        $medias_assoc[] = $medias;
        if($bids_assoc) {
            $selectstring = "SELECT library.id, library.media_type, library.media_id," .
            "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
            " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
            " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
            " l.user_email AS user_email, l.fk_userid as fk_userid ," .
            " other_table.id as media_type_id,  other_table.title as title  " .
            " FROM #__medialibrary AS library " .
            " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
            " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
            " LEFT JOIN #__medialibrary_lend AS l ON l.id = library.fk_lendid" .
            " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
            " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
            " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
            " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
            " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
            " WHERE library.id in (" . $bids_assoc . ")";
            $database->setQuery($selectstring);
            $medias_assoc = $database->loadObjectList();
        }

        // get list of categories
        $userlist[] = mosHTML::makeOption('-1', '----------');
        $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
        $userlist = array_merge($userlist, $database->loadObjectList());
        $usermenu = mosHTML::selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
        HTML_medialibrary::showLendMedias($option,$medias,@$medias_assoc,$usermenu,"lend");
    }

    function lend_return($option, $bid) {
        global $database, $my;
        if (!is_array($bid) || count($bid) !== 1) {
            echo "<script> alert('" . _MEDIALIBRARY_SELECT_ONE_ITEM_TO_LEND 
                . "'); window.history.go(-1);</script>\n";
            exit;
        }
        $bids = implode(',', $bid);
        $bids = explode(',', $bids);

          $select = "SELECT allmedia.id, allmedia.title, allmedia.mediaid, l.id AS lid, l.fk_userid,".
            " m.id AS mainid, m.media_type, cc.name AS category, l.lend_from AS lend_from, " .
              "l.lend_return AS lend_return, l.lend_until AS lend_until, " .
              "l.user_name AS user_name, l.user_email AS user_email, u.name " .
            "\nFROM #__medialibrary AS m" .
            "\nLEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id" .
            "\nLEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid" .
              "\nLEFT JOIN #__medialibrary_lend AS l ON l.fk_mediaid = m.id" .
              "\nLEFT JOIN #__users AS u ON l.fk_userid = u.id" .
                "\nLEFT JOIN (SELECT id, title, game_id AS mediaid, 'game' AS type FROM #__medialibrary_game " .
                "\nUNION all SELECT id, title, music_id AS mediaid, 'music' AS type FROM #__medialibrary_music " .
                "\nUNION all SELECT id, title, book_id AS mediaid, 'book' AS type FROM #__medialibrary_book " .
                  "\nUNION all SELECT id, title, video_id AS mediaid, 'video' AS type FROM #__medialibrary_video)".
                  "\n AS allmedia ON allmedia.id = m.media_id AND allmedia.type = m.media_type" .
                  "\n WHERE l.fk_mediaid IN (" . $bids[0] . ")";
        $database->setQuery($select);
        $medias = $database->loadObject();



        if (!$database->query()) {
            echo "<script> alert('" . addslashes($database->getErrorMsg()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }

        $count = count($medias);
        for ($i = 0;$i < $count;$i++) {
            if ((($medias->lend_from) == '') && (($medias->lend_return) == '')) {
?>
       <script type = "text/JavaScript" language = "JavaScript">
       alert('You cannot return medias that were not lent out');
       window.history.go(-1);
       </script>
       <?php
                exit;
            }
        }
        $bids = implode(',', $bid);
        $bids = explode(',', $bids);
        $bids = getAssociatMedias($bids[0]);
        if($bids == ""){
          $bids = implode(',', $bid);
          $bids = explode(',', $bids);
          $bids = $bids[0];
        }
        $medias_lends_assoc = array();
        $title_assoc = array();
        if($bids) {
          $selectstring = "SELECT library.*," .
          "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
            " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
            " l.lend_until as lend_until, l.lend_return as lend_return, l.user_name as user_name ," .
              " l.user_email as user_email, l.fk_userid as fk_userid ," .
              " other_table.id as media_type_id,  other_table.title as title  " .
                " FROM #__medialibrary_lend AS l, #__medialibrary AS library " .
                " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
                  " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
                  " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
                    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
                    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
                      " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
                      " AS other_table ON other_table.id = library.media_id and 
                            other_table.type = library.media_type" .
                        " WHERE library.id in (" . $bids . ") and l.fk_mediaid = library.id " ;
          $database->setQuery($selectstring);
          $medias_lends_assoc = $database->loadObjectList();

		  if (isset($medias_lends_assoc)) {

		    for ($i = 0; $i < count($medias_lends_assoc); $i++) {

		    $cutfrom = explode(' ', $medias_lends_assoc[$i]->lend_from);
		    $cutuntil = explode(' ', $medias_lends_assoc[$i]->lend_until);

		    $medias_lends_assoc[$i]->lend_from = $cutfrom[0];
		    $medias_lends_assoc[$i]->lend_until = $cutuntil[0];
		    }
    	}

          $selectstring = "SELECT DISTINCT other_table.id, other_table.title as title  " .
          " FROM #__medialibrary_lend AS l, #__medialibrary AS library " .
          " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
          " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
          " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
          " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
          " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type " .
          "\nWHERE library.id in ($bids)";
          $database->setQuery($selectstring);
          $title_assoc = $database->loadObjectList();

          $is_lend_out = false;
          for ($i = 0;$i < count($medias_lends_assoc);$i++) {
              if ($medias_lends_assoc[$i]->lend_from != '' && $medias_lends_assoc[$i]->lend_return == '') {
                  $is_lend_out = true;
                  break;
              }
          }
          if (!$is_lend_out) { ?>
              <script type = "text/JavaScript" language = "JavaScript">
                  alert("<?php echo _MEDIALIBRARY_CANNOT_RETURN_BOOK_THAT_WERE_NOT_LEND_OUT; ?>");
                  window.history.go(-1);
              </script>
              <?php
              exit;
          }
        //check lend_return == null count for all assosiate
        $ids = explode(',', $bids);
        $lend_count = - 1;
        $all_assosiate_lend = array();
        $count = count($ids);
        for ($i=0;$i<$count;$i++) {
            $query = "SELECT * FROM #__medialibrary_lend WHERE fk_mediaid = " . $ids[$i] .
                     " and lend_return is null ORDER BY lend_from";
            $database->setQuery($query);
            $all_assosiate_lend_item = $database->loadObjectList();
            if ($lend_count != - 1 && $lend_count != count($all_assosiate_lend_item)) {
?>
                <script type = "text/JavaScript" language = "JavaScript">
                    alert("<?php echo _MEDIALIBRARY_ERROR_IN_LEND_FOR_ASSOCIATED; ?>");
                    window.history.go(-1);
                </script>
                <?php
                exit;
            }
            $lend_count = count($all_assosiate_lend_item);
            $all_assosiate_lend[] = $all_assosiate_lend_item;
        }
    }	
		if (isset($all_assosiate_lend)) {
            for ($i = 0; $i < count($all_assosiate_lend[0]); $i++) {
        		$cutfrom = explode(' ', $all_assosiate_lend[0][$i]->lend_from);
                $cutuntil = explode(' ', $all_assosiate_lend[0][$i]->lend_until);

                $all_assosiate_lend[0][$i]->lend_from = $cutfrom[0];
                $all_assosiate_lend[0][$i]->lend_until = $cutuntil[0];
            }
        }

        // get list of users
        $userlist[] = mosHTML::makeOption('-1', '----------');
        $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
        $userlist = array_merge($userlist, $database->loadObjectList());
        $usermenu = mosHTML::selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
        HTML_medialibrary::editLendMedias($option, $medias, $medias_lends_assoc, $title_assoc, 
                $all_assosiate_lend, $usermenu, "lend_return");
   }

   
    function saveLend($option, $bids, $task = "") {
        global $database, $my;

		$userid = mosGetParam($_POST, 'userid');

        if ($userid == -1) {

            $user_name1 = protectInjectionWithoutQuote('user_name', '');
            $user_mail1 = protectInjectionWithoutQuote('user_email', '');
           
            if (empty($user_name1)) {
                    echo "<script> alert('" . _MEDIALIBRARY_INFOTEXT_JS_LEND_REQ_NAME . "'); 
                           window.history.go(-1);</script>\n";
                exit;
            }

            $mailvalid = strpos($user_mail1, '@');
            if (empty($user_mail1) || $mailvalid === false) {
                    echo "<script> alert('" . _MEDIALIBRARY_INFOTEXT_JS_LEND_REQ_EMAIL . "'); 
                           window.history.go(-1);</script>\n";
                exit;
            }
        }
        /*$checkMedia = mosGetParam($_POST, 'checkMedia');
        if ($checkMedia != "on") {
            echo "<script> alert('Select an item to  rent'); window.history.go(-1);</script>\n";
            exit;
        }*/
        $id = mosGetParam($_POST, 'id');
        $lend_from = mosGetParam($_POST, 'lend_from');
        $lend_until = mosGetParam($_POST, 'lend_until');
        if (!is_array($bids) || count($bids) < 1) {
            echo "<script> alert('Select an item to lend'); window.history.go(-1);</script>\n";
            exit;
        }
        $lend = new mosMediaLibrary_lend($database);
        if ($task == "edit_lend") $lend->load($bids[0]);
        $query = "SELECT * FROM #__medialibrary_lend where fk_mediaid = " . $id . " AND lend_return is NULL ";
        $database->setQuery($query);
        $rentTerm = $database->loadObjectList();
        /*if ($lend_from > $lend_until) {
            echo "<script> alert('" . $lend_from . " more then " . $lend_until . "'); window.history.go(-1); </script>\n";
            exit();
        }*/
        $lend_from = substr($lend_from, 0, 11);
        $lend_until = substr($lend_until, 0, 11);
        if (isset($rentTerm[0])) {
            for ($e = 0, $m = count($rentTerm);$e < $m;$e++) {
                if ($task == "edit_lend" && $bids[0] == $rentTerm[$e]->id) continue;
                $rentTerm[$e]->lend_from = substr($rentTerm[$e]->lend_from, 0, 10);
                $rentTerm[$e]->lend_until = substr($rentTerm[$e]->lend_until, 0, 10);
                
                if (($lend_from >= $rentTerm[$e]->lend_from && $lend_from <= $rentTerm[$e]->lend_until) || ($lend_from <= $rentTerm[$e]->lend_from && $lend_until >= $rentTerm[$e]->lend_until) || ($lend_until >= $rentTerm[$e]->lend_from && $lend_until <= $rentTerm[$e]->lend_until)) {
                    echo "<script> alert('Sorry, this item already rent out from " . $rentTerm[$e]->lend_from . " until " . $rentTerm[$e]->lend_until . "'); window.history.go(-1); </script>\n";
                    exit();
                }
            }
        } //if end
        
        $lend->lend_from = data_transformer(mosGetParam($_REQUEST, 'lend_from'), "to");
        if (mosGetParam($_POST, 'lend_until') != "") {
            $lend->lend_until = data_transformer(mosGetParam($_REQUEST, 'lend_until'), "to");
        } else {
            $lend->lend_until = null;
        }
        
        $lend->fk_mediaid = $id;


        $userid = mosGetParam($_POST, 'userid');

         
        
        if ($userid == "-1") {
            $lend->user_name = mosGetParam($_POST, 'user_name', '');
            $lend->user_email = mosGetParam($_POST, 'user_email', '');
        } else {
            $lend->getLendTo(intval($userid));
            $lend->fk_userid = $userid;
        }
        if (!$lend->check($lend)) {
            echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (!$lend->store()) {
            echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
            exit();
        }
        $lend->checkin();
        $media = new mosMediaLibrary($database);
        $media->load($id);
        $media->fk_lendid = $lend->id;
        $media->store();
        $media->checkin();
        mosRedirect("index.php?option=$option");
    }


   

    function saveLend_return($option, $lids) {
        global $database, $my;
        $id = mosGetParam($_POST, 'id');
        if (!is_array($lids) || count($lids) < 1) {
            echo "<script> alert('Select an item to return'); window.history.go(-1);</script>\n";
            exit;
        }
        for ($i = 0, $n = count($lids);$i < $n;$i++) {
            $lend = new mosMediaLibrary_lend($database);
            $lend->load($_REQUEST['mid'][$i]);
            if ($lend->lend_return != null) {
                echo "<script> alert('Already returned'); window.history.go(-1);</script>\n";
                exit;
            }
            $lend->lend_return = date("Y-m-d H:i:s"); //edit(add)
            $lend->store(); //edit(add)
            if (!$lend->check($lend)) {
                echo "<script> alert('" . addslashes($lend->getError()) . "'); window.history.go(-1); </script>\n";
                exit;
            }
            if (!$lend->store()) {
                echo "<script> alert('" . addcslashes($lend->getError()) 
                    . "'); window.history.go(-1); </script>\n";
                exit;
            }
            $is_update_media_lend = true;
            $book = new mosMediaLibrary($database);
            $book->load($id);
            $query = "SELECT * FROM #__medialibrary_lend WHERE fk_mediaid=" . $id . " AND lend_return IS NULL";
            $database->setQuery($query);
            $check_lends = $database->loadObjectList();
            if (isset($check_lends[0]->id)) {
                $book->fk_lendid = $check_lends[0]->id;
                $is_update_media_lend = false;
            } else {
                $book->fk_lendid = 0;
            }
            $book->store();
            $book->checkin();
        }
        mosRedirect("index.php?option=$option");
    }


function import($option) {
    global $database, $my;
    $file = file($_FILES['import_file']['tmp_name']);
    $catid = mosGetParam($_POST, 'import_catid');
    $type = mosGetParam($_POST, 'import_type');
    //***********************   begin add for XML format   ***************************************
    $type = mosGetParam($_POST, 'import_type');
    switch ($type) {
            //CSV=='1' XML=='2'

        case '1':
            $retVal = mosMediaLibraryImportExport::importMediasCSV($file, $catid);
            HTML_medialibrary::showImportResult($retVal, $option);
        break;
        default:
            $retVal = mosMediaLibraryImportExport::importMediasXML($_FILES['import_file']['tmp_name'], $catid);
            HTML_medialibrary::showImportResult($retVal, $option);
        break;
            //***********************   end add for XML format   ************************/

    }
}


function export($option) {
    global $database, $my, $mainframe, $medialibrary_configuration;
    $catid = mosGetParam($_POST, 'export_catid', 0);
    $type = mosGetParam($_POST, 'export_type', 0);
    //print_r($catid);print_r($type);exit;
    $where = array();
    $wherecatid = '';

    if ($catid > 0) {
        array_push($where, "ac.catid='$catid'");
        $wherecatid = " AND c.id ='$catid'";
    }

    $selectstring = "SELECT a.id FROM #__medialibrary AS a
            \nLEFT JOIN #__medialibrary_categories AS ac ON a.id = ac.mediaid" .
             (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
              "\nGROUP BY ac.mediaid" .
              "\nORDER BY a.ordering";
    $database->setQuery($selectstring);
    if (version_compare(JVERSION, "3.0.0", "lt")) {
        $mediaids = $database->loadResultArray();
    } else {
        $mediaids = $database->loadColumn();
    }
    echo $database->getErrorMsg();
    if ($database->getErrorNum()) {
        echo $database->stderr();
        return;
    }

    $medias = array();
    $count = 0;
    foreach($mediaids as $bid) {
        $media = new mosMediaLibrary($database);
        // load the row from the db table
        $media->load(intval($bid));
        $medias[$count] = $media;
        $count++;
    }

    
    
    $selectstring = "SELECT c.* FROM #__medialibrary_main_categories AS c" .
                    "\nWHERE c.section='com_medialibrary' " . $wherecatid .
                    "\nORDER BY c.parent_id";
    $database->setQuery($selectstring);
    $cats = $database->loadAssocList();

    $peoples = ExportPeople($database, $medias, $catid);
    $retVal = mosMedialibraryImportExport::exportMediasXML($medias, $cats);
    $retVal = substr($retVal, 0, -9)."\n". $peoples . "</data>\n";
    
    $type2 = 'xml';
    switch ($type) {
        case '1':
            $type2 = 'csv';
        break;
        case '2':
            $type2 = 'xml';
        break;
    }
    $InformationArray = mosMedialibraryImportExport::storeExportFile($retVal, $type2);
    HTML_medialibrary::showExportResult($InformationArray, $option);
}

function ExportPeople($database,$medias, $catid) {
        $peoples_for_media = array();
        foreach ($medias as $media) {
            if ($catid != 0){
                $query = "SELECT  fk_people_id FROM #__medialibrary_people_connect 
                          WHERE fk_media_id =  $media->id";
                $database->setQuery($query);
                $people_for_media = $database->loadResult();
                $peoples_for_media = array_merge($peoples_for_media, $people_for_media);
            }
        } 
        $query = "SELECT p.id FROM #__medialibrary_people AS p
           \nORDER BY p.id";
        $database->setQuery($query);
        $peoplesids = $database->loadResultArray();
        if (version_compare(JVERSION, '3.0', 'lt')) {
            $peoplesids = $database->loadResultArray();
        } else {
            $peoplesids = $database->loadColumn();
        }
        echo $database->getErrorMsg();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return;
        }
        $peoples = "<peoples>\n";
        foreach($peoplesids as $aid) {
            $tmp2 = new mosMedialibrary_people($database);
            if ($tmp2->load(intval($aid))) {
                $tmp2->description = str_replace('|', '-', $tmp2->description);
                $tmp2->description = str_replace('\n', ' ', $tmp2->description);
                $tmp2->description = str_replace('\r', ' ', $tmp2->description);
                $tmp2->auto_gener_description = str_replace('|', '-', $tmp2->auto_gener_description);
                $tmp2->auto_gener_description = str_replace('\n', ' ', $tmp2->auto_gener_description);
                $tmp2->auto_gener_description = str_replace('\r', ' ', $tmp2->auto_gener_description);
                if ($catid == 0){
                    $peoples.= $tmp2->toXML2();
                } else {
                    if (in_array($tmp2->id, $peoples_for_media)){
                    $peoples.= $tmp2->toXML2();
                }
                }
            }
            unset($tmp2);
        }
        $peoples.= "</peoples>\n";
        return $peoples;
    }
function importExport($option) {
    global $database;
    $q = "SELECT id AS value, title AS text
      FROM #__medialibrary_main_categories
      WHERE section = '" . $option . "'
      ORDER BY ordering"; // for J 1.6
    // get list of categories
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $database->setQuery($q); // for J 1.6
    $categories = array_merge($categories, $database->loadObjectList());
    if (count($categories) < 1) {
        mosRedirect("index.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
    }
    $impclist = mosHTML::selectList($categories, 'import_catid',
     'class="inputbox" size="1" id="import_catid"', 'value', 'text', 0);
    $expclist = mosHTML::selectList($categories, 'export_catid',
     'class="inputbox" size="1" id="export_catid"', 'value', 'text', 0);
    $params = array();
    $params['import']['category'] = $impclist;
    $params['export']['category'] = $expclist;
    $importtypes[0] = mosHTML::makeOption('0', _MEDIALIBRARY_ADMIN_PLEASE_SEL);
    //$importtypes[1] = mosHTML::makeOption('1', _MEDIALIBRARY_ADMIN_FORMAT_CSV);
    $importtypes[2] = mosHTML::makeOption('2', _MEDIALIBRARY_ADMIN_FORMAT_XML);
    $importtypes[3] = mosHTML::makeOption('3', _MEDIALIBRARY_ADMIN_ENTIRE_RECOVER);
    //$importtypes[4] = mosHTML :: makeOption('4', _MEDIALIBRARY_ADMIN_FULL_IMPORT);
    $params['import']['type'] = mosHTML::selectList($importtypes,
     'import_type', 'id="import_type" class="inputbox" size="1" onchange = "impch();"', 'value', 'text', 0);
    $exporttypes[0] = mosHTML::makeOption('0', _MEDIALIBRARY_ADMIN_PLEASE_SEL);
    //$exporttypes[1] = mosHTML::makeOption('1', _MEDIALIBRARY_ADMIN_FORMAT_CSV);
    $exporttypes[2] = mosHTML::makeOption('2', _MEDIALIBRARY_ADMIN_FORMAT_XML);
    $exporttypes[3] = mosHTML::makeOption('3', _MEDIALIBRARY_ADMIN_ENTIRE_BU);
    $params['export']['type'] = mosHTML::selectList($exporttypes, 'export_type',
     'id="export_type" class="inputbox" size="1" onchange="expch();"', 'value', 'text', 0);
    HTML_medialibrary::showImportExport($params, $option);
}


function editing_game($media_class, $medialibrary, $option, $bid) {
    global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
    $is_new = false;
    if ($bid === 0) {
        $is_new = true;
    }
    if (empty($media_class->game_id) && $medialibrary_configuration['mediaid']['auto-increment']['boolean'] == 1) {
        $database->setQuery("select game_id from #__medialibrary_game order by game_id");
        $game_ids = $database->loadObjectList();
        $numeric_game_ids = Array();
        foreach($game_ids as $game_id) {
            if (!is_numeric($game_id->game_id)) {
                echo "<script> alert('You have no numeric gameId. " .
                 "Please set option  " . _MEDIALIBRARY_ADMIN_CONFIG_BOOKID_AUTO_INCREMENT .
                 " to \'No\' or change all gameId to numeric '); window.history.go(-1); </script>\n";
                exit();
            }
            $numeric_game_ids[] = intval($game_id->game_id);
        }
        if (count($numeric_game_ids) > 0) {
            sort($numeric_game_ids);
            $media_class->game_id = $numeric_game_ids[count($numeric_game_ids) - 1] + 1;
        } else $media_class->game_id = 1;
    }

    /************************************    language     *********************************************/
    $associateArray = array();
    if (!empty($bid)) {
        $call_from = 'backend';
        $associateArray = edit_medialibrary_associate($medialibrary,$media_type = 'game',$call_from,false);
    }
    /**************************************************************************************************/

    // get list of categories
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $query = "SELECT  id ,name, parent_id as parent" .
     "\n FROM #__medialibrary_main_categories" .
      "\n WHERE section='com_medialibrary'" .
       "\n AND published > 0" .
        "\n ORDER BY parent_id, ordering";
    $database->setQuery($query);
    $rows = $database->loadObjectList();
    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $list = mediaLibraryTreeRecurse(0, '', array(), $children);
    foreach($list as $i => $item) {
        $item->text = $item->treename;
        $item->value = $item->id;
        $list[$i] = $item;
    }
    $categories = array_merge($categories, $list);
    if (count($categories) <= 1) {
        mosRedirect("index.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
    }
    $cat_idlist = '';
    if(!$is_new){
        $game_id = (!empty($media_class->id))? $media_class->id : $media_class->game_id;
        $query = "SELECT catid FROM #__medialibrary_categories where mediaid=
          (SELECT  m.id FROM #__medialibrary as m
          LEFT JOIN #__medialibrary_game as mg on m.media_id = mg.id
          WHERE m.media_type = 'game' AND mg.id = " . $media_class->id . " )";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $cat_idlist = $database->loadResultArray();
        } else {
            $cat_idlist = $database->loadColumn();
        }
    }
    if (empty($cat_idlist)) $cat_idlist[0] = '0';
    $clist = mosHTML::selectList($categories, 'catid[]',
     'class="inputbox" multiple', 'value', 'text', $cat_idlist);

    $retVal = mosMedialibraryWS::getArray();
    $ws = null;
    for ($i = 0, $n = count($retVal);$i < $n;$i++) {
        $help = $retVal[$i];
        $ws[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $wslist = mosHTML::selectList($ws, 'informationFrom',
     'class="inputbox" size="1"', 'value', 'text',
      intval($medialibrary_configuration['editmedia']['default']['host']));
    else $wslist = mosHTML::selectList($ws, 'informationFrom',
     'class="inputbox" size="1"', 'value', 'text', intval($medialibrary->informationFrom));

    $retVal1 = mosMedialibraryOthers::getLanguageArray();
    $lang = null;
    for ($i = 0, $n = count($retVal1);$i < $n;$i++) {
        $help = $retVal1[$i];
        $lang[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $medialibrary_configuration['editmedia']['default']['lang']);
    else $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $media_class->language);

    $query = "SELECT lang_code, title FROM #__languages";
    $database->setQuery($query);
    $languages = $database->loadObjectList();
    $languages_row[] = mosHTML::makeOption('*', 'All');
    if (!empty($media_class->langDescription)) {
        $selected = $media_class->langDescription;
    } else {
        $selected = '*';
    }
    foreach($languages as $language) {
        $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
    }
    $langshow = mosHTML::selectList($languages_row, 'langDescription',
     'class="inputbox" size="1"', 'value', 'text', $selected);

    $retVal2 = mosMedialibraryOthers::getRatingArray();
    $rating = null;
    for ($i = 0, $n = count($retVal2);$i < $n;$i++) {
        $help = $retVal2[$i];
        $rating[] = mosHTML::makeOption($help[0], $help[1]);
    }
    $ratinglist = mosHTML::selectList($rating, 'rating',
     'class="inputbox" size="1"', 'value', 'text', $media_class->rating);

    $type_list = mosMedialibraryOthers::getTypeArray();
    $type = null;
    foreach($type_list as $value) {
        $help = $value;
        $type[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($is_new) {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text', $medialibrary->media_type);
    } else {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" disabled="true"',
          'value', 'text', $medialibrary->media_type);
    }
    // delete egame?
    $help = str_replace($mosConfig_live_site, "", $media_class->egameURL);
    $delete_edocument_yesno[] = mosHTML::makeOption($help, _MEDIALIBRARY_YES);
    $delete_edocument_yesno[] = mosHTML::makeOption('0', _MEDIALIBRARY_NO);
    $delete_edocument = mosHTML::RadioList($delete_edocument_yesno, 'delete_edocument',
     'class="inputbox"', '0', 'value', 'text');
    // fail if checked out not by 'me'
    if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id) {
        mosRedirect("index.php?option=$option", _MEDIALIBRARY_IS_EDITED);
    }

    if ($bid) {
        $medialibrary->checkout($my->id);
    } else {
        // initialise new record
        $medialibrary->published = 0;
        $medialibrary->approved = 0;
    }


    if (($medialibrary->owneremail) == '' || $bid == 0) {
        $medialibrary->owneremail = $my->email;
    }

    $countInfo = is_array($bid) ? count ($bid) : 1;
    for ($i = 0; $i < $countInfo; $i++) {
        $bids[$i] = explode(',', $bid[$i]);
        $fk_mediaid = $bids[$i][0];
    }

    //$omail = $medialibrary->owneremail;
    $database->setQuery("SELECT username AS owner FROM #__users " . " WHERE id ='$medialibrary->owner_ID'");
    $medialibrary->owner = $database->loadResult();
    //*****************************   begin for reviews **************************//
    if(isset($fk_mediaid) && $fk_mediaid != '') {
        $database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b"
    . " WHERE a.fk_userid = b.id and a.fk_mediaid=" . $fk_mediaid . " ORDER BY date ;");
    $reviews1 = $database->loadObjectList();
    //take review for anonymous users
    $database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  "
    . " WHERE a.fk_userid = 0 and a.fk_mediaid = " . $fk_mediaid . " ORDER BY date ;");
    $reviews2 = $database->loadObjectList();
    $reviews = array_merge($reviews1, $reviews2);
    } else {
        $reviews = '';
    }

    if (!empty($medialibrary->id)) { //check ebook file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_emedia_files WHERE fk_emedia_id =" . $medialibrary->id);
        $files = $db->loadObjectList();
    } else $files = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_video_source WHERE fk_media_id=" . $medialibrary->id);
        $videos = $db->loadObjectList();

    } else $videos = array();
    $youtubeCode = "";
    // for ($i = 0;$i < count($videos);$i++) {
    //     if (!empty($videos[$i]->youtube)) {
    //         $youtubeCode['youtube'] = $videos[$i]->youtube;
    //         unset($videos[$i]);
    //     }
    // }
    $youtubeId = "";
    if (!empty($youtubeCode)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE youtube = '" .
          $youtubeCode['youtube'] . "'");
        $youtubeId = $db->loadResult();
    }
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_audio_source WHERE fk_media_id=" . $medialibrary->id);
        $audios = $db->loadObjectList();
    } else $audios = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_track_source WHERE fk_media_id=" . $medialibrary->id);
        $tracks = $db->loadObjectList();
    } else $tracks = array();
    //**********************   end for reviews   *****************************//

    $query = "SELECT p.people_name ,p.id, p.type as type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'game_studio'"
                ."\n ORDER BY p.people_name" ;
                //print_r($query);exit;
    $database->setQuery($query);
    $studio = $database->loadObjectList();
    $studio_row[] = mosHTML::makeOption('0', 'Selected');
    foreach($studio as $studio_id) {
        $studio_row[] = mosHTML::makeOption($studio_id->id, $studio_id->people_name);
    }
    $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
            . $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    if (empty($people_idlist)) $people_idlist[0] = '';

    $studioshow = mosHTML::selectList($studio_row, 'new_game_studio_select[]', 
        ' class="inputbox" multiple ', 'value', 'text', $people_idlist);
    //**********************   end for reviews   *****************************//
    $multimedia_type = 'game';
    $authorsshow = '';
    $artistshow = '';
    $actorshow = '';
    HTML_medialibrary::editMedia($option, $medialibrary, $media_class, $clist,
        $wslist, $langlist, $ratinglist, $delete_edocument, $reviews, $type_list, $multimedia_type, 
        $langshow,$files, $videos, $audios, $tracks, $youtubeCode, $youtubeId,$associateArray, $artistshow, 
        $authorsshow, $actorshow, $studioshow);
}

/*
$authors_row[] = mosHTML::makeOption('', 'Selected');
    $authors_html_select = array();
    foreach($authors as $author) {
        $authors_row[] = mosHTML::makeOption($author->id, $author->people_name);
    }
    $authors_html_select['author_ids'] = array();
    if($medialibrary->id){
        $query = "SELECT fk_people_id FROM #__medialibrary_people_connect WHERE fk_media_id= ".$medialibrary->id;
        $database->setQuery($query);
        $authors_html_select['author_ids'] = $database->loadColumn();
    }

    $authors_html_select['authors_makeOption'] = $authors_row;
    $authorsshow = mosHTML::selectList($authors_row, 'new_author_select[]', ' class="inputbox" multiple ', 'value',
                'text', $medialibrary->id);
*/

function editing_music($media_class, $medialibrary, $option, $bid) {
    global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
    $is_new = false;
    if ($bid === 0) {
        $is_new = true;
    }
    if (empty($media_class->music_id) && 
            $medialibrary_configuration['mediaid']['auto-increment']['boolean'] == 1) {
        $database->setQuery("select music_id from #__medialibrary_music order by music_id");
        $music_ids = $database->loadObjectList();
        $numeric_music_ids = Array();
        foreach($music_ids as $music_id) {
            if (!is_numeric($music_id->music_id)) {
                echo "<script> alert('You have no numeric musicId. " .
                 "Please set option  " . _MEDIALIBRARY_ADMIN_CONFIG_BOOKID_AUTO_INCREMENT .
                 " to \'No\' or change all musicId to numeric '); window.history.go(-1); </script>\n";
                exit();
            }
            $numeric_music_ids[] = intval($music_id->music_id);
        }
        if (count($numeric_music_ids) > 0) {
            sort($numeric_music_ids);
            $media_class->music_id = $numeric_music_ids[count($numeric_music_ids) - 1] + 1;
        } else $media_class->music_id = 1;
    }


  /************************************    language     *********************************************/
    $associateArray = array();
    if (!empty($bid)) {
        $call_from = 'backend';
        $associateArray = edit_medialibrary_associate($medialibrary,$media_type = 'music',$call_from,false);
    }
  /**************************************************************************************************/


    // get list of categories
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $query = "SELECT  id ,name, parent_id as parent" .
     "\n FROM #__medialibrary_main_categories" .
      "\n WHERE section='com_medialibrary'" .
       "\n AND published > 0" .
        "\n ORDER BY parent_id, ordering";
    $database->setQuery($query);
    $rows = $database->loadObjectList();
    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $list = mediaLibraryTreeRecurse(0, '', array(), $children);
    foreach($list as $i => $item) {
        $item->text = $item->treename;
        $item->value = $item->id;
        $list[$i] = $item;
    }
    $categories = array_merge($categories, $list);
    if (count($categories) <= 1) {
        mosRedirect("index.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
    }
    $cat_idlist = '';
    if(!$is_new){
        $query = "SELECT catid FROM #__medialibrary_categories where mediaid=
          (SELECT m.id FROM #__medialibrary as m
          LEFT JOIN #__medialibrary_music as mm on m.media_id = mm.id
          WHERE
           m.media_type = 'music' AND mm.id = " . $media_class->id . " )";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $cat_idlist = $database->loadResultArray();
        } else {
            $cat_idlist = $database->loadColumn();
        }
    }
    if (empty($cat_idlist)) $cat_idlist[0] = '0';
    $clist = mosHTML::selectList($categories, 'catid[]', 'class="inputbox" multiple',
     'value', 'text', $cat_idlist);

    $retVal = mosMedialibraryWS::getArray();
    $ws = null;
    for ($i = 0, $n = count($retVal);$i < $n;$i++) {
        $help = $retVal[$i];
        $ws[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $wslist = mosHTML::selectList($ws, 'informationFrom',
     'onchange="checkDisabled(this.value)" class="inputbox" size="1"', 'value', 'text',  
                     intval($medialibrary_configuration['editmedia']['default']['host']));
    else $wslist = mosHTML::selectList($ws, 'informationFrom',
     'onchange="checkDisabled(this.value)" class="inputbox" size="1"', 'value', 'text', 
        intval($medialibrary->informationFrom));

    $retVal1 = mosMedialibraryOthers::getLanguageArray();
    $lang = null;
    for ($i = 0, $n = count($retVal1);$i < $n;$i++) {
        $help = $retVal1[$i];
        $lang[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $medialibrary_configuration['editmedia']['default']['lang']);
    else $langlist = mosHTML::selectList($lang, 'language', 'class="inputbox" size="1"',
     'value', 'text', $media_class->language);

    $query = "SELECT lang_code, title FROM #__languages";
    $database->setQuery($query);
    $languages = $database->loadObjectList();
    $languages_row[] = mosHTML::makeOption('*', 'All');
    if (!empty($media_class->langDescription)) {
        $selected = $media_class->langDescription;
    } else {
        $selected = '*';
    }
    foreach($languages as $language) {
        $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
    }
    $langshow = mosHTML::selectList($languages_row, 'langDescription',
     'class="inputbox" size="1"', 'value', 'text', $selected);

    $retVal2 = mosMedialibraryOthers::getRatingArray();
    $rating = null;
    for ($i = 0, $n = count($retVal2);$i < $n;$i++) {
        $help = $retVal2[$i];
        $rating[] = mosHTML::makeOption($help[0], $help[1]);
    }
    $ratinglist = mosHTML::selectList($rating, 'rating',
     'class="inputbox" size="1"', 'value', 'text', $media_class->rating);

    $type_list = mosMedialibraryOthers::getTypeArray();
    $type = null;
    foreach($type_list as $value) {
        $help = $value;
        $type[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($is_new) {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text', $medialibrary->media_type);
    } else {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" disabled="true"',
          'value', 'text', $medialibrary->media_type);
    }
    // delete emusic?
    $help = str_replace($mosConfig_live_site, "", $media_class->emusicURL);
    $delete_edocument_yesno[] = mosHTML::makeOption($help, _MEDIALIBRARY_YES);
    $delete_edocument_yesno[] = mosHTML::makeOption('0', _MEDIALIBRARY_NO);
    $delete_edocument = mosHTML::RadioList($delete_edocument_yesno,
     'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
    // fail if checked out not by 'me'
    if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id) {
        mosRedirect("index.php?option=$option", _MEDIALIBRARY_IS_EDITED);
    }
    if ($bid) {
        $medialibrary->checkout($my->id);
    } else {
        // initialise new record
        $medialibrary->published = 0;
        $medialibrary->approved = 0;
    }
    if (($medialibrary->owneremail) == '' || $bid == 0) {
        $medialibrary->owneremail = $my->email;
    }
    //$omail = $medialibrary->owneremail;
    $countInfo = is_array($bid) ? count ($bid) : 1;
    for ($i = 0; $i < $countInfo; $i++) {
        $bids[$i] = explode(',', $bid[$i]);
        $fk_mediaid = $bids[$i][0];
    }

    $database->setQuery("SELECT username AS owner FROM #__users " . " WHERE id=$medialibrary->owner_ID ");
    $medialibrary->owner = $database->loadResult();
    //*****************************   begin for reviews **************************//
    if(isset($fk_mediaid) && $fk_mediaid != '') {
        $database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b"
    . " WHERE a.fk_userid = b.id and a.fk_mediaid=" . $fk_mediaid . " ORDER BY date ;");
    $reviews1 = $database->loadObjectList();
    //take review for anonymous users
    $database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  "
    . " WHERE a.fk_userid = 0 and a.fk_mediaid = " . $fk_mediaid . " ORDER BY date ;");
    $reviews2 = $database->loadObjectList();
    $reviews = array_merge($reviews1, $reviews2);
    } else {
        $reviews = '';
    }

    if (!empty($medialibrary->id)) { //check ebook file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_emedia_files WHERE fk_emedia_id =" . $medialibrary->id);
        $files = $db->loadObjectList();
    } else $files = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_video_source WHERE fk_media_id=" . $medialibrary->id);
        $videos = $db->loadObjectList();

    } else $videos = array();
    $youtubeCode = "";
    // for ($i = 0;$i < count($videos);$i++) {
    //     if (!empty($videos[$i]->youtube)) {
    //         $youtubeCode['youtube'] = $videos[$i]->youtube;
    //         unset($videos[$i]);
    //     }
    // }
    $youtubeId = "";
    if (!empty($youtubeCode)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE youtube = '" .
          $youtubeCode['youtube'] . "'");
        $youtubeId = $db->loadResult();
    }
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_audio_source WHERE fk_media_id=" . $medialibrary->id);
        $audios = $db->loadObjectList();
    } else $audios = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_track_source WHERE fk_media_id=" . $medialibrary->id);
        $tracks = $db->loadObjectList();
    } else $tracks = array();

    $query = "SELECT p.people_name ,p.id FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'artist'"
                ."\n ORDER BY p.people_name";
                //print_r($query);exit;
    $database->setQuery($query);
    $artist = $database->loadObjectList();
  //  print_r($authors);exit;
    $artist_row[] = mosHTML::makeOption('0', 'Selected');
     foreach($artist as $artist_id) {
        $artist_row[] = mosHTML::makeOption($artist_id->id, $artist_id->people_name);
    }
    $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
            . $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    //print_r($people_idlist);exit;
    if (empty($people_idlist)) $people_idlist[0] = '';

    $artistshow = mosHTML::selectList($artist_row, 'new_artist_select[]', ' class="inputbox" multiple ', 'value',
                'text', $people_idlist);
    //**********************   end for reviews   *****************************//
    $multimedia_type = 'music';
    HTML_medialibrary::editMedia($option, $medialibrary, $media_class, $clist,$wslist, $langlist, $ratinglist, 
            $delete_edocument,$reviews, $type_list, $multimedia_type, $langshow,$files, $videos,$audios, 
            $tracks, $youtubeCode, $youtubeId,$associateArray, $artistshow);
}



function editing_video($media_class, $medialibrary, $option, $bid) {
    global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
    $is_new = false;
    if ($bid === 0) {
        $is_new = true;
    }

    if (empty($media_class->video_id) && 
            $medialibrary_configuration['mediaid']['auto-increment']['boolean'] == 1) {
        $database->setQuery("select video_id from #__medialibrary_video order by video_id");
        $video_ids = $database->loadObjectList();
        $numeric_video_ids = Array();
        foreach($video_ids as $video_id) {
            if (!is_numeric($video_id->video_id)) {
                echo "<script> alert('You have no numeric VideoId. " .
                 "Please set option  " . _MEDIALIBRARY_ADMIN_CONFIG_BOOKID_AUTO_INCREMENT .
                 " to \'No\' or change all VideoId to numeric '); window.history.go(-1); </script>\n";
                exit();
            }
            $numeric_video_ids[] = intval($video_id->video_id);
        }
        if (count($numeric_video_ids) > 0) {
            sort($numeric_video_ids);
            $media_class->video_id = $numeric_video_ids[count($numeric_video_ids) - 1] + 1;
        } else $media_class->video_id = 1;
    }

  /************************************    language     *********************************************/
    $associateArray = array();
    if (!empty($bid)) {
        $call_from = 'backend';
        $associateArray = edit_medialibrary_associate($medialibrary,$media_type = 'video',$call_from,false);
    }
  /**************************************************************************************************/

    // get list of categories 
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $query = "SELECT  id ,name, parent_id as parent" 
        . "\n FROM #__medialibrary_main_categories"
        . "\n WHERE section='com_medialibrary'" 
        . "\n AND published > 0" 
        . "\n ORDER BY parent_id, ordering";
    $database->setQuery($query);
    $rows = $database->loadObjectList();
    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $list = mediaLibraryTreeRecurse(0, '', array(), $children);
    foreach($list as $i => $item) {
        $item->text = $item->treename;
        $item->value = $item->id;
        $list[$i] = $item;
    }
    $categories = array_merge($categories, $list);
    if (count($categories) <= 1) {
        mosRedirect("index.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
    }
    $cat_idlist = '';
    if(!$is_new){
        $query = "SELECT catid FROM #__medialibrary_categories where mediaid=
                  (SELECT m.id FROM #__medialibrary as m
                  LEFT JOIN #__medialibrary_video as mv on m.media_id = mv.id
                  WHERE m.media_type = 'video' AND mv.id = " . $media_class->id . " )";
//print_r($query);exit;
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $cat_idlist = $database->loadResultArray();
        } else {
            $cat_idlist = $database->loadColumn();
        }
    }
    if (empty($cat_idlist)) $cat_idlist[0] = '0';
    $clist = mosHTML::selectList($categories, 'catid[]',
     'class="inputbox" multiple', 'value', 'text', $cat_idlist);

    $retVal = mosMedialibraryWS::getArray();
    $ws = null;
    for ($i = 0, $n = count($retVal);$i < $n;$i++) {
        $help = $retVal[$i];
        $ws[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $wslist = mosHTML::selectList($ws, 'informationFrom',
     'class="inputbox" size="1"', 'value', 'text',
      intval($medialibrary_configuration['editmedia']['default']['host']));
    else $wslist = mosHTML::selectList($ws, 'informationFrom',
     'class="inputbox" size="1"', 'value', 'text', intval($medialibrary->informationFrom));

    $retVal1 = mosMedialibraryOthers::getLanguageArray();
    $lang = null;
    for ($i = 0, $n = count($retVal1);$i < $n;$i++) {
        $help = $retVal1[$i];
        $lang[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $medialibrary_configuration['editmedia']['default']['lang']);
    else $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $media_class->language);

    $query = "SELECT lang_code, title FROM #__languages";
    $database->setQuery($query);
    $languages = $database->loadObjectList();
    $languages_row[] = mosHTML::makeOption('*', 'All');
    if (!empty($media_class->langDescription)) {
        $selected = $media_class->langDescription;
    } else {
        $selected = '*';
    }
    foreach($languages as $language) {
        $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
    }
    $langshow = mosHTML::selectList($languages_row, 'langDescription',
     'class="inputbox" size="1"', 'value', 'text', $selected);

    $retVal2 = mosMedialibraryOthers::getRatingArray();
    $rating = null;
    for ($i = 0, $n = count($retVal2);$i < $n;$i++) {
        $help = $retVal2[$i];
        $rating[] = mosHTML::makeOption($help[0], $help[1]);
    }
    $ratinglist = mosHTML::selectList($rating, 'rating',
     'class="inputbox" size="1"', 'value', 'text', $media_class->rating);

    $type_list = mosMedialibraryOthers::getTypeArray();
    $type = null;
    foreach($type_list as $value) {
        $help = $value;
        $type[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($is_new) {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" ',
          'value', 'text', $medialibrary->media_type);
    } else {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" disabled="true"',
          'value', 'text', $medialibrary->media_type);
    }
    // delete evideo?
    $help = str_replace($mosConfig_live_site, "", $media_class->evideoURL);
    $delete_edocument_yesno[] = mosHTML::makeOption($help, _MEDIALIBRARY_YES);
    $delete_edocument_yesno[] = mosHTML::makeOption('0', _MEDIALIBRARY_NO);
    $delete_edocument = mosHTML::RadioList($delete_edocument_yesno,
     'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
    // fail if checked out not by 'me'
    if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id) {
        mosRedirect("index.php?option=$option", _MEDIALIBRARY_IS_EDITED);
    }
    if ($bid) {
        $medialibrary->checkout($my->id);
    } else {
        // initialise new record
        $medialibrary->published = 0;
        $medialibrary->approved = 0;
    }
    if (($medialibrary->owneremail) == '' || $bid == 0) {
        $medialibrary->owneremail = $my->email;
    }

    $countInfo = is_array($bid) ? count ($bid) : 1;
    for ($i = 0; $i < $countInfo; $i++) {
        $bids[$i] = explode(',', $bid[$i]);
        $fk_mediaid = $bids[$i][0];
    }

    $database->setQuery("SELECT username AS owner FROM #__users " . " WHERE id ='$medialibrary->owner_ID'");
    $medialibrary->owner = $database->loadResult();
    //*****************************   begin for reviews **************************//
    if(isset($fk_mediaid) && $fk_mediaid != '') {
        $database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b"
    . " WHERE a.fk_userid = b.id and a.fk_mediaid=" . $fk_mediaid . " ORDER BY date ;");
    $reviews1 = $database->loadObjectList();
    //take review for anonymous users
    $database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  "
    . " WHERE a.fk_userid = 0 and a.fk_mediaid = " . $fk_mediaid . " ORDER BY date ;");
    $reviews2 = $database->loadObjectList();
    $reviews = array_merge($reviews1, $reviews2);
    } else {
        $reviews = '';
    }

    if (!empty($medialibrary->id)) { //check ebook file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_emedia_files WHERE fk_emedia_id =" . $medialibrary->id);
        $files = $db->loadObjectList();
    } else $files = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_video_source WHERE fk_media_id=" . $medialibrary->id);
        $videos = $db->loadObjectList();

    } else $videos = array();
    $youtubeCode = "";
    // for ($i = 0;$i < count($videos);$i++) {
    //     if (!empty($videos[$i]->youtube)) {
    //         $youtubeCode['youtube'] = $videos[$i]->youtube;
    //         unset($videos[$i]);
    //     }
    // }
    $youtubeId = "";
    if (!empty($youtubeCode)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE youtube = '" .
          $youtubeCode['youtube'] . "'");
        $youtubeId = $db->loadResult();
    }
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_audio_source WHERE fk_media_id=" . $medialibrary->id);
        $audios = $db->loadObjectList();
    } else $audios = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_track_source WHERE fk_media_id=" . $medialibrary->id);
        $tracks = $db->loadObjectList();
    } else $tracks = array();

    //**********************   end for reviews   *****************************//
    $query = "SELECT p.people_name ,p.id, p.type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'actor'"
                ."\n ORDER BY p.people_name";
    $database->setQuery($query);
    $actors = $database->loadObjectList();

    $actors_row[] = mosHTML::makeOption('0', 'Selected');

    foreach($actors as $actor) {
        $actors_row[] = mosHTML::makeOption($actor->id, $actor->people_name);
    }
     $people_idlist = '';
        if(!$is_new){
            $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
                . $medialibrary->id . "'";
            $database->setQuery($query);
            if (version_compare(JVERSION, "3.0.0", "lt")) {
                $people_idlist = $database->loadResultArray();
            } else {
                $people_idlist = $database->loadColumn();
            }
        }
        if (empty($people_idlist)) $people_idlist = '';
    $actorshow = mosHTML::selectList($actors_row, 'new_actor_select[]', ' class="inputbox" multiple ', 'value',
                'text', $people_idlist);
    //print_r($actorsshow);exit;

    //****************  switch studio  ***************////

    $query = "SELECT p.people_name ,p.id, p.type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'video_studio'"
                ."\n ORDER BY p.people_name";
                //print_r($query);exit;
    $database->setQuery($query);
    $studio = $database->loadObjectList();
    $studio_row[] = mosHTML::makeOption('0', 'Selected');

    foreach($studio as $studio_id) {
        $studio_row[] = mosHTML::makeOption($studio_id->id, $studio_id->people_name);
    }
   $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
            . $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    if (empty($people_idlist)) $people_idlist[0] = '';
    //print_r($studio_html_select);exit;
    $studioshow = mosHTML::selectList($studio_row, 'new_video_studio_select[]', ' class="inputbox" multiple ', 
        'value', 'text', $people_idlist);

    $query = "SELECT p.people_name ,p.id, p.type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'producer'"
                ."\n ORDER BY p.people_name";
                //print_r($query);exit;
    $database->setQuery($query);
    $producer = $database->loadObjectList();
    $producer_row[] = mosHTML::makeOption('0', 'Selected');

    foreach($producer as $producer_id) {
        $producer_row[] = mosHTML::makeOption($producer_id->id, $producer_id->people_name);
    }
   $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
            . $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    if (empty($people_idlist)) $people_idlist[0] = '';
    //print_r($studio_html_select);exit;
    $producershow = mosHTML::selectList($producer_row, 'new_producer_select[]', ' class="inputbox" multiple ', 
        'value', 'text', $people_idlist);

    $query = "SELECT p.people_name ,p.id, p.type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'director'"
                ."\n ORDER BY p.people_name";
                //print_r($query);exit;
    $database->setQuery($query);
    $director = $database->loadObjectList();
    $director_row[] = mosHTML::makeOption('0', 'Selected');
    foreach($director as $director_id) {
        $director_row[] = mosHTML::makeOption($director_id->id, $director_id->people_name);
    }
   $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" 
            . $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    if (empty($people_idlist)) $people_idlist[0] = '';
    //print_r($studio_html_select);exit;
    $directorshow = mosHTML::selectList($director_row, 'new_director_select[]', ' class="inputbox" multiple ', 
        'value', 'text', $people_idlist);
//print_r($directorshow);exit;s
    $multimedia_type = 'video';
    $artistshow='';
    $authorsshow = '';
    HTML_medialibrary::editMedia($option, $medialibrary, $media_class, $clist,
     $wslist, $langlist, $ratinglist, $delete_edocument, $reviews, $type_list, $multimedia_type, $langshow, $files,
     $videos, $audios, $tracks, $youtubeCode, $youtubeId, $associateArray, $authorsshow, $artistshow, $actorshow,
      $studioshow, $producershow, $directorshow );
}





function editing_book($media_class, $medialibrary, $option, $bid) {
    global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
    $is_new = false;
    if ($bid === 0) {
        $is_new = true;
    }//print_r('$bookids');exit;

    if (empty($media_class->book_id) && $medialibrary_configuration['mediaid']['auto-increment']['boolean'] == 1) {
        $database->setQuery("select book_id from #__medialibrary_book order by book_id");
        $bookids = $database->loadObjectList();

        $numeric_bookids = Array();
        foreach($bookids as $book_id) {
            if (!is_numeric($book_id->book_id)) {
                echo "<script> alert('You have no numeric BookId. " .
                 "Please set option  " . _MEDIALIBRARY_ADMIN_CONFIG_BOOKID_AUTO_INCREMENT .
                 " to \'No\' or change all BookID to numeric '); window.history.go(-1); </script>\n";
                exit();
            }
            $numeric_bookids[] = intval($book_id->book_id);
        }

        if (count($numeric_bookids) > 0) {
            sort($numeric_bookids);
            $media_class->book_id = $numeric_bookids[count($numeric_bookids) - 1] + 1;
        } else $media_class->book_id = 1;
    }

    /************************************    language     *********************************************/

    
    $associateArray = array();
    if (!empty($bid)) {
       $call_from = 'backend';
        $associateArray = edit_medialibrary_associate($medialibrary,$media_type = 'book',$call_from,false);
    }


    /**************************************************************************************************/

    // get list of categories
    $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
    $query = "SELECT  id ,name, parent_id as parent" .
     "\n FROM #__medialibrary_main_categories" .
      "\n WHERE section='com_medialibrary'" .
       "\n AND published > 0" .
        "\n ORDER BY parent_id, ordering";
    $database->setQuery($query);
    $rows = $database->loadObjectList();
    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $list = mediaLibraryTreeRecurse(0, '', array(), $children);
    foreach($list as $i => $item) {
        $item->text = $item->treename;
        $item->value = $item->id;
        $list[$i] = $item;
    }
    $categories = array_merge($categories, $list);

    if (count($categories) <= 1) {
        mosRedirect("index.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
    }
    $cat_idlist = '';
           //print_r($medialibrary->id);exit;
    if(!$is_new){
        $query = "SELECT catid FROM #__medialibrary_categories where mediaid=
        (SELECT m.id FROM #__medialibrary as m
        LEFT JOIN #__medialibrary_book as mb on m.media_id = mb.id
        WHERE m.media_type = 'book' AND
         mb.id = " . $media_class->id . " )";
//print_r($query);exit;
        $database->setQuery($query);

        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $cat_idlist = $database->loadResultArray();
        } else {
            $cat_idlist = $database->loadColumn();
        }
    }
    if (empty($cat_idlist)) $cat_idlist[0] = '0';
    $clist = mosHTML::selectList($categories, 'catid[]', 'class="inputbox" multiple', 'value','text',$cat_idlist);

    $retVal = mosMedialibraryWS::getArray();
    $ws = null;
    for ($i = 0, $n = count($retVal);$i < $n;$i++) {
        $help = $retVal[$i];
        $ws[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $wslist = mosHTML::selectList($ws, 'informationFrom',
     'onchange="checkDisabled(this.value)" class="inputbox" size="1"', 'value', 'text',
      intval($medialibrary_configuration['editmedia']['default']['host']));
    else $wslist = mosHTML::selectList($ws, 'informationFrom',
     'onchange="checkDisabled(this.value)" class="inputbox" size="1"', 'value','text',
        intval($medialibrary->informationFrom));

    $retVal1 = mosMedialibraryOthers::getLanguageArray();
    $lang = null;
    for ($i = 0, $n = count($retVal1);$i < $n;$i++) {
        $help = $retVal1[$i];
        $lang[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($bid == 0) $langlist = mosHTML::selectList($lang, 'language',
     'class="inputbox" size="1"', 'value', 'text', $medialibrary_configuration['editmedia']['default']['lang']);
    else $langlist = mosHTML::selectList($lang, 'language', 'class="inputbox" size="1"',
     'value', 'text', $media_class->language);

    
    if (version_compare(JVERSION, "1.6.0", "lt")) {
        $allLanguages = array();
        $lang = JFactory::getLanguage();
        foreach($lang->getLocale()  as  $locale) {
            if (mb_strlen($locale) == 5 && $locale[2] == '_'){
                $locale[2] = '-';
                $query = "SELECT title FROM #__medialibrary_languages 
                          WHERE lang_code = '$locale'";
                $database->setQuery($query);
                $language_title = $database->loadResult();
                $language = new ArrayObject;
                $language->lang_code = $locale;
                $language->title = $language_title;
                $languages[] = $language;
            }
        }
    } else {
        $query = "SELECT lang_code, title FROM #__languages";
        $database->setQuery($query);
        $languages = $database->loadObjectList();
    }


    $languages_row[] = mosHTML::makeOption('*', 'All');
    if (!empty($media_class->langDescription)) {
        $selected = $media_class->langDescription;
    } else {
        $selected = '*';
    }
    foreach($languages as $language) {
        $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
    }
    $langshow = mosHTML::selectList($languages_row, 'langDescription',
     'class="inputbox" size="1"', 'value', 'text', $selected);

    $retVal2 = mosMedialibraryOthers::getRatingArray();
    $rating = null;
    for ($i = 0, $n = count($retVal2);$i < $n;$i++) {
        $help = $retVal2[$i];
        $rating[] = mosHTML::makeOption($help[0], $help[1]);
    }
    $ratinglist = mosHTML::selectList($rating, 'rating', 'class="inputbox" size="1"',
     'value', 'text', $media_class->rating);
    // Р  Р вЂ Р РЋРІР‚в„–Р  Р’В±Р  РЎвЂўР РЋР вЂљ Р РЋРІР‚С™Р  РЎвЂР  РЎвЂ”Р  Р’В°
    $type_list = mosMedialibraryOthers::getTypeArray();
    $type = null;
    foreach($type_list as $value) {
        $help = $value;
        $type[] = mosHTML::makeOption($help[0], $help[1]);
    }
    if ($is_new) {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" ', 'value',
          'text', $medialibrary->media_type);
    } else {
        $type_list = mosHTML::selectList($type, 'media_type',
         'class="inputbox" size="1" onchange="type_select();" disabled="true"',
          'value', 'text', $medialibrary->media_type);
    }
    // delete ebook?
    $help = str_replace($mosConfig_live_site, "", $media_class->ebookURL);
    $delete_edocument_yesno[] = mosHTML::makeOption($help, _MEDIALIBRARY_YES);
    $delete_edocument_yesno[] = mosHTML::makeOption('0', _MEDIALIBRARY_NO);
    $delete_edocument = mosHTML::RadioList($delete_edocument_yesno,
     'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
    // fail if checked out not by 'me'
    if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id) {
        mosRedirect("index.php?option=$option", _MEDIALIBRARY_IS_EDITED);
    }
    if ($bid) {
        $medialibrary->checkout($my->id);
    } else {
        // initialise new record
        $medialibrary->published = 0;
        $medialibrary->approved = 0;
    }
    if (($medialibrary->owneremail) == '' || $bid == 0) {
        $medialibrary->owneremail = $my->email;
    }
    if(!is_array($bid)){
        $bid_temp = $bid;
        $bid = array();
        $bid[] = $bid_temp;
    }

     $countInfo = (is_array($bid)) ? count ($bid) : 1;
        for ($i = 0; $i < $countInfo; $i++) {
                $bids[$i] = explode(',', $bid[$i]);
                $fk_mediaid = $bids[$i][0];
        }
    $database->setQuery("SELECT username AS owner FROM #__users " . " WHERE id ='$medialibrary->owner_ID'");
    $medialibrary->owner = $database->loadResult();
    //*****************************   begin for reviews **************************//

    if(isset($fk_mediaid) && $fk_mediaid != '') {
        $database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b"
    . " WHERE a.fk_userid = b.id and a.fk_mediaid=" . $fk_mediaid . " ORDER BY date ;");
    $reviews1 = $database->loadObjectList();
    //take review for anonymous users
    $database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  "
    . " WHERE a.fk_userid = 0 and a.fk_mediaid = " . $fk_mediaid . " ORDER BY date ;");
    $reviews2 = $database->loadObjectList();
    $reviews = array_merge($reviews1, $reviews2);
    } else {
        $reviews = '';
    }
    if (!empty($medialibrary->id)) { //check ebook file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_emedia_files WHERE fk_emedia_id =" . $medialibrary->id);
        $files = $db->loadObjectList();
    } else $files = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_video_source WHERE fk_media_id=" . $medialibrary->id);
        $videos = $db->loadObjectList();

    } else $videos = array();
    $youtubeCode = "";
    // for ($i = 0;$i < count($videos);$i++) {
    //     if (!empty($videos[$i]->youtube)) {
    //         $youtubeCode['youtube'] = $videos[$i]->youtube;
    //         unset($videos[$i]);
    //     }
    // }
    $youtubeId = "";
    if (!empty($youtubeCode)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE youtube = '" .
          $youtubeCode['youtube'] . "'");
        $youtubeId = $db->loadResult();
    }
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_audio_source WHERE fk_media_id=" . $medialibrary->id);
        $audios = $db->loadObjectList();
    } else $audios = array();
    if (!empty($medialibrary->id)) { //check video file
        $db = JFactory::getDBO();
        $db->setQuery("SELECT * FROM #__medialibrary_track_source WHERE fk_media_id=" . $medialibrary->id);
        $tracks = $db->loadObjectList();
    } else $tracks = array();

    //**********************   end for reviews   *****************************//
    $query = "SELECT p.people_name ,p.id, p.type FROM #__medialibrary_people AS p "
                ."\n WHERE p.type = 'author'"
                ."\n ORDER BY p.people_name";
    $database->setQuery($query);
    $authors = $database->loadObjectList();

    $authors_row[] = mosHTML::makeOption('0', 'Selected');
    foreach($authors as $author) {
        $authors_row[] = mosHTML::makeOption($author->id, $author->people_name);
    }

    $people_idlist = '';
    if(!$is_new){
        $query = "select fk_people_id from #__medialibrary_people_connect where fk_media_id='" . 
            $medialibrary->id . "'";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $people_idlist = $database->loadResultArray();
        } else {
            $people_idlist = $database->loadColumn();
        }
    }
    if (empty($people_idlist)) $people_idlist = '';

    $authorsshow = mosHTML::selectList($authors_row, 'new_author_select[]', ' class="inputbox"  multiple ', 
        'value', 'text', $people_idlist);
    $multimedia_type = 'book';
    $artistshow='';

    //field modal article
    $inp = new JFormFieldModal_Article_ML();
    JFormHelper::addFieldPath($mosConfig_live_site . 
        "/components/com_medialibrary");
    $inp = JFormHelper::loadFieldType('Modal_Article_ML', false);
    $medialibrary->modal_article = @$inp->getInput();

    HTML_medialibrary::editMedia($option, $medialibrary, $media_class, $clist, $wslist, $langlist, $ratinglist, 
        $delete_edocument, $reviews, $type_list, $multimedia_type, $langshow, $files, $videos, $audios, $tracks, 
        $youtubeCode, $youtubeId,  $associateArray, $artistshow, $authorsshow);
}





function getTreeCateg(&$return = array(), $id = 0, $sublvl = '-1') {
    global $database;
    $sublvl++;
    $addpref = '';
    if ($sublvl) {
        $result->text = $addpref . 'L ' . $result->text;
    }
    $database->setQuery("SELECT id AS value, name AS text, parent_id " .
       " FROM #__medialibrary_main_categories" .
       "\nWHERE section='com_medialibrary' AND parent_id=$id ORDER BY ordering");
    $results = $database->loadObjectList();
    if (count($results)) {
        foreach($results as $result) {
            for ($c = 0;$c < $sublvl;$c++) {
                $addpref.= ' ';
            }
            $return[] = $result;
            getTreeCateg($return, $result->value, $sublvl);
        }
    }
    return $return;
}
function checkAccess_ML($accessgroupid, $recurse, $usersgroupid, $acl) {
    if (is_array($usersgroupid)) if (is_int($usersgroupid)) return false;
    //parse usergroups
    $tempArr = array();
    $tempArr = explode(',', $accessgroupid);
    for ($i = 0;$i < count($tempArr);$i++) {
        if (($tempArr[$i] == $usersgroupid OR in_array($tempArr[$i], $usersgroupid)) || $tempArr[$i] == - 2) {
            //allow access
            return true;
        } else {
            if ($recurse == 'RECURSE') {
                if (is_array($usersgroupid)) {
                    for ($j = 0;$j < count($usersgroupid);$j++) {
                        if (in_array($usersgroupid[$j], $tempArr)) {
                            return 1;
                        }
                    }
                } else {
                    if (in_array($usersgroupid, $tempArr)) {
                        return 1;
                    }
                }
            }
        }
    } // end for
    //deny access
    return 0;
}
function showLanguageManager($option) {
    global $database, $mainframe, $mosConfig_list_limit, $menutype, $mosConfig_absolute_path;

    $section = "com_medialibrary";
    $search['const'] = protectInjectionWithoutQuote('search_const');
    $search['const_value'] = protectInjectionWithoutQuote('search_const_value');
    $value = protectInjectionWithoutQuote('search_const');

    $search['languages'] = protectInjectionWithoutQuote('search_languages');
    $search['sys_type'] = protectInjectionWithoutQuote('search_sys_type');
    $where_query = array();
    if ($search['const'] != '') $where_query[] = "c.const LIKE '%" . $search['const'] . "%'";
    if ($search['const_value'] != '') $where_query[] = "cl.value_const LIKE '%" . $search['const_value'] . "%'";
    if ($search['languages'] != '') $where_query[] = "cl.fk_languagesid = " 
            . $database->quote($search['languages']) . " ";
    if ($search['sys_type'] != '') $where_query[] = "c.sys_type LIKE '%" . $search['sys_type'] . "%'";
    $where = "";
    $i = 0;
    if (count($where_query) > 0) $where = "WHERE ";
    foreach($where_query as $item) {
        if ($i == 0) $where.= "( $item ) ";
        else $where.= "AND ( $item ) ";
        $i++;
    }
    $query = "SELECT cl.id, cl.value_const, c.sys_type, l.title, c.const ";
    $query.= "FROM #__medialibrary_const_languages as cl ";
    $query.= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
    $query.= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id $where";
    $database->setQuery($query);
    $const_languages = $database->loadObjectList();
    $sectionid = $mainframe->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
    $limitstart = $mainframe->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $mainframe->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);
    $total = count($const_languages);
    $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
    $const_languages = array_slice($const_languages, $pageNav->limitstart, $pageNav->limit);
    $query = "SELECT sys_type FROM #__medialibrary_const GROUP BY sys_type";
    $database->setQuery($query);
    $sys_types = $database->loadObjectList();
    $sys_type_row[] = mosHTML::makeOption('', '--Select sys type--');
    foreach($sys_types as $sys_type) {
        $sys_type_row[] = mosHTML::makeOption($sys_type->sys_type, $sys_type->sys_type);
    }
    $search['sys_type'] = mosHTML::selectList($sys_type_row, 'search_sys_type',
     'class="inputbox input-medium" size="1" onchange="document.adminForm.submit();"',
      'value', 'text', $search['sys_type']);
    $query = "SELECT id, title FROM #__medialibrary_languages";
    $database->setQuery($query);
    $languages = $database->loadObjectList();
    $languages_row[] = mosHTML::makeOption('', '--Select language--');
    foreach($languages as $language) {
        $languages_row[] = mosHTML::makeOption($language->id, $language->title);
    }
    $search['languages'] = mosHTML::selectList($languages_row, 'search_languages',
     'class="inputbox input-medium" size="1" onchange="document.adminForm.submit();"',
      'value', 'text', $search['languages']);

    if(JRequest::getVar('task','') == 'loadLang'){
        loadConstMedia();
        language_check();
    }

    HTML_medialibrary::showLanguageManager($const_languages, $pageNav, $search);
}
function editLanguageManager($section = '', $uid = 0) {
    global $database, $my, $acl, $medialibrary_configuration;
    global $mosConfig_absolute_path, $mosConfig_live_site;
    $row = new mosMedialibrary_language($database); // for 1.6
    // load the row from the db table
    $row->load($uid);
    $query = "SELECT * FROM #__medialibrary_const WHERE id = " . $row->fk_constid;
    $database->setQuery($query);
    $const = $database->loadObject();
    $lists['const'] = $const->const;
    $lists['sys_type'] = $const->sys_type;
    $query = "SELECT title FROM #__medialibrary_languages WHERE id = " . $row->fk_languagesid;
    $database->setQuery($query);
    $language = $database->loadResult();
    $lists['languages'] = $language;
    HTML_medialibrary::editLanguageManager($row, $lists);
}
function saveLanguageManager() {
    global $database, $mosConfig_absolute_path;
    $row = new mosMedialibrary_language($database); // for 1.6
    $post = JRequest::get('post', JREQUEST_ALLOWHTML);
    if (!$row->bind($post)) {
        echo "<script> alert(\"" . $row->getError() . "\"); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$row->check()) {
        echo "<script> alert(\"" . $row->getError() . "\"); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$row->store()) {
        echo "<script> alert(\"" . $row->getError() . "\"); window.history.go(-1); </script>\n";
        exit();
    }
    mosRedirect('index.php?option=com_medialibrary&section=language_manager');
}
function cancelLanguageManager() {
    global $database, $mosConfig_absolute_path;
    $row = new mosMedialibrary($database); // for 1.6
    $row->bind($_POST);
    mosRedirect('index.php?option=com_medialibrary&section=language_manager');
    }

    function cloneMedia($option, $bid, $media_type) {
        global $database, $my, $mosConfig_live_site, $doc, $medialibrary_configuration, $mosConfig_absolute_path;
        $doc->addStyleSheet($mosConfig_live_site . '/components/com_medialibrary/includes/medialibrary.css');
        $medialibrary = new mosMediaLibrary($database);
        $category = new mainMedialibraryCategories($database);
        $medialibrary->load(intval($bid));
        //print_r($medialibrary);exit;
        switch ($medialibrary->media_type) {
            case 'book':
                $media_class = new mosMedialibrary_book($database);
            break;
            case 'video':
                $media_class = new mosMedialibrary_video($database);
            break;
            case 'music':
                $media_class = new mosMedialibrary_music($database);
            break;
            case 'game':
                $media_class = new mosMedialibrary_game($database);
            break;
        }

        $media_class->load($medialibrary->media_id);
                        //print_r($medialibrary->media_id);exit;
        //set that it's a new record in table
       //print_r($media_class);exit;
        $media_class->id = 0;

/*************************************CLONE PICTURE*************************************/
        if($medialibrary->informationFrom == 0) {
            $uploaddir = '/components/com_medialibrary/covers/';
            $code = guid();
            $photos_without_url = str_replace($uploaddir, '', $media_class->imageURL);
            $media_photos_clon = $code.createNewNameCover($photos_without_url);
            if (!strripos($mosConfig_absolute_path.$uploaddir.$photos_without_url, 'http') and 
                    $photos_without_url != ''){
                if(copy($mosConfig_absolute_path.$uploaddir.$photos_without_url, 
                        $mosConfig_absolute_path.$uploaddir.$media_photos_clon)){
                    $media_class->imageURL = $uploaddir.$media_photos_clon;
                }
            }
        }

/*}
/*************************************END CLONE PICTURE*********************************/
        if (!$media_class->store()) {
            echo "<script> alert('" . addslashes($media->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        //insert new item in category table
        $query = "SELECT catid FROM #__medialibrary_categories"
                ."\n WHERE mediaid=".$medialibrary->id;
//print_r($query);exit;
        $database->setQuery($query);
        $cat_id = $database->loadResult();
        $query = "SELECT fk_people_id FROM #__medialibrary_people_connect"
                ."\n WHERE  fk_media_id=".$medialibrary->id;
        //print_r($query);exit;
        $database->setQuery($query);
        $authors_ids = $database->loadColumn();
       //print_r($authors_ids);exit;


        //end
        //set new record in main table
        $medialibrary->id = 0;
        $medialibrary->media_id = $media_class->id;
        if (!$medialibrary->store()) {
            echo "<script> alert('" . addslashes($media->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        //insert new item in category

        $query = "INSERT INTO #__medialibrary_categories (mediaid, catid) VALUES"
                ."\n ('".$medialibrary->id."','".$cat_id."')";
        $database->setQuery($query);
        $database->query();
        foreach ($authors_ids as $auth_id) {
            $query = "INSERT INTO #__medialibrary_people_connect(fk_media_id, fk_people_id) VALUES"
                    ."\n ('".$medialibrary->id."', '".$auth_id."')";
            $database->setQuery($query);
            $database->query();
        }

        //end


        switch ($medialibrary->media_type) {
            case 'book':
                editing_book($media_class, $medialibrary, $option, $media_class->id);
            break;
            case 'video':
                editing_video($media_class, $medialibrary, $option, $media_class->id);
            break;
            case 'music':
                editing_music($media_class, $medialibrary, $option, $media_class->id);
            break;
            case 'game':
                editing_game($media_class, $medialibrary, $option, $media_class->id);
            break;
        }
    }

    function manageAuthor($option) {
        global $mosConfig_absolute_path,$database,$mosConfig_list_limit;
        global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
        $mainframe = JFactory::getApplication();
        $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
        $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
        $srch_for = $mainframe->getUserStateFromRequest("srch_for{$option}", 'srch_for', '0'); //
        $langshow_filter = $mainframe->getUserStateFromRequest("langshow_filter{$option}", 'langshow_filter', '*');
        $typeshow_filter = $mainframe->getUserStateFromRequest("typeshow_filter{$option}", 'typeshow_filter', '0');
        $search = $mainframe->getUserStateFromRequest("auth_search{$option}", 'auth_search', '');
        $where = array();
        if ($langshow_filter != '*') {
            array_push($where, "p.langshow='$langshow_filter'");
        }
        $typeuages_row = ['All types', 'author', 'game_studio', 'artist', 'video_studio', 'director', 'producer',
          'actor'];

        if ($typeshow_filter != '*' and $typeshow_filter != '0') {
            array_push($where, "p.type='".$typeuages_row[$typeshow_filter]."'");
        }
        if ($search) {
            switch ($srch_for ) {
                case 'autors':
                    array_push($where, "LOWER(p.people_name) LIKE '%$search%'");
                break;
                case 'id':
                    array_push($where, "LOWER(p.id) LIKE '%$search%'");
                break;
                case 'title':
                    array_push($where, "LOWER(other_table.title) LIKE '%$search%'");
                break;
                default:
                    array_push($where, "(LOWER(p.people_name) LIKE '%$search%' OR LOWER(p.id) LIKE
                                        '%$search%' OR LOWER(other_table.title) LIKE '%$search%')");
                break;
            }
        }
        $q = "SELECT count(p.id) FROM #__medialibrary_people_connect AS pc " .
           " LEFT JOIN #__medialibrary AS library ON library.id = pc.fk_media_id" .
        " RIGHT JOIN #__medialibrary_people AS p ON   pc.fk_people_id = p.id ".
         " LEFT JOIN #__medialibrary_lend AS l on library.id = l.fk_mediaid and l.lend_return is null  " .
         " LEFT JOIN #__users AS u on u.id = library.owner_ID ".
         " LEFT JOIN (SELECT g.id, g.title AS title, g.langDescription, 'game' as type, g.comment " .
         " FROM #__medialibrary_game AS g ".
         " UNION all SELECT m.id, m.title AS title, m.langDescription, 'music' as type, m.comment " .
         " FROM #__medialibrary_music AS m  ".
         "UNION all SELECT b.id, b.title AS title, b.langDescription, 'book' as type, b.comment " .
         " FROM #__medialibrary_book AS b " .
         " UNION all SELECT v.id, v.title AS title, v.langDescription, 'video' as type, v.comment " .
         " FROM #__medialibrary_video AS v )".
         " AS other_table ON other_table.id =library.media_id AND other_table.type = library.media_type ".
         (count($where) ? " where " . implode(' AND ', $where) : "") ;
        $database->setQuery($q);
        $total = $database->loadResult();
        echo $database->getErrorMsg();

        $pageNav = new JPagination($total, $limitstart, $limit);

        $query = "SELECT p.id as id, p.people_name as people_name, p.type as type,
            p.hits as hits,  p.published as published,
            p.checked_out as checked_out, p.langshow as langshow, 
            GROUP_CONCAT(DISTINCT other_table.title SEPARATOR ',') AS title 
            FROM #__medialibrary_people_connect AS pc " .
           " LEFT JOIN #__medialibrary AS library ON library.id = pc.fk_media_id" .
         " RIGHT JOIN #__medialibrary_people AS p ON   pc.fk_people_id = p.id ".
               " LEFT JOIN #__medialibrary_lend AS l on library.id = l.fk_mediaid and l.lend_return is null  " .
         " LEFT JOIN #__users AS u on u.id = library.owner_ID ".
         " LEFT JOIN (SELECT g.id, g.title AS title, g.langDescription, 'game' as type, g.comment " .
         " FROM #__medialibrary_game AS g ".
         " UNION all SELECT m.id, m.title AS title, m.langDescription, 'music' as type, m.comment " .
         " FROM #__medialibrary_music AS m  ".
         " UNION all SELECT b.id, b.title AS title, b.langDescription, 'book' as type, b.comment " .
         " FROM #__medialibrary_book AS b " .
         " UNION all SELECT v.id, v.title AS title, v.langDescription, 'video' as type, v.comment " .
         " FROM #__medialibrary_video AS v)".
         " AS other_table ON other_table.id =library.media_id AND other_table.type = library.media_type ".
           (count($where) ? " where " . implode(' AND ', $where) : "") .
         " GROUP BY p.id".
        "\n LIMIT $pageNav->limitstart,$pageNav->limit;";
        //print_r($query);exit;
        $database->setQuery($query);
        $rows = $database->loadObjectlist();

    //Выборка для отображения PEople

    


        for($i=0;$i<count($rows);$i++){

        $result[$i] = "SELECT name FROM  #__users WHERE id='".$rows[$i]->checked_out."'";
        $database->setQuery($result[$i]);
        $username = $database->loadObjectList();

        if(empty($username)) $rows[$i]->checked_out_user = '';
        else $rows[$i]->checked_out_user = $username[0]->name;
        }
            

    // echo '<pre>';
    // print_r($rows);
    // echo '</pre>';


        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $allLanguages = array();
            $lang = JFactory::getLanguage();
            foreach($lang->getLocale()  as  $locale) {
                if (mb_strlen($locale) == 5 && $locale[2] == '_'){
                    $locale[2] = '-';
                    $query = "SELECT title FROM #__medialibrary_languages 
                              WHERE lang_code = '$locale'";
                    $database->setQuery($query);
                    $language_title = $database->loadResult();
                    $language = new ArrayObject;
                    $language->lang_code = $locale;
                    $language->title = $language_title;
                    $languages[] = $language;
                }
            }
        } else {
            $query = "SELECT lang_code, title FROM #__languages";
            $database->setQuery($query);
            $languages = $database->loadObjectList();
        }

        $languages_row[] = mosHTML::makeOption('*', 'All languages');
        if (version_compare(JVERSION, '2.5', 'ge')) {
            foreach($languages as $language) {
                $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
            }
        }

        $langshow_filter = mosHTML::selectList($languages_row, 'langshow_filter', 'class="inputbox inputboxuathors"
            onchange="document.adminForm.submit();", size="1"', 'value', 'text', $langshow_filter);
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            foreach($typeuages_row as $code => $typeuage) {
                $languages_rows[] = mosHTML::makeOption($code, $typeuage);
            }
        } else {
            $languages_rows = $typeuages_row;
        }
        $typeshow_filter = mosHTML::selectList($languages_rows, 'typeshow_filter', 'class="inputbox inputboxutype"
            onchange="document.adminForm.submit();", size="1"', 'value', 'text', $typeshow_filter);
        
        $search_for[] = mosHTML::makeOption('0', _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL);
        $search_for[] = mosHTML::makeOption('id', _MEDIALIBRARY_LABEL_PEOPLE_ID);
        $search_for[] = mosHTML::makeOption('autors', _MEDIALIBRARY_SHOW_SEARCH_FOR_AUTORS);
        $search_for[] = mosHTML::makeOption('title', _MEDIALIBRARY_LABEL_TITLE_MEDIA);
        $search_for_list = mosHTML::selectList($search_for, 'srch_for', 'class="inputbox" size="1" ', 'value',
                        'text', $srch_for);

        HTML_medialibrary::showAuthors($option,$rows,$pageNav, $search, $search_for_list, $langshow_filter, 
                $typeshow_filter);
    }
    function deleteAuthor($option) {
        global $database, $mosConfig_absolute_path;
        $a_ids = JRequest::getVar('bid','');

                foreach ($a_ids as $id) {
                    $authors4del = new mosMediaLibrary_people($database);
                    $authors4del->load($id);
                    $Query = "SELECT fk_media_id FROM #__medialibrary_people_connect WHERE fk_people_id = $id";
                    $database->setQuery($Query);
                    if (count($database->loadObjectlist()) != 0){
                        print_r("<script> alert('"._MEDIALIBRARY_DELETE_MEDIA_FIRST."');
                                window.history.go(-1);</script>");exit;
                    } else {
                        if(!empty($authors4del->id)){
                            $authors4del->delete();
                            $database->setQuery("DELETE FROM #__medialibrary_people_connect 
                                                 WHERE fk_people_id = ($id)");
                            if (!$database->query()) {
                                echo "<script> alert('" . addcslashes($database->stderr()) 
                                    . "'); window.history.go(-1); </script>\n";
                            }
                            
                            $imageURL = $authors4del->imageURL;
                            $file_inf = pathinfo($imageURL);
                            $file_type = '.' . $file_inf['extension'];
                            $file_name = basename($imageURL, $file_type);
                            if(empty($file_name) ){
                                continue ;
                            }                            
                            $path = $mosConfig_absolute_path . '/components/com_medialibrary/covers';
                            $check_files = JFolder::files($path, '^' . $file_name . '.*$', false, true);
                            foreach($check_files as $check_file) {
                                unlink($check_file);
                            }
                        }
                    }
                }


        mosRedirect("index.php?option=$option&task=manage_author");
    }
    function publishAuthor($id, $task, $option) {
        global $database;//print_r($task);exit;
        if ($task == "publish_author") {
            $task = 1;
        } else {
            $task = 0;
        }
    $database->setQuery("UPDATE #__medialibrary_people SET published = $task WHERE id  = $id ");
    if (!$database->query()) {
        echo "<script> alert(\"" . $database->getErrorMsg() . "\"); window.history.go(-1); </script>\n";
        exit();
    }
    mosRedirect("index.php?option=$option&task=manage_author");
}





//EDIT AUTHOR


    function editAuthor($bid, $option) {
        global $database, $my, $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        //load/create author
        $author = new mosMediaLibrary_people($database);
        if($bid){
            $author->load($bid);
        }
        if (!isset($author->owneremail) || ($author->owneremail) == '') {
            $author->owneremail = $my->email;
        }
        if(!isset($author->owner_id) || $author->owner_id == ''){
            $author->owner_id = $my->id;
        }
        //end


        if ($bid) {
            // existing record
            $author->checkout($my->id);
            // code for Link Menu

        } else {
            // new record
            $is_new = true;
            $author->section = $section;
            $author->published = 1;
        }



        //language select
        $query = "SELECT lang_code, title FROM #__languages";
        $database->setQuery($query);
        $languages = $database->loadObjectList();
        $languages_row[] = mosHTML::makeOption('*', 'All');
        if (version_compare(JVERSION, '2.5', 'ge')) {
            foreach($languages as $language) {
                $languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
            }
        }
       //print_r($_FILES['picture_file_author']);exit;
        if (!isset($author->langshow)) $author->langshow = '*';
        $langshow = mosHTML::selectList($languages_row, 'langshow', 'class="inputbox" size="1"', 'value',
                'text', $author->langshow);

        $people_type = array(); 
        $people_type[] = mosHTML::makeOption('actor', 'actor');
        $people_type[] = mosHTML::makeOption('artist', 'artist');
        $people_type[] = mosHTML::makeOption('author', 'author');
        $people_type[] = mosHTML::makeOption('director', 'director');
        $people_type[] = mosHTML::makeOption('game_studio', 'game_studio');
        $people_type[] = mosHTML::makeOption('producer', 'producer');
        $people_type[] = mosHTML::makeOption('video_studio', 'video_studio');

        $message = "";
        if (!isset($author->type)) $author->type = '';
        if($bid){
          $people_type_list = mosHTML::selectList($people_type, 'type', 'class="inputbox" size="1" disabled=true',
           'value', 'text', $author->type);
                
          $selectstring = "SELECT p.id, other_table.title as title, p.type, c.catid, p.people_name as people_name,
              pc.fk_media_id as media_id ".
              " FROM #__medialibrary AS m "
             ."\n LEFT JOIN (SELECT id, title, 'game' as type, asin as asin_isbn FROM #__medialibrary_game " .
              " UNION all SELECT id, title, 'music' as type, asin as asin_isbn FROM #__medialibrary_music " .
              " UNION all SELECT id, title, 'book' as type, isbn as asin_isbn FROM #__medialibrary_book " .
              " UNION all SELECT id, title, 'video' as type, asin as asin_isbn FROM #__medialibrary_video) " .
              " AS other_table ON other_table.id = m.media_id and other_table.type = m.media_type"
             ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id"
             ."\n LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
             ."\n LEFT JOIN #__medialibrary_categories AS c ON c.mediaid = m.id"
             ."\n WHERE p.id = " . $bid               
             ."\n GROUP BY p.id";              
          $database->setQuery($selectstring);
          $rows = $database->loadObjectList();
          
          $database->setQuery("SELECT id FROM #__menu 
                    WHERE 
                       link LIKE 'index.php?option=com_medialibrary&view=all_author%' 
                    or link LIKE 'index.php?option=com_medialibrary&view=allcategories%'
                    or link LIKE 'index.php?option=com_medialibrary&view=allbook%'
                    or link LIKE 'index.php?option=com_medialibrary&view=allgame%'
                    or link LIKE 'index.php?option=com_medialibrary&view=allmusic%'
                    or link LIKE 'index.php?option=com_medialibrary&view=allvideo%'
                    ");
          $ItemId_tmp_from_db = $database->loadResult();
          $media_titles = '';
          foreach($rows as $row2) {
              $link1 = "index.php?option=com_medialibrary&amp;task=view&amp;id=" . $row2->media_id .
                      "&amp;catid=" . $row2->catid . "&amp;Itemid=" . $ItemId_tmp_from_db;
              $media_titles.= '<a href="' . sefRelToAbs($mosConfig_live_site . "/" . $link1) .
                      '" target="_self">' . $row2->title . '</a><br/>';
          }
          if($author->type == "actor") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_ACTOR_DESCTIPTION;
          }  else if($author->type == "artist") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_ARTIST_DESCTIPTION;
          }  else if($author->type == "author") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_AUTHOR_DESCTIPTION;
          }  else if($author->type == "director") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_DIRECTOR_DESCTIPTION;
          }  else if($author->type == "game_studio") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_GAME_STUDIO_DESCTIPTION;
          }  else if($author->type == "producer") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_PRODUCER_DESCTIPTION;
          }  else if($author->type == "video_studio") {      
            $message = _MEDIALIBRARY_ADMIN_CONFIG_VIDEO_STUDIO_DESCTIPTION;
          }
          $message = str_replace("{person_name}", $author->people_name, $message);
          $message = str_replace("{media_titles}", $media_titles, $message);
          
        }else {
          $people_type_list = mosHTML::selectList($people_type, 'type', 
            'class="inputbox" size="1" onchange="set_description(this)"', 'value',
            'text');
        }


        $associateArray = array();
        if (!empty($bid)) {
            $associateArray = edit_author_associate_media($author);
            // print_r($author);exit;
        }
        // $file = $_FILES['picture_file_author'];
        // $author->imageURL = $file['name'];

        //end


        $author->owner = '';
        if($author->owner_id){
            $query = "SELECT name FROM #__users WHERE id= $author->owner_id";
            $database->setQuery($query);
            $author->owner = $database->loadResult();
        }
        HTML_medialibrary::editAuthor($option, $author, $langshow,  
          $associateArray,$people_type_list,$message);
    }








    function cloneAuthor($option, $bid) {
        global $database, $my, $mosConfig_live_site;
        global $mosConfig_absolute_path, $medialibrary_configuration;

        $author = new mosMediaLibrary_people($database);
        $author->load(intval($bid));
        //selcet from table //load result array book_id
        $query = "SELECT fk_media_id FROM #__medialibrary_people_connect WHERE fk_people_id = " . $author->id . "";
        $database->setQuery($query);
        $book_ids = $database->loadColumn();
        $author->id = 0;
        if (!$author->store()) {
            echo "<script> alert('" . addslashes($media->getError()) . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if($book_ids){
            foreach ($book_ids as $book_id) {
                $query = "INSERT INTO #__medialibrary_people_connect(fk_people_id, fk_media_id) VALUES("
                    . $author->id .",". $book_id .")";
                $database->setQuery($query);
                $database->query();
            }
        }
        editAuthor($author->id, $option);

    }
?>
