<?php
/*
// "Frontpage Slideshow" Component for Joomla! 1.5.x - Version 1.7.1
// Copyright (c) 2006 - 2008 JoomlaWorks, a Komrade LLC company.
// This code cannot be redistributed without permission from JoomlaWorks - http://www.joomlaworks.gr.
// More info at http://www.joomlaworks.gr and http://www.frontpageslideshow.net
// Developers: Fotis Evangelou - George Chouliaras
// ***Last update: February 27th, 2008***
*/

// no direct access
defined('_JEXEC') or die('Restricted access');

// Set the table directory
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fpslideshow'.DS.'tables');

// Require the helper
require_once (JPATH_COMPONENT.DS.'helpers'.DS.'toolbars.php');

$mosConfig_absolute_path 	= JPATH_SITE;
$mosConfig_live_site 		= $mainframe->isAdmin() ? $mainframe->getSiteURL() : JURI::base();

require_once( JApplicationHelper::getPath('class') );
require_once( JApplicationHelper::getPath('front_html') );

$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
JArrayHelper::toInteger($cid, array(0));

$user = & JFactory::getUser();
if ( !$user->gid && !in_array($task,array("getcategories","getcontents","getimages")) ) {
	$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') ); 
	exit();
}

$id = JRequest::getVar('id', 0, '', 'int');

if($task=="getimages") {
	HTML_FPSlideShow::showHeaderIM($task);
} else {
	HTML_FPSlideShow::showHeader($task);
}

switch ($task) {

	// SLIDES
	case "cancel":
		cancelSlide( $option );
		break;

	case "slides":
		showSlides( $option, $mosConfig_live_site, $mosConfig_absolute_path );
		break;

	case "new":
		editSlide( 0, $option, $fpss_config );
		break;

	case "edit":
		editSlide( $id, $option, $fpss_config );
		break;

	case "save":
		saveSlide( $option );
		break;

	case "orderup":
		orderSlide( $cid[0], -1, $option );
		break;

	case "orderdown":
		orderSlide( $cid[0], 1, $option );
		break;

	case "saveorder":
		saveOrder( $cid, $option );
		break;

	case "publish":
		publishSlides( $cid, 1, $option );
		break;

	case "unpublish":
		publishSlides( $cid, 0, $option );
		break;

	case "delete":
		deleteSlides( $cid, $option );
		break;

	case 'accesspublic':
		accessMenu( intval( $cid[0] ), 0, $option, $task );
		break;

	case 'accessregistered':
		accessMenu( intval( $cid[0] ), 1, $option, $task );
		break;

	case 'accessspecial':
		accessMenu( intval( $cid[0] ), 2, $option, $task );
		break;

		// HELPERS
	case 'getcategories':
		getcategories();
		break;

	case 'getcontents':
		getcontents();
		break;

	case 'getimages':
		getimages();
		break;

		// CREDITS
	case "credits":
		viewCredits( $option );
		break;

		// DEFAULT
	default:
		showSlides( $option, $mosConfig_live_site, $mosConfig_absolute_path );
		break;
}

HTML_FPSlideShow::showFooter();

function viewCredits( $option ) {
	HTML_FPSlideShow::viewCredits( $option );
}

// SLIDES
function showSlides( $option, $mosConfig_live_site, $mosConfig_absolute_path ) {
	global $mainframe;

	$db = &JFactory::getDBO();

	// limit
	$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
	$limitstart = JRequest::getVar('limitstart', 0);

	// query count
	$query = 'SELECT COUNT(s.id)'
	. ' FROM '._FPSS_TABLE_SLIDES.' AS s'
	;
	$db->setQuery( $query );
	$total = $db->loadResult();

	// pagination
	jimport('joomla.html.pagination');
	$pagination = new JPagination( $total, $limitstart, $limit );

	// main query
	$query = 'SELECT s.*, g.name as groupname '
	. ' FROM '._FPSS_TABLE_SLIDES.' AS s'
	. ' LEFT JOIN #__groups AS g ON g.id = s.registers'
	. ' ORDER BY s.ordering'
	;
	//echo $query;

	$db->setQuery( $query, $pagination->limitstart, $pagination->limit );
	$slides = $db->loadObjectList();

	HTML_FPSlideShow::showSlides( $slides, $pagination, $option, $mosConfig_live_site, $mosConfig_absolute_path );
}

