<?php

/*
// K2 Multiple Images plugin by Andrey M
// molotow11@gmail.com
*/

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

jimport('joomla.plugin.plugin');
jimport('joomla.html.parameter');
jimport('joomla.version');

class plgSystemK2MultiImages extends JPlugin {
	
	//frontend gallery view
	function onK2BeforeDisplayContent(&$item, &$params, $limitstart) {
		ini_set("display_errors", "On");			
		error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);		
	
		$mainframe = JFactory::getApplication();
		$plugin = JPluginHelper::getPlugin('system', 'k2multiimages');
		$plgParams = class_exists('JParameter') ? new JParameter($plugin->params) : new JRegistry($plugin->params);
		$pluginPath = JPATH_SITE.'/plugins/system/k2multiimages/K2MultiImages';
		$template = JRequest::getVar("template_name", $plgParams->get("template", ""));

		if(!is_object($item->params)) { //params is string? mod_k2_content fix.
			$item->params = class_exists('JParameter') ? new JParameter($item->params) : new JRegistry($item->params);
		}
		
		$return = '';
		$context = JRequest::getVar("option") . '.' . JRequest::getVar("view");
		switch($context) {
			//itemlist view
			case "com_k2.itemlist" :
				if(!$plgParams->get('incategory')) {
					break;
				}			
				switch($template) {				
					case "slider" :
						$tmpl = "slider";					
					break;
					case "slider-hs" :	
						$tmpl = "slider-hs";						
					break;
					case "" :
					case "standart" :
					case "standard" :
					default :
						$tmpl = "standard";
					break;
				}
				ob_start();
				if(JFile::exists(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/category-{$tmpl}.php")) {
					//template override
					require(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/category-{$tmpl}.php");
				}
				else {
					require($pluginPath."/templates/category-{$tmpl}.php");
				}
				$return .= ob_get_contents();
				ob_end_clean();
			break;
			//item view
			case "com_k2.item" :
				switch($template) {
					case "slider-hs" :					
						$this->addJS();	
						$tmpl = "slider-hs";						
					break;
					case "" :
					case "standart" :
					case "standard" :
						$this->addJS();	
						$tmpl = "standard";
					break;
					default :
						$tmpl = $template;
					break;
				}
				ob_start();
				
				$category_params = new JRegistry($item->category->params);	
				if($category_params->get('theme')) {
					if(JFile::exists(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/com_k2/{$category_params->get('theme')}/item-{$tmpl}.php")) {
						//template override
						require(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/com_k2/{$category_params->get('theme')}/item-{$tmpl}.php");
					}
					else {
						if(JFile::exists(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/item-{$tmpl}.php")) {
							//template override
							require(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/item-{$tmpl}.php");
						}
						else {
							require($pluginPath."/templates/item-{$tmpl}.php");
						}
					}
				}
				else {
					if(JFile::exists(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/item-{$tmpl}.php")) {
						//template override
						require(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/item-{$tmpl}.php");
					}
					else {
						require($pluginPath."/templates/item-{$tmpl}.php");
					}
				}
				$return .= ob_get_contents();
				ob_end_clean();
			break;
		}
		return $return;
	}
	
	//admin form 
	function onRenderAdminForm(&$item, $type, $tab='') {
		if($type == 'item' && $tab == 'other') {
			$mainframe = JFactory::getApplication();
			$pluginPath = JPATH_SITE.'/plugins/system/k2multiimages/K2MultiImages';
			$plugin = new JObject;
			$plugin->name = "K2Multiimages";
			$form = '';
				ob_start();
				if(JFile::exists(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/admin_form.php")) {
					//template override
					require(JPATH_SITE."/templates/".$mainframe->getTemplate()."/html/k2multiimages/admin_form.php");
				}
				else {
					require($pluginPath."/templates/admin_form.php");
				}
				$form .= ob_get_contents();
				ob_end_clean();			
			$plugin->fields = $form;
			return $plugin;
		}
	}
	
	function onBeforeK2Save(&$item, $isNew) {
		//save and edit item
		$pluginPath = JPATH_SITE.'/plugins/system/k2multiimages/K2MultiImages';
		if(JRequest::getVar("option") == "com_k2" && JRequest::getVar("view") == "item" &&
			(JRequest::getVar("task") == "save" || JRequest::getVar("task") == "apply" || JRequest::getVar("task") == "saveAndNew")) {		
			require_once($pluginPath.DS.'administrator'.DS.'models'.DS.'itemmultiimages.php');
			$model = new K2ModelItemMultiImages;					
			$model->save($item, $isNew);
		}	
	}
	
	function onAfterRoute() {
		
		$mainframe = JFactory::getApplication();
		$pluginPath = JPATH_SITE.'/plugins/system/k2multiimages/K2MultiImages';

		//add extra js in itemlist view
		if (JRequest::getVar("option") == "com_k2" && JRequest::getVar("view") == "itemlist" && !$mainframe->isAdmin()) { 		
			$this->addJS();
		}
		
		//remove item in backend
		if (JRequest::getVar("option") == "com_k2" && JRequest::getVar("view") == "items" && 
			$mainframe->isAdmin() && JRequest::getVar("task") == "remove") { 
			require_once($pluginPath.DS."administrator".DS."models".DS."itemsmultiimages.php");
			$model = new K2ModelItemsMultiimages;				
			$model->remove();
		}
		
		//copy item in backend
		if (JRequest::getVar("option") == "com_k2" && JRequest::getVar("view") == "items" && 
			$mainframe->isAdmin() && JRequest::getVar("task") == "copy") {
			require_once($pluginPath.DS."administrator".DS."models".DS."itemsmultiimages.php");
			$model = new K2ModelItemsMultiimages;		
			$model->copy();				
		}
		// sig pro import
		if($_GET['multiimages'] && $_GET['a'] == 'import') {
			$last_id = JRequest::getInt("last_id");
			$query = "SELECT id, title, gallery, catid FROM #__k2_items WHERE gallery != ''";
			if($last_id) {
				$query .= " AND id <= {$last_id}";
			}
			$query .= " ORDER BY id DESC";
			$items = JFactory::getDBO()->setQuery($query)->loadObjectList();
			$totals = JFactory::getDBO()->setQuery("SELECT id FROM #__k2_items WHERE gallery != ''")->loadColumn();
			
			foreach($totals as $k=>$item_id) {
				$current = count($totals) - ($k + 1);
				if(!$last_id || $item_id == $last_id) {
					break;
				}
			}
			
			// getting images
			$path = JPATH_SITE . '/media/k2/galleries/' . $items[0]->id;
			if(JFolder::exists($path)) {
				require_once(JPATH_SITE . '/plugins/system/k2multiimages/K2MultiImages/administrator/models/itemmultiimages.php');
				foreach(JFolder::files($path, '^.*(jpg|png|gif)$') as $counter=>$name) {
					$file_path = $path . '/' . $name;
					K2ModelItemMultiImages::addImageByPath($items[0], $file_path, $counter);
				}
			}
			
			echo "Imported item: {$items[0]->title} (id {$items[0]->id}) <br />";
			echo "{$current}th item(s) of " . count($totals) . " imported<br />";	
			
			if(count($items)) {
				JFactory::getDBO()->setQuery("INSERT INTO #__k2_multiimages_import VALUES ('', {$items[0]->id})")->query();
			}
			
			echo "<span class='next-item-id' style='display: none;'>".$items[1]->id."</span>";		
			die;
		}
		
		// import reset
		if($_GET['multiimages'] && $_GET['a'] == 'reset') {
			JFactory::getDBO()->setQuery("TRUNCATE TABLE #__k2_multiimages_import")->query();
			echo "Cleared.";
			die;
		}
	}
	
	function getCatid($itemid) {
		$db = JFactory::getDBO();
		$query = "SELECT catid FROM #__k2_items WHERE id = {$itemid}";
		$db->setQuery($query);
		return $db->loadResult();
	}
	
	function addJS() {
		$lang = JFactory::getLanguage();
		$lang->load("plg_system_k2multiimages", JPATH_ADMINISTRATOR);
		$pluginPath = JPATH_SITE.'/plugins/system/k2multiimages/K2MultiImages';
		$pluginPathSite = JURI::root().'plugins/system/k2multiimages/K2MultiImages';
		$document = JFactory::getDocument();
		
		$document->addScript($pluginPathSite.'/assets/highslide/highslide-with-gallery.packed.js');
		$document->addStyleSheet($pluginPathSite.'/assets/highslide/highslide.css');						
		$document->addScriptDeclaration("
			hs.graphicsDir = '".$pluginPathSite."/assets/highslide/graphics/';\n
			hs.captionEval = 'this.a.rel';\n
			hs.allowSizeReduction = true;\n
			hs.align = 'center';\n
			hs.zIndexCounter = '10001';\n
			hs.showCredits = 0;\n
			var galleryOptions = {\n
				slideshowGroup: 'gallery',\n
				wrapperClassName: 'dark',\n
				dimmingOpacity: 0.7,\n
				align: 'center',\n
				transitions: ['expand', 'crossfade'],\n
				fadeInOut: true,\n
				wrapperClassName: 'borderless floating-caption',\n
				marginLeft: 100,\n
				marginBottom: 80,\n
				numberPosition: 'caption'\n
			};\n
			hs.addSlideshow({\n
				slideshowGroup: 'gallery',\n
				interval: 5000,\n
				repeat: false,\n
				useControls: true,\n
				fixedControls: 'fit',\n
				overlayOptions: {\n
					className: 'text-controls',\n
					opacity: 0.75,\n
					position: 'bottom center',\n
					offsetX: 0,\n
					offsetY: -15,\n
					hideOnMouseOut: true\n
				}\n
			});\n
			hs.lang = {\n
				loadingText : '".JText::_('PLG_K2_MULTIIMAGES_LOADING')."',\n
				nextText : '".JText::_('PLG_K2_MULTIIMAGES_NEXT')."',\n
				nextTitle : '".JText::_('PLG_K2_MULTIIMAGES_NEXT_TITLE')."',\n
				closeText : '".JText::_('PLG_K2_MULTIIMAGES_CLOSE')."',\n
				closeTitle : '".JText::_('PLG_K2_MULTIIMAGES_CLOSE_TITLE')."',\n
				playText : '".JText::_('PLG_K2_MULTIIMAGES_PLAY')."',\n
				playTitle : '".JText::_('PLG_K2_MULTIIMAGES_PLAY_TITLE')."',\n
				pauseText : '".JText::_('PLG_K2_MULTIIMAGES_PAUSE')."',\n
				pauseTitle : '".JText::_('PLG_K2_MULTIIMAGES_PAUSE_TITLE')."',\n
				previousText : '".JText::_('PLG_K2_MULTIIMAGES_PREVIOUS')."',\n
				previousTitle : '".JText::_('PLG_K2_MULTIIMAGES_PREVIOUS_TITLE')."',\n
				fullExpandText : '".JText::_('PLG_K2_MULTIIMAGES_EXPAND')."',\n
				fullExpandTitle : '".JText::_('PLG_K2_MULTIIMAGES_EXPAND_TITLE')."',\n
				number: '".JText::_('PLG_K2_MULTIIMAGES_IMAGE')." %1 ".JText::_('PLG_K2_MULTIIMAGES_IMAGE_OF')." %2',\n
				restoreTitle : '".JText::_('PLG_K2_MULTIIMAGES_RESTORE_TITLE')."'\n
			};\n	
		");	
	}
}

?>