<?php

// no direct access
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.filesystem.file' );

class K2ModelItemMultiImages {

	function save(&$item, $isNew) {		
		if(JFile::exists(JPATH_SITE.'/administrator/components/com_k2/lib/class.upload.php') && !class_exists("upload")) {
			require_once(JPATH_SITE.'/administrator/components/com_k2/lib/class.upload.php');
		}
		if(JFile::exists(JPATH_SITE.'/media/k2/assets/vendors/verot/class.upload.php/src/class.upload.php') && !class_exists("upload")) {
			require_once(JPATH_SITE.'/media/k2/assets/vendors/verot/class.upload.php/src/class.upload.php');
		}
	
		$db = JFactory::getDBO();
		$params = JComponentHelper::getParams('com_k2');			
		$files = JRequest::get('files');
		
		$k2_image_hash = md5("Image".$item->id);
		if($isNew) {
			$k2_image_hash = md5("Image".$this->getNewId());
		}
		
		//multiple files add////////////
		$files_multi_start = JRequest::getInt("image_multiple_start");
		
		if($files["image_multiple"]["name"][0] != "") {
			foreach($files["image_multiple"]["name"] as $k=>$file) {
				$files["image".$files_multi_start]["name"] = $file;
				$files["image".$files_multi_start]["type"] = $files["image_multiple"]["type"][$k];
				$files["image".$files_multi_start]["tmp_name"] = $files["image_multiple"]["tmp_name"][$k];
				$files["image".$files_multi_start]["error"] = $files["image_multiple"]["error"][$k];
				$files["image".$files_multi_start]["size"] = $files["image_multiple"]["size"][$k];			
				$files_multi_start++;
			}
		}
		////////////////////////////////
		
		$files[] = '';
		
		//caption and credits
		for($i=1; $i<count($files); $i++) {				
			$caption[$i] = JRequest::getVar("image".$i."_caption");
			$credits[$i] = JRequest::getVar("image".$i."_credits");					
		}		
		$item->image_caption = implode("|", $caption);
		$item->image_credits = implode("|", $credits);

		//Image
		if((int)$params->get('imageMemoryLimit')) {
			ini_set('memory_limit', (int)$params->get('imageMemoryLimit').'M');
		}
		
		//Upload Images	
		ini_set("memory_limit", "400M");
		ini_set("upload_max_filesize", "300M");
		ini_set("post_max_size", "300M");
		ini_set("max_execution_time", "300"); 
		ini_set("display_errors", "On");			
		error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
		
		$multiimages_plugin = JPluginHelper::getPlugin('system', 'k2multiimages');
		$plgParams = class_exists('JParameter') ? new JParameter($multiimages_plugin->params) : new JRegistry($multiimages_plugin->params);
			
		$watermark = $plgParams->get("watermark", 0);
		$watermark_image = $plgParams->get("watermark_image", "");
		if($watermark == "1" && $watermark_image != '' && $watermark_image != '-1') {
			$watermark_image = JPATH_SITE.DS.'images'.DS.$watermark_image;
			$watermark_on = 1;
		}
		
		for($i=1; $i<count($files); $i++) {		
			$existingImage = JRequest::getVar('existingImage'.$i);
			if ((@$files['image'.$i]['error'] == 0 || $existingImage) && !JRequest::getBool('del_image'.$i)) {
				if($files['image'.$i]['error'] == 0){
					$image = $files['image'.$i];
				}
				else {
					$image = JPATH_SITE.DS.JPath::clean($existingImage);
				}

				$handle = new Upload($image);
				$handle->allowed = array('image/*');
				if ($handle->uploaded) {

					//Image params
					$category = JTable::getInstance('K2Category', 'Table');
					$category->load($item->catid);
					$cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
					if ($cparams->get('inheritFrom')) {
						$masterCategoryID = $cparams->get('inheritFrom');
						$query = "SELECT * FROM #__k2_categories WHERE id=".(int)$masterCategoryID;
						$db->setQuery($query, 0, 1);
						$masterCategory = $db->loadObject();
						$cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
					}

					$params->merge($cparams);
					if($i > 1) {
						$filename = $k2_image_hash."_".$i;
					}
					else {
						$filename = $k2_image_hash;
					}

					//Original image
					$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'src';
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = 100;
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename;
					$handle->Process($savepath);
					
					//Resized images
					$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache';

					//XLarge image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					if(@$watermark_on) {
						$handle->image_watermark = $watermark_image; 
						$handle->image_watermark_position = "BR";
					}
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_XL';
					if (JRequest::getInt('itemImageXL')) {
						$imageWidth = JRequest::getInt('itemImageXL');
					} else {
						$imageWidth = $params->get('itemImageXL', '800');
					}
					$handle->image_x = $imageWidth;
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}
						
					//Large image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					if(@$watermark_on) {
						$handle->image_watermark = $watermark_image; 
						$handle->image_watermark_position = "BR";
					}
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_L';
					if (JRequest::getInt('itemImageL')) {
						$imageWidth = JRequest::getInt('itemImageL');
					} else {
						$imageWidth = $params->get('itemImageL', '600');
					}
					$handle->image_x = $imageWidth;
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}