function publishSlides( $cid=null, $state=0, $option ) {
	global $mainframe, $Itemid;

	$db = &JFactory::getDBO();

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	JArrayHelper::toInteger($cid);

	if (count( $cid ) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		JError::raiseError(500, JText::_( 'Select a slide to '.$action, true ) );
	}

	$total = count($cid);
	$cids = implode( ',', $cid );

	$query = "UPDATE "._FPSS_TABLE_SLIDES
	. "\n SET state = $state "
	. "\n WHERE id IN ( $cids )"
	;
	$db->setQuery( $query );
	if (!$db->query()) {
		JError::raiseError(500, $db->getErrorMsg() );
	}

	if (count( $cid ) == 1) {
		$row = new mosFPSlideShowImages( $database );
		$row->checkin( $cid[0] );
	}

	switch ( $state ) {
		case 1:
			$msg = $total .' '.JText::_('FPSS_IMAGES_PUBLISHED_DONE');
			break;

		case 0:
		default:
			$msg = $total .' '.JText::_('FPSS_IMAGES_UNPUBLISHED_DONE');
			break;
	}

	$mainframe->redirect( JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), $msg );
}

function orderSlide( $uid, $inc, $option ) {
	global $mainframe, $Itemid;

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	// Initialize variables
	$db		= & JFactory::getDBO();

	$row = & JTable::getInstance('slide', 'Table');
	$row->load( (int) $uid );
	$row->move( $inc );

	$cache = & JFactory::getCache($option);
	$cache->clean();

	$mainframe->redirect(JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid));
}

function saveOrder( &$cid, $option ) {
	global $mainframe, $Itemid;

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	// Initialize variables
	$db			= & JFactory::getDBO();

	$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
	$order		= JRequest::getVar( 'order', array (0), 'post', 'array' );
	$total		= count($cid);
	$conditions	= array ();

	JArrayHelper::toInteger($cid, array(0));
	JArrayHelper::toInteger($order, array(0));

	// Instantiate an slide table object
	$row = & JTable::getInstance('slide', 'Table');

	// Update the ordering for items in the cid array
	for ($i = 0; $i < $total; $i ++)
	{
		$row->load( (int) $cid[$i] );
		if ($row->ordering != $order[$i]) {
			$row->ordering = $order[$i];
			if (!$row->store()) {
				JError::raiseError( 500, $db->getErrorMsg() );
				return false;
			}
			// remember to updateOrder this group
			$condition = '';
			$found = false;
			foreach ($conditions as $cond)
			if ($cond[1] == $condition) {
				$found = true;
				break;
			}
			if (!$found)
			$conditions[] = array ($row->id, $condition);
		}
	}

	// execute updateOrder for each group
	foreach ($conditions as $cond)
	{
		$row->load($cond[0]);
		$row->reorder($cond[1]);
	}

	$cache = & JFactory::getCache($option);
	$cache->clean();

	$msg = JText::_('FPSS_IMAGES_FULLREORDERING_DONE');
	$mainframe->redirect(JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), $msg);

} // saveOrder

function accessMenu( $uid, $access, $option, $task ) {
	global $mainframe, $Itemid;

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	$db  =& JFactory::getDBO();
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	$n   = count( $cid );

	switch ($task) {

		case 'accessregistered' :
			$access = 1;
			break;

		case 'accessspecial' :
			$access = 2;
			break;

		case 'accesspublic' :
		default:
			$access = 0;
			break;

	}

	JArrayHelper::toInteger( $cid );
	$cids = implode( ',', $cid );

	$query = 'UPDATE '._FPSS_TABLE_SLIDES
	. ' SET registers = ' . (int) $access
	. ' WHERE id IN ( '. $cids.'  )'
	; echo $query;
	$db->setQuery( $query );
	if (!$db->query()) {
		return JError::raiseWarning( 500, $row->getError() );
	}

	$msg =JText::sprintf( 'FPSS_IMAGES_CHANGE_ACCESS_IMAGES', $n );

	$mainframe->redirect(JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), $msg);
}

