<?php

/*------------------------------------------------------------------------
# "Hot Joomla Carousel Pro" Joomla module
# Copyright (C) 2010 ArhiNet d.o.o. All Rights Reserved.
# License: http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
# Author: HotJoomlaTemplates.com
# Website: http://www.hotjoomlatemplates.com
-------------------------------------------------------------------------*/

//no direct access
defined('_JEXEC') or die('Direct Access to this location is not allowed.');

require_once (JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
global $mainframe;

// Path assignments
$mosConfig_absolute_path = JPATH_SITE;
$mosConfig_live_site = JURI :: base();
if(substr($mosConfig_live_site, -1)=="/") { $mosConfig_live_site = substr($mosConfig_live_site, 0, -1); }
 
// get parameters from the module's configuration
$enablejQuery = $params->get('enablejQuery','1');
$noConflict = $params->get('noConflict','0');
$articleNumber = $params->get('articleNumber','1');
$carouselImagesPath = $params->get('imageFolder','images/stories');
$objectMargin = $params->get('objectMargin','10'); $objectMarginReal = $objectMargin / 2;
$objectPadding = $params->get('objectPadding','2');
$articleBgColor = $params->get('articleBgColor','#ffffff');
$objectBorderWidth = $params->get('objectBorderWidth','2');
$objectBorderColor = $params->get('objectBorderColor','#000000');
$moduleWidth = $params->get('moduleWidth','500');
$moduleHeight = $params->get('moduleHeight','136');
	$controlPositon = (($moduleHeight - 32) / 2) - 12;
	$moduleHeightControl = $moduleHeight - 25;
$objectWidth = $params->get('objectWidth','145');
$objectHeight = $params->get('objectHeight','128');
$carouselPagination = $params->get('carouselPagination','1');
$carouselAutoSlide = $params->get('carouselAutoSlide','true');
$carouselAutoSlideInterval = $params->get('carouselAutoSlideInterval','3000');
$carouselEffect = $params->get('carouselEffect','slide');
$carouselAnimSpeed = $params->get('carouselAnimSpeed','normal');
$carouselDirection = $params->get('carouselDirection','horizontal');
$arrowDisplay = $params->get('arrowDisplay','1');
	if (!$arrowDisplay) { $arrowDisplayHTML = 'display:none;'; }else{ $arrowDisplayHTML = 'display:block; width:32px;'; }
$arrowStyle = $params->get('arrowStyle','5');
$carouselLoop = $params->get('carouselLoop','1');

$buttonVertPadding = $params->get('buttonVertPadding','3');
$buttonHorizPadding = $params->get('buttonHorizPadding','5');
$buttonBorderColor = $params->get('buttonBorderColor','#cccccc');
$buttonBorderColorActive = $params->get('buttonBorderColorActive','#cccccc');
$buttonBorderSize = $params->get('buttonBorderSize','1');
$buttonBorderSizeActive = $params->get('buttonBorderSizeActive','1');
$buttonRadius = $params->get('buttonRadius','7');
$buttonBgColor = $params->get('buttonBgColor','cccccc');
$buttonBgColorActive = $params->get('buttonBgColorActive','#eeeeee');

$where = $params->get('where','category');
$customItemID = $params->get('customItemID',''); $customItemIDHTML = ''; if($customItemID) { $customItemIDHTML = '&amp;Itemid='.$customItemID; }
$imageLinks = $params->get('imageLinks','');
$linkTarget = $params->get('linkTarget','1'); if ($linkTarget) { $linkTargetHTML = ' target="_blank"'; }
$moduleclass_sfx = $params->get('moduleclass_sfx','');

// source is content category/item
if ($where == 'category' || $where == 'content') {

	// DB Parameters
	$database =& JFactory::getDBO();
	$user =& JFactory::getUser();
	$aid = $user->get('aid', 0);
	$now =& JFactory::getDate();
	$contentConfig = &JComponentHelper::getParams( 'com_content' );
	$access	= !$contentConfig->get('shownoauth');
	
	// Content retrieval settings
	$where_id = trim( $params->get('where_id',''));
	$ordering = $params->get('ordering','rdate');
	$count = intval($params->get('count',5));
	$show_front = intval($params->get('show_front',0));
	// Item display settings
	$display = intval($params->get('display',2));
	$linked	= intval($params->get('linked',1));
	$datecreated = intval($params->get('datecreated',1));
	$dateformat = intval($params->get('dateformat',5));
	$show_category_title = intval($params->get('show_category_title',1));
	$seperator = trim($params->get('seperator','&gt;&gt;'));
	$chars = intval($params->get('chars',''));
	$words = intval($params->get('words',''));
	$more = intval($params->get('more',1));
	$plugins = intval($params->get('plugins',1));
	$hideimages	= intval($params->get('hideimages',0));
	$cleanupimages = intval($params->get('cleanupimages',0));
	$striptags = intval($params->get('striptags',0));
	$allowed_tags = $params->get('allowed_tags',"<br><br /><a><b><i><u><span>"); // these tags will NOT be stripped off!

	switch ( $ordering ) {
		case 'random':
			$orderby = 'rand()';
			break;
		case 'date':
			$orderby = 'a.created';
			break;
		case 'rdate':
			$orderby = 'a.created DESC';
			break;
		case 'alpha':
			$orderby = 'a.title';
			break;
		case 'ralpha':
			$orderby = 'a.title DESC';
			break;
		case 'hits':
			$orderby = 'a.hits DESC';
			break;
		case 'rhits':
			$orderby = 'a.hits ASC';
			break;
		case 'order':
		default:
			$orderby = 'a.ordering';
			break;
	}
	// select between content, category
	switch ( $where ) {
		case 'content':
			$where_clause = "\n AND ( a.id IN (". $where_id .") )";
			break;
		case 'category':  // retrieve content item from specified category
		default:
			$where_clause = "\n AND ( a.catid IN (". $where_id .") )";
			break;
	}
	
	$query = "SELECT a.*, cc.title as ctitle, "
	. " CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(\":\", a.id, a.alias) ELSE a.id END as slug,"
	. " CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(\":\", cc.id, cc.alias) ELSE cc.id END as catslug"
	. "\n FROM #__content AS a"
	. "\n INNER JOIN #__categories AS cc ON cc.id = a.catid"
	. ($show_front == '0' ? "\n LEFT JOIN #__content_frontpage AS f ON f.content_id = a.id" : "")
	. "\n WHERE ( a.state = '1' AND a.checked_out = '0' )"
	. "\n AND ( a.publish_up = '0000-00-00 00:00:00' OR a.publish_up <= '". $now->toMySql() ."' )"
	. "\n AND ( a.publish_down = '0000-00-00 00:00:00' OR a.publish_down >= '". $now->toMySql() ."' )"
	. ( $show_front == '0' ? "\n AND f.content_id IS NULL " : "")
	. $where_clause
	. "\n ORDER BY $orderby LIMIT 0,$count"
	;
	
	$rows = "";
	
	$database->setQuery( $query );
	$rows = $database->loadObjectList();


	// Output
	$html2out = array();

	// Process content
	foreach ( $rows as $row ) {
	
		$row->text = $row->introtext;
		$link = JRoute::_(ContentHelperRoute::getArticleRoute($row->slug, $row->catslug, $row->sectionid));
	
		// Plugin processing
		if ($plugins && ($where == 'category' || $where == 'content')) {
	
			/*
			* Process the prepare content plugins
			/*/
			JPluginHelper::importPlugin('content');
			$module->content = JHtml::_('content.prepare', $module->content);
	
	
		} else {
			$row->text = preg_replace('/{([a-zA-Z0-9\-_]*)\s*(.*?)}/i','', $row->text);
		}
	
		// Cleanup images
		if(!function_exists("cleanImgAttributes")){
			function cleanImgAttributes($string,$tag_array,$attr_array) {
				$attr = implode("|",$attr_array);
				foreach($tag_array as $tag) {
					$tag_regex = "/<($tag).+?>/";
					preg_match_all($tag_regex, $string, $matches, PREG_PATTERN_ORDER);
					foreach($matches as $match){
						$cleanedup = preg_replace('/('.$attr.')=([\\"\\\']).+?([\\"\\\'])/', "", $match[0]);
						$cleanedup = preg_replace('|  +|', ' ', $cleanedup);
						$cleanedup = str_replace(" >",">",$cleanedup);
						$string = str_replace($match[0],$cleanedup,$string);
					}
				}
				return $string;
			}
		}
	
		if ($hideimages==0 && $cleanupimages) {
			$row->text = cleanImgAttributes($row->text,array("img"),array("style","width","height","hspace","vspace","border"));
		}
	
		// HTML cleanup
		if ($striptags) {
			$row->text = strip_tags($row->text, $allowed_tags);
		}
	
		// Character limitation
		if ($chars) {
			if(function_exists("mb_substr")) {
				$row->text = mb_substr($row->text, 0, $chars).'...';
			}
			else {
				$row->text = substr($row->text, 0, $chars).'...';
			}
		}
	
		// Word limitation
		if (!function_exists('word_limiter')) {
			function word_limiter($str, $limit = 100, $end_char = '&#8230;') {
				if (trim($str) == '')
					return $str;
				preg_match('/\s*(?:\S*\s*){'. (int) $limit .'}/', $str, $matches);
				if (strlen($matches[0]) == strlen($str))
					$end_char = '';
				return rtrim($matches[0]).$end_char;
			}
		}
		if ($words) {
			$row->text = word_limiter($row->text,$words);
		}
	
		/* Single item output inside - START HERE */
		$output = "\n";
	
		// Item title
		if ($display != 1) {
			$output .= '<div class="contentheading">';
			if ($linked) { $output .= '<a href="'.$link.'">'; }
			$output .= $row->title;
			if ($linked) { $output .= '</a>'; }
			$output .= "</div>\n";
		}
	
		// Item creation date
		if ($datecreated) {
			
			$output .= '<span class="small">'.JHTML::_('date', $row->created, JText::_('DATE_FORMAT_LC'.$dateformat)).' '.$seperator.'</span> ';
			$output .= "\n"; //line break
		}
	
		// Category display
		if ($show_category_title) {
	
			$output .= '<span class="small">';
			
			if ($show_category_title) { $output .= $row->ctitle;}
				
			$output .= "</span>\n"; //line break
		}
	
		// Item introtext	
		if ($display != 0 || $more) {
			if ($display != 0) {
				$output .= '<div>'.$row->text.'</div>';
				$output .= "\n"; //line break
			}
			if ($more) {
				$output .= '<a class="readon" href="'.$link.$customItemIDHTML.'">'.JText::sprintf('Read more...').'</a>';
				$output .= "\n"; //line break
			}
		}
		/* Single item output - END HERE */
	
		$html2out[] = $output;
	
	}
}

require(JModuleHelper::getLayoutPath('mod_hot_joomla_carousel_pro'));