					//Medium image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					if(@$watermark_on) {
						$handle->image_watermark = $watermark_image; 
						$handle->image_watermark_position = "BR";
					}
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_M';
					if (JRequest::getInt('itemImageM')) {
						$imageWidth = JRequest::getInt('itemImageM');
					} else {
						$imageWidth = $params->get('itemImageM', '400');
					}
					$handle->image_x = $imageWidth;
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}

					//Small image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_S';
					if (JRequest::getInt('itemImageS')) {
						$imageWidth = JRequest::getInt('itemImageS');
					} else {
						$imageWidth = $params->get('itemImageS', '200');
					}
					$handle->image_x = $imageWidth;
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}

					//XSmall image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_XS';
					if (JRequest::getInt('itemImageXS')) {
						$imageWidth = JRequest::getInt('itemImageXS');
					} else {
						$imageWidth = $params->get('itemImageXS', '100');
					}
					$handle->image_x = $imageWidth;
					
					if($plgParams->get("fixSmall", 0)) {
						$handle->image_y = $imageWidth;
						$handle->image_ratio_crop = true;
                        $handle->image_ratio_y = false;
					}
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}

					//Generic image
					$handle->image_resize = true;
					$handle->image_ratio_y = true;
					$handle->image_convert = 'jpg';
					$handle->jpeg_quality = $params->get('imagesQuality');
					$handle->file_auto_rename = false;
					$handle->file_overwrite = true;
					$handle->file_new_name_body = $filename.'_Generic';
					$imageWidth = $params->get('itemImageGeneric', '300');
					$handle->image_x = $imageWidth;
					
					if ($imageWidth > 0) {
						$handle->Process($savepath);
					}
				}
			}
			
		} // image create
				
		//Delete Images	
		for($i=1; $i<count($files); $i++) {
			if($i > 1) {
				$filename = $k2_image_hash."_".$i;
			}
			else {
				$filename = $k2_image_hash;
			}
			
			if (JRequest::getBool('del_image'.$i)) {				
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$filename.'.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$filename.'.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_XS.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_XS.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_S.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_S.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_M.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_M.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_L.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_L.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_XL.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_XL.jpg');
				}
				if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_Generic.jpg')) {
					JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filename.'_Generic.jpg');
				}
			}			
		} // image delete
		
		//Replace captions and credits after delete
		for($i=count($files); $i>0; $i--) {		
			if (JRequest::getBool('del_image'.$i)) {
				$captions = explode("|", $item->image_caption);
				$credits = explode("|", $item->image_credits);
				
				$arrcount = $i - 1;
				$slice_capt =  count($captions);
				$slice_cred =  count($credits) - $arrcount;
				
				unset($captions[$arrcount]);
				$captions = array_slice($captions, 0);
				
				unset($credits[$arrcount]);
				$credits = array_slice($credits, 0);
				
				$item->image_caption = implode("|", $captions);
				$item->image_credits = implode("|", $credits);			
			}
		}
		
		//Replace Images after delete
		for($i = count($files); $i > 0; $i--) {		
			if (JRequest::getBool('del_image'.$i)) {
					if($i < count($files)) {
						$start = $i+1;
						for($j = $start; $j < count($files); $j++) {
							$filenameCurr = $k2_image_hash."_".$j;
							if(($j-1) > 1) {
								$filenameNew = $k2_image_hash."_".($j-1);
							}
							else {
								$filenameNew = $k2_image_hash;
							}
							
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$filenameCurr.'.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$filenameCurr.'.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$filenameNew.'.jpg';
								JFile::move($src, $dst);
							}							
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_XS.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_XS.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_XS.jpg';
								JFile::move($src, $dst);
							}
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_S.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_S.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_S.jpg';
								JFile::move($src, $dst);
							}
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_M.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_M.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_M.jpg';
								JFile::move($src, $dst);
							}
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_L.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_L.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_L.jpg';
								JFile::move($src, $dst);
							}
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_XL.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_XL.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_XL.jpg';
								JFile::move($src, $dst);
							}
							if (JFile::exists(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_Generic.jpg')) {
								$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameCurr.'_Generic.jpg';
								$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$filenameNew.'_Generic.jpg';
								JFile::move($src, $dst);
							}
						}
					}
			}
		} // image replace
		
		// Ordering images
		$imagesOrdering = JRequest::getVar("imagesOrdering", "");
		
		if($imagesOrdering != "") {
			$imagesOrdering = explode("|", $imagesOrdering);
			$imagesOrdering = array_diff($imagesOrdering, array(''));
			
			$moved = Array();
			foreach($imagesOrdering as $image=>$moveTo) {
				if(in_array($moveTo, $moved)) continue;
				
				$image = $image + 1;
				if($image == $moveTo) continue;
				
				$moved[] = (int)$image;
				$moved[] = (int)$moveTo;
				$moved = array_unique($moved);

				if($image == "1") {
					$moveFrom = $k2_image_hash;
				}
				else {
					$moveFrom = $k2_image_hash."_".$image;
				}

				if($moveTo == "1") {
					$moveTo = $k2_image_hash;
				}
				else {
					$moveTo = $k2_image_hash."_".$moveTo;
				}
				
				$tmp = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.'temp.jpg';
				
				// Source image
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$moveFrom.'.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'src'.DS.$moveTo.'.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy Source image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy Source image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy Source image from tmp to dst <br /><br />";
				}
				
				// XSmall
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_XS.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_XS.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy xsmall image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy xsmall image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy xsmall image from tmp to dst <br /><br />";
				}	

				// Small
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_S.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_S.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy small image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy small image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy small image from tmp to dst <br /><br />";
				}
				
				// Medium
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_M.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_M.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy medium image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy medium image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy medium image from tmp to dst <br /><br />";
				}
				
				// Large
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_L.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_L.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy large image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy large image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy large image from tmp to dst <br /><br />";
				}
				
				// XLarge
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_XL.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_XL.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy xlarge image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy xlarge image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy xlarge image from tmp to dst <br /><br />";
				}
				
				// Generic
				$src = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveFrom.'_Generic.jpg';
				$dst = JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.$moveTo.'_Generic.jpg';
				if(!JFile::copy($src, $tmp)) {
					echo "Error copy generic image from src to tmp <br /><br />";
				}
				if(!JFile::copy($dst, $src)) {
					echo "Error copy generic image from dst to src <br /><br />";
				}
				if(!JFile::copy($tmp, $dst)) {
					echo "Error copy generic image from tmp to dst <br /><br />";
				}			
				JFile::delete(JPATH_ROOT.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.'temp.jpg');
			}
			
			//re-order captions
			$tmp = Array();
			foreach($caption as $k=>$capt) {
				$order_change = @$imagesOrdering[$k-1];
				if(array_key_exists(($k-1), $imagesOrdering)) {
					$tmp[] = $caption[$order_change];
				}
				else {
					$tmp[] = $capt;
				}
			}
			$item->image_caption = implode("|", $tmp);	
			//re-order credits
			$tmp = Array();
			foreach($credits as $k=>$cred) {
				$order_change = @$imagesOrdering[$k-1];
				if(array_key_exists(($k-1), $imagesOrdering)) {
					$tmp[] = $credits[$order_change];
				}
				else {
					$tmp[] = $cred;
				}
			}
			$item->image_credits = implode("|", $tmp);
		}
	}
	
	function getNewId() {
		$db = JFactory::getDBO();
		$query = "SELECT id FROM #__k2_items ORDER BY id DESC LIMIT 1";
		$db->setQuery($query);
		return $db->loadResult() + 1;
	}
	
	function addImageByPath($item, $image_path, $counter) {
		if(JFile::exists(JPATH_SITE.'/administrator/components/com_k2/lib/class.upload.php') && !class_exists("upload")) {
			require_once(JPATH_SITE.'/administrator/components/com_k2/lib/class.upload.php');
		}
		if(JFile::exists(JPATH_SITE.'/media/k2/assets/vendors/verot/class.upload.php/src/class.upload.php') && !class_exists("upload")) {
			require_once(JPATH_SITE.'/media/k2/assets/vendors/verot/class.upload.php/src/class.upload.php');
		}
		
		$params = JComponentHelper::getParams('com_k2');			
		$k2_image_hash = md5("Image".$item->id);

		$multiimages_plugin = JPluginHelper::getPlugin('system', 'k2multiimages');
		$plgParams = class_exists('JParameter') ? new JParameter($multiimages_plugin->params) : new JRegistry($multiimages_plugin->params);
			
		$watermark = $plgParams->get("watermark", 0);
		$watermark_image = $plgParams->get("watermark_image", "");
		if($watermark == "1" && $watermark_image != '' && $watermark_image != '-1') {
			$watermark_image = JPATH_SITE.DS.'images'.DS.$watermark_image;
			$watermark_on = 1;
		}
		
		$handle = new Upload($image_path);
		$handle->allowed = array('image/*');
		if ($handle->uploaded) {
			//Image params
			JTable::addIncludePath(JPATH_SITE.'/administrator/components/com_k2/tables');
			$category = JTable::getInstance('K2Category', 'Table');
			$category->load($item->catid);
			$cparams = class_exists('JParameter') ? new JParameter($category->params) : new JRegistry($category->params);
			if ($cparams->get('inheritFrom')) {
				$masterCategoryID = $cparams->get('inheritFrom');
				$query = "SELECT * FROM #__k2_categories WHERE id=".(int)$masterCategoryID;
				$masterCategory = JFactory::getDBO()->setQuery($query, 0, 1)->loadObject();
				$cparams = class_exists('JParameter') ? new JParameter($masterCategory->params) : new JRegistry($masterCategory->params);
			}

			$params->merge($cparams);
			$counter = $counter + 1;
			if($counter > 1) {
				$filename = $k2_image_hash."_".$counter;
			}
			else {
				$filename = $k2_image_hash;
			}

			//Original image
			$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'src';
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = 100;
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename;
			$handle->Process($savepath);
			
			//Resized images
			$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache';

			//XLarge image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			if(@$watermark_on) {
				$handle->image_watermark = $watermark_image; 
				$handle->image_watermark_position = "BR";
			}
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_XL';
			$imageWidth = $params->get('itemImageXL', '800');
			$handle->image_x = $imageWidth;
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}
				
			//Large image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			if(@$watermark_on) {
				$handle->image_watermark = $watermark_image; 
				$handle->image_watermark_position = "BR";
			}
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_L';
			$imageWidth = $params->get('itemImageL', '600');
			$handle->image_x = $imageWidth;
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}

			//Medium image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			if(@$watermark_on) {
				$handle->image_watermark = $watermark_image; 
				$handle->image_watermark_position = "BR";
			}
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_M';
			$imageWidth = $params->get('itemImageM', '400');
			$handle->image_x = $imageWidth;
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}

			//Small image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_S';
			$imageWidth = $params->get('itemImageS', '200');
			$handle->image_x = $imageWidth;
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}

			//XSmall image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_XS';
			$imageWidth = $params->get('itemImageXS', '100');
			$handle->image_x = $imageWidth;
			
			if($plgParams->get("fixSmall", 0)) {
				$handle->image_y = $imageWidth;
				$handle->image_ratio_crop = true;
				$handle->image_ratio_y = false;
			}
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}

			//Generic image
			$handle->image_resize = true;
			$handle->image_ratio_y = true;
			$handle->image_convert = 'jpg';
			$handle->jpeg_quality = $params->get('imagesQuality');
			$handle->file_auto_rename = false;
			$handle->file_overwrite = true;
			$handle->file_new_name_body = $filename.'_Generic';
			$imageWidth = $params->get('itemImageGeneric', '300');
			$handle->image_x = $imageWidth;
			
			if ($imageWidth > 0) {
				$handle->Process($savepath);
			}
		}
	}
}