function editSlide( $uid, $option, $config ) {
	global $mainframe;

	$db =& JFactory::getDBO();

	// SLIDE
	$row =& JTable::getInstance('slide', 'Table');
	$id = intval($uid);
	$row->load($id);
	$slide =& $row;

	$editor =& JFactory::getEditor();
	
	if(!$slide->id) {
		$slide->showtitle=$config->showtitle;
		$slide->showseccat=$config->showseccat;
		$slide->showcustomtext=$config->showcustomtext;
		$slide->showplaintext=$config->showplaintext;
		$slide->showreadmore=$config->showreadmore;
		$slide->registers=0;
	}

	$nullDate = $db->getNullDate();
	if($slide->publish_up==$nullDate) $slide->publish_up="";
	if($slide->publish_down==$nullDate) $slide->publish_down="Never";

	$lists['published'] = JHTML::_('select.booleanlist', 'state', '', $slide->state);
	$lists['publish_up'] = JHTML::_('calendar', $slide->publish_up, 'publish_up', 'publish_up', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19'));
	$lists['publish_down'] = JHTML::_('calendar', $slide->publish_down, 'publish_down', 'publish_down', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'25',  'maxlength'=>'19'));
	$lists['editor'] = $editor->display( 'ctext',  $slide->ctext , '100%', '350', '30', '10' ) ;

	if($slide->menu) {
		$content =& JTable::getInstance('content');
		$content->load( (int)$slide->menu );
		$sectionid = $content->sectionid;
		$categoryid = $content->catid;
	} else { $sectionid = ""; $categoryid = ""; }

	$javascript = "onchange='getCategoryList(this)'";
	$lists['jsections']	= mosFPSlideShow::getJSections( 'sectionid', $sectionid, $javascript );

	if($slide->menu) {
		$javascript = "onchange='getContentList(this)'";
		$lists["jcategories"] = mosFPSlideShow::getJCategories( 'categoryid', $categoryid, $sectionid, $javascript );
		$lists["jcontents"] = mosFPSlideShow::getJContents( 'contentid', $slide->menu, $categoryid, NULL );
	} else {
		$lists["jcategories"] = "<select id=\"categoryid\" name=\"categoryid\" class=\"inputbox\" size=\"1\" onchange=\"getContentList(this)\"><option value=\"0\">".JText::_( 'FPSS_SEL_CATEGORY' )."</option></select>";
		$lists["jcontents"] = "<select id=\"contentid\" name=\"contentid\" class=\"inputbox\" size=\"1\"><option value=\"0\">".JText::_( 'FPSS_SEL_CONTENT' )."</option></select>";
	}

	$lists["menu"] = mosFPSlideShow::builtDropDownMenu( $slide->menu2 );

	$lists['target'] = JHTML::_('select.booleanlist', 'target', '', $slide->target);
	$lists['groups'] = mosFPSlideShow::getAccessgroups($slide->registers);

	$lists['showtitle'] = JHTML::_('select.booleanlist', 'showtitle', '', $slide->showtitle);
	$lists['showseccat'] = JHTML::_('select.booleanlist', 'showseccat', '', $slide->showseccat);
	$lists['showcustomtext'] = JHTML::_('select.booleanlist', 'showcustomtext', '', $slide->showcustomtext);
	$lists['showplaintext'] = JHTML::_('select.booleanlist', 'showplaintext', '', $slide->showplaintext);
	$lists['showreadmore'] = JHTML::_('select.booleanlist', 'showreadmore', '', $slide->showreadmore);


	HTML_FPSlideShow::editSlide( $slide, $option, $lists, $config );


}

function cancelSlide( $option ) {
	global $mainframe, $Itemid;

	$mainframe->redirect(JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), $msg);
}

function saveSlide( $option ) {
	global $mainframe, $Itemid;

	$db =& JFactory::getDBO();

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	// load config file
	require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fpslideshow'.DS.'configuration.php');
	$config = new FPSSConfig();

	// load upload file
	require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fpslideshow'.DS.'class.upload.php');

	$live_site = $mainframe->isAdmin() ? $mainframe->getSiteURL() : JURI::base();
	//JPATH_ROOT

	$nullDate 	= $db->getNullDate();

	$option = JRequest::getCmd( 'option');

	$row =& JTable::getInstance('slide', 'Table');

	//JRequest::getVar( 'listdir', _FPSSBASEPATH, 'get', 'text' );
	$imageaction = JRequest::getVar( 'imageaction', 1, 'post', 'int' );
	$oldpathtype = JRequest::getVar( 'oldpathtype', 0, 'post', 'int' );
	$serverimage = JRequest::getVar( 'serverimage', '', 'post', 'text' );
	$resize_x = JRequest::getVar( 'resize_x', 300, 'post', 'int' );
	$quality = JRequest::getVar( 'quality', 80, 'post', 'int' );

	if ((!$_FILES['image']['size'] && $serverimage==""  ) && !$oldpathtype)
	{
		$mainframe->redirect( JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), JText::_('FPSS_IMAGES_ALERT_MUST_IMAGE') );
		exit();
	}

	if (!$row->bind(JRequest::get('post')))
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	//upload image
	if($imageaction==2) {
		if($_FILES['image']['size']>0) {
			$handle = new Upload($_FILES['image']);
			if ($handle->uploaded) {

				if($resize_x == 0) {
					$width  = $config->width;
					$height = 0;
				} else {
					$width  = $resize_x;
					//$height = intval($FPSS_CONFIG['height']);
				}

				if($width > 0 || $height > 0) {
					$handle->image_resize = true;
				}
				if($width > 0 && $height > 0) {
					$handle->image_x = $width;
					$handle->image_y = $height;
				}
				if($width > 0 && $height == 0) {
					$handle->image_x = $width;
					$handle->image_ratio_y = true;
				}
				if($height > 0 && $width == 0) {
					$handle->image_y = $height;
					$handle->image_ratio_x = true;
				}

				// quality checker -- must convert the image to JPG
				$handle->image_convert = 'jpg';
				if($quality>10) {
					$handle->jpeg_quality  = $quality;
				} else {
					$handle->jpeg_quality  = $config->quality;
				}

				$handle->Process(JPATH_ROOT.DS."components".DS.$option.DS."images".DS);
				if ($handle->processed) {
					$row->path = "components/".$option."/images/".$handle->file_dst_name;
					if($oldpathtype==1) {
						$sl =& JTable::getInstance('slide', 'Table');
						$sl->load((int)$row->id);
						@unlink(JPATH_ROOT.DS.$sl->path);
					}
					$row->path_type=1;
				} else {
					echo "<script> alert('Cannot save uploaded file'); window.history.go(-1); </script>\n";
					exit();
				}
			} else {
				echo "<script> alert('Cannot upload file ".$_FILES['image']['size']."'); window.history.go(-1); </script>\n";
				exit();
			}
		}
	} elseif($imageaction==3) {
		$row->path = str_replace($live_site,"",$serverimage);
		if($oldpathtype==1) {
			$sl =& JTable::getInstance('slide', 'Table');
			$sl->load((int)$row->id);
			@unlink(JPATH_ROOT.DS.$sl->path);
		}
		$row->path_type=2;
	}


	// sanitise id field
	$row->id = (int) $row->id;

	if ($row->publish_up == '') {
		$row->publish_up = $nullDate;
	}

	if (trim( $row->publish_down ) == 'Never' || trim( $row->publish_down ) == '') {
		$row->publish_down = $nullDate;
	}

	if($row->publish_up>$row->publish_down) {
		$row->publish_up = $nullDate;
		$row->publish_down = $nullDate;
	}

	$row->state = JRequest::getVar( 'published', 0, 'post', 'int' );
	$row->target = JRequest::getVar( 'target', 0, 'post', 'int' );
	$row->menu = JRequest::getVar( 'contentid', 0, 'post', 'int' );
	$row->registers = JRequest::getVar( 'registers', 0, 'post', 'int' );

	$row->name = $name = JRequest::getVar( 'name', '', 'post', 'text' );
	$row->ctext = JRequest::getVar( 'ctext', '', 'post', 'string', JREQUEST_ALLOWRAW );
	$row->plaintext = JRequest::getVar( 'plaintext', '', 'post', 'text' );

	$row->showtitle = JRequest::getVar( 'showtitle', 0, 'post', 'int' );
	$row->showseccat = JRequest::getVar( 'showseccat', 0, 'post', 'int' );
	$row->showcustomtext = JRequest::getVar( 'showcustomtext', 0, 'post', 'int' );
	$row->showplaintext = JRequest::getVar( 'showplaintext', 0, 'post', 'int' );
	$row->showreadmore = JRequest::getVar( 'showreadmore', 0, 'post', 'int' );

	$linkto = JRequest::getVar( 'linkto', 0, 'post', 'int' );
	switch ($linkto) {
		case 1:
			$row->menu=0;
			$row->menu2=0;
			break;

		case 2:
			$row->clink="";
			$row->menu2=0;
			break;

		case 3:
		default:
			$row->clink="";
			$row->menu=0;
			break;

	}

	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	$row->checkin();
	$row->reorder();

	$msg = JText::sprintf( 'FPSS_SLIDE_SAVED' );
	$mainframe->redirect( JRoute::_('index.php?option='.$option.'&task=slides&Itemid='.$Itemid), $msg );

}

function deleteslides( $cid, $option )
{
	global $mainframe, $option;

	// Check for request forgeries
	JRequest::checkToken() or die( 'Invalid Token' );

	$db  =& JFactory::getDBO();
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	$n   = count( $cid );

	JArrayHelper::toInteger( $cid );

	foreach ($cid as $id) {

		$slide =& JTable::getInstance('slide', 'Table');
		$slide->load($id);
		if($slide->delete( $id )) {
			if($slide->path_type==1) @unlink(JPATH_ROOT.DS.$slide->path);
			$slide->reorder();
		}

	}

	$msg =JText::sprintf( 'FPSS_SLIDES_SUCC_DELETED', $n );

	$mainframe->redirect(JROUTE::_('index.php?option='.$option.'&task=slides', false), $msg);

}






/////////////////////////////// HELPERS  ////////////////////////////////////////////////

// JSON
function getcategories() {

	$db =& JFactory::getDBO();

	$sid = JRequest::getVar( 'sid', 0, 'get', 'int' );

	if (!headers_sent()) {

		while(@ob_end_clean());
		ob_start();

		// build list of sections
		$query = "SELECT cc.id AS value, cc.title AS text"
		. "\n FROM #__categories AS cc"
		. "\n WHERE published = '1'"
		. "\n AND section = '$sid'"
		. "\n ORDER BY cc.ordering"
		;

		$db->setQuery($query);
		$categories = $db->loadObjectList();
		//echo $query;
		echo "obj.options[obj.options.length] = new Option('".JText::_('FPSS_SEL_CATEGORY')."','0');";
		foreach ($categories as $category) {
			$s = str_replace("'","\'",$category->text);
			echo "obj.options[obj.options.length] = new Option('$s','$category->value');";
		}

		$out = ob_get_contents();

		ob_end_clean();

		echo $out;

		exit();

	} else echo "Headers sent!";

}

function getcontents() {

	$db =& JFactory::getDBO();

	$cid = JRequest::getVar( 'cid', 0, 'get', 'int' );

	if (!headers_sent()) {

		while(@ob_end_clean());
		ob_start();

		// build list of sections
		$query = "SELECT c.id AS value, c.title AS text"
		. "\n FROM #__content AS c"
		. "\n WHERE state = '1'"
		. "\n AND catid = '$cid'"
		. "\n ORDER BY c.ordering"
		;

		$db->setQuery($query);
		$contents = $db->loadObjectList();
		//echo $query;
		echo "obj.options[obj.options.length] = new Option('".JText::_('FPSS_SEL_CONTENT')."','0');";
		foreach ($contents as $content) {
			$c = str_replace("'","\'",$content->text);
			echo "obj.options[obj.options.length] = new Option('$c','$content->value');";
		}

		$out = ob_get_contents();

		ob_end_clean();

		echo $out;

		exit();

	} else {
		echo "Headers sent!";
	}

}


// FPSS IMAGE MANAGER (POPUP)

function makeSafe( $file ) {
	return str_replace( '..', '', urldecode( $file ) );
}

function getimages() {

	global $mainframe;
	$live_site = $mainframe->isAdmin() ? $mainframe->getSiteURL() : JURI::base();

	require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fpslideshow'.DS.'configuration.php');
	$config = new FPSSConfig();

	if(!defined("_FPSSBASEPATH")) define("_FPSSBASEPATH",$config->basepath);
	if(!defined("_FPSSLIVESITE")) define("_FPSSLIVESITE",$live_site);

	$listdir = JRequest::getVar( 'listdir', _FPSSBASEPATH, 'get', 'text' );
	$listdir = makeSafe($listdir);

	$js =  '<script type="text/javascript" language="javascript">
				<!--
					function sendtomain(thesi) {
						opener.document.forms[\'adminForm\'].serverimage.value = document.getElementById(\'image\' + thesi).src;
						window.close();
						return false;
					}
				//-->
			</script>';

	$mainframe->addCustomHeadTag($js);

		?>
        <div id="jwfpss-imgbrowser">
		<form method="get" name="adminForm" action="index2.php">
	  		<div class="changedir">
				<?php echo JText::_( 'FPSS_IMGBR_DIR'); ?> <?php echo changeDir($listdir); ?>
                <div class="jwfpss-clr"></div>
            </div>
        	<h2><?php echo JText::_( 'FPSS_IMGBR_LIST'); ?></h2>
        	<div class="jwpds-comments"><?php echo JText::_( 'FPSS_IMGBR_CLICK'); ?></div>            
	  		<?php echo showDir($listdir); ?>
	    	<input type="hidden" name="option" value="com_fpslideshow">
	    	<input type="hidden" name="task" value="getimages">
		</form>
        </div>
		<?php 


}

function changeDir( $listdir ) {

	$imgFiles 	= listofdirectories( _FPSSBASEPATH );
	$images 	= array();
	$folders 	= array();
	$folders[] 	= JHTML::_('select.option', _FPSSBASEPATH, '/', 'id', 'name');

	$len = strlen( _FPSSBASEPATH );
	foreach ($imgFiles as $file) {
		$folders[] 	= JHTML::_('select.option', $file, substr( $file, $len ), 'id', 'name');
	}
	if (is_array( $folders )) {
		sort( $folders );
	}

	return JHTML::_('select.genericlist',  $folders, 'listdir', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'id', 'name', $listdir);
}

function listofdirectories( $listdir ) {

	static $filelist = array();
	static $dirlist = array();

	if(is_dir(JPATH_BASE.DS.$listdir)) {
		$dh = opendir(JPATH_BASE.DS.$listdir);
		while (false !== ($dir = readdir($dh))) {
			if (is_dir(JPATH_BASE.DS.$listdir .'/'. $dir) && $dir !== '.' && $dir !== '..' && strtolower($dir) !== 'cvs' && strtolower($dir) !== '.svn') {
				$subbase = $listdir .'/'. $dir;
				$dirlist[] = $subbase;
				$subdirlist = listofdirectories($subbase);
			}
		}
		closedir($dh);
	}
	return $dirlist;
}

function showDir($listdir) {

	// get list of images
	$d = @dir( JPATH_BASE.DS.$listdir);

	if($d) {
		//var_dump($d);
		$images 	= array();
		$allowable 	= 'gif|jpg|png';

		while (false !== ($entry = $d->read())) {
			$img_file = $entry;
			if(is_file( JPATH_BASE.DS.$listdir.'/'.$img_file) && substr($entry,0,1) != '.' && strtolower($entry) !== 'index.html' ) {
				if (eregi( $allowable, $img_file )) {
					$image_info 				= @getimagesize( JPATH_BASE.DS.$listdir.'/'.$img_file);
					$file_details['file'] 		= JPATH_BASE.DS.$listdir."/".$img_file;
					$file_details['img_info'] 	= $image_info;
					$file_details['size'] 		= filesize( JPATH_BASE.DS.$listdir."/".$img_file);
					$images[$entry] 			= $file_details;
				}
			}
		}
		$d->close();

		if(count($images) > 0 || count($folders) > 0 || count($docs) > 0) {
			//now sort the folders and images by name.
			ksort($images);

			if(count($images)>0) {
				$j=0;
				echo "<table class=\"adminList\">
						<tr>
							<th>".JText::_('_FPSS_IMGBR_PREVIEW')."</th>
							<th>".JText::_('_FPSS_IMGBR_FILENAME')."</th>
							<th>".JText::_('_FPSS_IMGBR_DIMENSIONS')."</th>
							<th>".JText::_('_FPSS_IMGBR_SIZE')."</th>
						</tr>	
					";			
				for($i=0; $i<count($images); $i++) {

					$image_name = key($images);
					show_image($images[$image_name]['file'], $image_name, $images[$image_name]['img_info'], $images[$image_name]['size'],$listdir,$i);
					next($images);

				}
				echo "</table>";
			}

		}
	}
}

function show_image($img, $file, $info, $size, $listdir, $i) {

	$img_file 		= basename($img);
	$img_url_link 	= _FPSSLIVESITE.$listdir ."/". rawurlencode( $img_file );
	$filesize 		= parse_size( $size );
	if ( ( $info[0] > 120 ) || ( $info[0] > 120 ) ) {
		$img_dimensions = imageResize($info[0], $info[1], 120);
	} else {
		$img_dimensions = 'width="'. $info[0] .'" height="'. $info[1] .'"';
	}
		?>
		<tr>
  			<td><img id="image<?php echo $i?>" onmouseover="this.style.cursor='pointer'" onclick="javascript:sendtomain(<?php echo $i?>);" src="<?php echo $img_url_link; ?>" <?php echo $img_dimensions; ?> border="0" /></td>
  			<td><b><?php echo htmlspecialchars( substr( $file, 0, 20 ) . ( strlen( $file ) > 20 ? '...' : ''), ENT_QUOTES ); ?></b></td>
  			<td><b class="red"><?php echo $info[0]; ?>x<?php echo $info[1]; ?>px</b></td>
  			<td><?php echo $filesize; ?></td>
		</tr>
		<?php
}

function parse_size($size){
	if($size < 1024) {
		return $size.' bytes';
	} else if($size >= 1024 && $size < 1024*1024) {
		return sprintf('%01.2f',$size/1024.0).' Kb';
	} else {
		return sprintf('%01.2f',$size/(1024.0*1024)).' Mb';
	}
}

function imageResize($width, $height, $target) {

	if ($width > $height) {
		$percentage = ($target / $width);
	} else {
		$percentage = ($target / $height);
	}

	$width = round($width * $percentage);
	$height = round($height * $percentage);

	return "width=\"$width\" height=\"$height\"";

}
// END

?>
