<?php
defined('_JEXEC') or die('Restricted access');

class igUtilityHelper
{
	function getGalleryDimensions($mainFiles, $lboxFiles, $profile)
	{
        //work out the largest width/height of the images
        $largestHeight = 0;
		$largestWidth = 0;
		$largestLboxHeight = 0;
		$largestLboxWidth = 0;

        for ($i=0; $i<count($mainFiles); $i++)
		{
		    $largestWidth = $mainFiles[$i]['width'] > $largestWidth ? $mainFiles[$i]['width'] : $largestWidth;
		    $largestHeight = $mainFiles[$i]['height'] > $largestHeight ? $mainFiles[$i]['height'] : $largestHeight;
		    $largestLboxWidth = $lboxFiles[$i]['width'] > $largestLboxWidth ? $lboxFiles[$i]['width'] : $largestLboxWidth;
		    $largestLboxHeight = $lboxFiles[$i]['height'] > $largestLboxHeight ? $lboxFiles[$i]['height'] : $largestLboxHeight;
        }

		//if the width/height has been manually set in the backend then override
		$largestWidth      = $profile->img_container_width > $largestWidth ? $profile->img_container_width : $largestWidth;
		$largestHeight     = $profile->img_container_height > $largestHeight ? $profile->img_container_height : $largestHeight;
		$largestLboxWidth  = $profile->lbox_img_container_width > $largestLboxWidth ? $profile->lbox_img_container_width : $largestLboxWidth;
		$largestLboxHeight = $profile->lbox_img_container_height > $largestLboxHeight ? $profile->lbox_img_container_height : $largestLboxHeight;
        
		//work out the overall gallery width
		$galleryLboxWidth = $largestLboxWidth;
		
        if($profile->show_large_image == 1)
        {
			$galleryWidth = $largestWidth;
		}
        else
        {
        	if($profile->thumb_container_width != 0)
        	{
        		$galleryWidth = $profile->thumb_container_width;
        	}
        	else
        	{
        		$thumbRowCount = $profile->images_per_row == 0 ? count($mainFiles) : $profile->images_per_row;
            	$galleryWidth = ($profile->thumb_width + 20) * $thumbRowCount;
        	}
        }

		//if the thumbs or descriptions are set to left/right, add on some width
		if( ($profile->photo_des_position == 'left' || $profile->photo_des_position == 'right') && $profile->show_descriptions == 1)
		{
		    $desWidth = $profile->photo_des_width == 0 ? 200 : $profile->photo_des_width;
		    $galleryWidth = $galleryWidth + $desWidth;
		}

		if( ($profile->thumb_position == 'left' || $profile->thumb_position == 'right') && $profile->show_thumbs == 1 && $profile->show_large_image == 1)
		{
		    $thumbRowCount = $profile->images_per_row == 0 ? count($mainFiles) : $profile->images_per_row;
            $profile->thumb_container_width = $profile->thumb_container_width == 0 ? ($profile->thumb_width + 20) * $thumbRowCount : $profile->thumb_container_width;

			$galleryWidth = $galleryWidth + $profile->thumb_container_width;
		}

		if( ($profile->lbox_photo_des_position == 'left' || $profile->lbox_photo_des_position == 'right') && $profile->lbox_show_descriptions == 1)
		{
		    $desWidth = $profile->lbox_photo_des_width == 0 ? 200 : $profile->lbox_photo_des_width;
			$galleryLboxWidth = $galleryLboxWidth + $desWidth;
		}

		if( ($profile->lbox_thumb_position == 'left' || $profile->lbox_thumb_position == 'right') && $profile->lbox_show_thumbs == 1)
		{
		    $thumbRowCount = $profile->lbox_images_per_row == 0 ? count($mainFiles) : $profile->lbox_images_per_row;
            $profile->lbox_thumb_container_width = $profile->lbox_thumb_container_width == 0 ? ($profile->lbox_thumb_width + 20) * $thumbRowCount : $profile->lbox_thumb_container_width;

			$galleryLboxWidth = $galleryLboxWidth + $profile->lbox_thumb_container_width;
		}

        //if the top/bottom description/thumbs width is wider than the current width, make the width bigger
	    if($profile->photo_des_width > $galleryWidth && $profile->show_descriptions == 1 && ($profile->photo_des_position == 'top' || $profile->photo_des_position == 'bottom') )
	    {
	       $galleryWidth =  $profile->photo_des_width;
	    }

	    if($profile->thumb_container_width > $galleryWidth && $profile->show_thumbs == 1 && ($profile->thumb_position == 'top' || $profile->thumb_position == 'bottom'))
	    {
	       $galleryWidth =  $profile->thumb_container_width;
	    }

	    if($profile->lbox_photo_des_width > $galleryLboxWidth && $profile->lbox_show_descriptions == 1 && ($profile->lbox_photo_des_position == 'top' || $profile->lbox_photo_des_position == 'bottom') )
	    {
	       $galleryLboxWidth =  $profile->lbox_photo_des_width;
	    }

	    if($profile->lbox_thumb_container_width > $galleryLboxWidth && $profile->lbox_show_thumbs == 1 && ($profile->lbox_thumb_position == 'top' || $profile->lbox_thumb_position == 'bottom'))
	    {
	       $galleryLboxWidth =  $profile->lbox_thumb_container_width;
	    }

	    //add 10 pixels for large_img padding
	    $galleryWidth = $galleryWidth + 10;
		$galleryLboxWidth = $galleryLboxWidth + 10;

		//add 14px for grey border shadow css
		if($profile->style == 'grey-border-shadow')
		{
            $galleryWidth = $galleryWidth + 14;
            $largestWidth = $largestWidth + 14;
		    $largestHeight = $largestHeight + 14;

		    $galleryLboxWidth = $galleryLboxWidth + 14;
		    $largestLboxWidth  = $largestLboxWidth + 14;
		    $largestLboxHeight = $largestLboxHeight + 14;
		}
		
		if($profile->slideshow_position == 'left-right' && $profile->show_slideshow_controls)
		{
			$galleryWidth = $galleryWidth + 26;
		}
		
		if($profile->lbox_slideshow_position == 'left-right' && $profile->lbox_show_slideshow_controls)
		{
			$galleryLboxWidth = $galleryLboxWidth + 26;
		}

		$sizesArray = array();
		$sizesArray['largestWidth'] = $largestWidth;
		$sizesArray['largestHeight'] = $largestHeight;
		$sizesArray['galleryWidth'] = $galleryWidth;
		$sizesArray['largestLboxWidth'] = $largestLboxWidth;
		$sizesArray['largestLboxHeight'] = $largestLboxHeight;
		$sizesArray['galleryLboxWidth'] = $galleryLboxWidth;

        return $sizesArray;

	}
	
	function writeBreadcrumbs($category)
	{
	    $app = JFactory::getApplication();
	    $db	= JFactory::getDBO();
		$pathway = $app->getPathway();

		$breadCrumbs = array();
		$breadCrumbsLinks = array();

		$Itemid = JRequest::getInt('Itemid', null);
		
		if( !empty($Itemid) )
		{
            $menu = $app->getMenu();
            $active = $menu->getActive();
            $idOfMenuCategory = (isset($active->query['igid'])) ? $active->query['igid'] : $active->id;
		}
		else
		{
		    $idOfMenuCategory = 0;
		}

        if($category->id != $idOfMenuCategory)
		{
            $breadCrumbs[] = $category->name;
            $breadCrumbsLinks[] = '';

            if($category->parent != 0)
            {
                $query = 'SELECT * FROM #__igallery WHERE id = '.(int)$category->parent;
                $db->setQuery($query);
                $bcCategory = $db->loadObject();

                if($bcCategory->id != $idOfMenuCategory)
		        {
                    array_unshift($breadCrumbs, $bcCategory->name);
                    array_unshift($breadCrumbsLinks, JRoute::_('index.php?option=com_igallery&amp;view=category&amp;igid='.$bcCategory->id) );

                    while($bcCategory->parent != 0)
                    {
                    	$query = 'SELECT * FROM #__igallery WHERE id = '.(int)$bcCategory->parent;
                    	$db->setQuery($query);
                    	$bcCategory = $db->loadObject();

                    	if($bcCategory->id == $idOfMenuCategory)
		                {
		                    break;
		                }

		                array_unshift($breadCrumbs, $bcCategory->name);
                    	array_unshift($breadCrumbsLinks, JRoute::_('index.php?option=com_igallery&amp;view=category&amp;igid='.$bcCategory->id) );
		            }
		        }
            }
		}

        for($i=0; $i<count($breadCrumbs); $i++)
		{
			$pathway->addItem($breadCrumbs[$i], $breadCrumbsLinks[$i]);
		}
	}
	
	
	
	function getItemid($catId)
	{
		$app = JFactory::getApplication();
		
		$menu = $app->getMenu();
		$menuItems = $menu->getMenu();
		$igMenuItems = array();
		
		//get all of the menu items that link to a category
		//as $igMenuItems[itemid] = catid
		foreach($menuItems as $key => $value)
		{
			if($value->component == 'com_igallery' && $value->query['view'] == 'category')
			{
				$igMenuItems[$value->id] = $value->query['igid'];
			}
		}
		
		//if there are none, return the current itemid
		if(count($igMenuItems) == 0)
		{
			return JRequest::getVar('Itemid', 1);
		}
		
		//if there is one, return that itemid
		if(count($igMenuItems) == 1)
		{
			return key($igMenuItems);
		}
		
		//if there is more than one...
		if(count($igMenuItems) > 1)
		{
			//if one of the menu items links to the target cat, then return that
			foreach($igMenuItems as $key => $value)
			{
				if($value == $catId)
				{
					return $key;
				}
			}
			
			//otherwise get all of the target cat's parents
			$parentCats = array();
			$db	=& JFactory::getDBO();
			
			$query = 'SELECT * FROM #__igallery WHERE id = '.(int)$catId;
            $db->setQuery($query);
            $row = $db->loadObject();

            while($row->parent != 0)
            {
                $query = 'SELECT * FROM #__igallery WHERE id = '.(int)$row->parent;
                $db->setQuery($query);
                $row = $db->loadObject();
                $parentCats[] = $row->id;
            }
            
            //for each menu item, loop through all the parents and try to find a match
			foreach($igMenuItems as $key => $value)
			{
				for($i=0; $i<count($parentCats); $i++)
				{
					if($value == $parentCats[$i])
					{
						return $key;
					}
				}
			}
			
			//if nothing can be found, return the current itemid
			return JRequest::getVar('Itemid', 1);
		}
	}
	
	function makeHeadJs($category, $profile, $photoList, $galleryWidth,
	$galleryLboxWidth, $mainFiles, $lboxFiles, $thumbFiles, $lboxThumbFiles,
	$source, $catid, $uniqueid)
	{
		
		$headJs = '
//make arrays and classes for the category: '.$category->name.' (id= '.$catid.')
window.addEvent(\'load\', function()
{
if( $chk( document.id(\'main_images_wrapper'.$uniqueid.'\') ) )
{
';

		$headJs .= 		'
	var idArray'.$uniqueid.' = [';
		for($n=0;$n<count($photoList);$n++)
		{
			$headJs .= $photoList[$n]->id.',';
		}
		$headJs = substr($headJs,0,-1);
		$headJs .= '];
		';

		$headJs .= '
	var jsonImagesObject'.$uniqueid.' =
	{';
		
		$headJs .= '
		"general":
		[
		';

		for($i=0; $i < count($photoList); $i++)
		{
			$row =& $photoList[$i];
			
			if(JRequest::getInt('igaddlinks', 0) == 1)
        	{
        		if(strlen($row->link) < 2)
        		{
	        		$limitStart = '';
					if($row->thumb_pagination == 1)
					{
						if($row->ordering > $row->thumb_pagination_amount)
						{
							$group = ceil( $row->ordering / $row->thumb_pagination_amount ) - 1;
							
							if($group > 0)
							{
								$limitStart = '&limitstart='.($group * $row->thumb_pagination_amount);
								$remainder = $row->ordering - ($group * $row->thumb_pagination_amount);
								$row->ordering = $remainder == 0 ? 1 : $remainder;
							}
						}
					}
        			
        			$linkItemid = igUtilityHelper::getItemid($row->gallery_id);
        			$photoList[$i]->link = 'index.php?option=com_igallery&view=category&igid='.$row->gallery_id.'&image='.$row->ordering.'&Itemid='.$linkItemid.$limitStart;
        			$photoList[$i]->target_blank = 0;
        		}
        	}
			$headJs .= '	{"url": "'.$photoList[$i]->link.'", "targetBlank": '.$photoList[$i]->target_blank.', "hits": '.$photoList[$i]->hits.', "alt": "'.$photoList[$i]->alt_text.'"}';
			if($i < (count($photoList) - 1) ){$headJs .= ',
		';}
		}
		
		$headJs .= '
		]';
		
		if($profile->show_large_image == 1)
		{
			$headJs .= ',
		
		"main":
		[
		';

		for($i=0; $i<count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$mainFiles[$i]['folderName'].'/'.$mainFiles[$i]['fullFileName'].'", "width": '.$mainFiles[$i]['width'].', "height": '.$mainFiles[$i]['height'].'}';
			if($i < (count($photoList) - 1) ){$headJs .= ',
		';}
		}
		$headJs .= '
		]';
		}
		
		if($profile->show_thumbs == 1)
		{
		$headJs .= ',

		"thumbs":
		[
		';

		for($i=0; $i < count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$thumbFiles[$i]['folderName'].'/'.$thumbFiles[$i]['fullFileName'].'", "width": '.$thumbFiles[$i]['width'].', "height": '.$thumbFiles[$i]['height'].'}';
			if($i < (count($photoList) - 1) ){$headJs .= ',
		';}
		}
		$headJs .= '
		]
		';
		}
		
		if($profile->lightbox == 1)
		{
		$headJs .= ',

		"lbox":
		[
		';

		for($i=0; $i < count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$lboxFiles[$i]['folderName'].'/'.$lboxFiles[$i]['fullFileName'].'", "width": '.$lboxFiles[$i]['width'].', "height": '.$lboxFiles[$i]['height'].'}';
		if($i < (count($photoList) - 1) ){$headJs .= ',
		';}
		}
		$headJs .= '
		]';
		}
		
		if($profile->lbox_show_thumbs == 1  && $profile->lightbox == 1)
		{
		$headJs .= ',

		"lboxThumbs":
		[
		';

		for($i=0; $i < count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$lboxThumbFiles[$i]['folderName'].'/'.$lboxThumbFiles[$i]['fullFileName'].'", "width": '.$lboxThumbFiles[$i]['width'].', "height": '.$lboxThumbFiles[$i]['height'].'}';
			if($i < (count($photoList) - 1) ){$headJs .= ',
		';}
		}
		$headJs .= '
		]
		';
		}
		
		$headJs .= '
	};

	var igalleryInt = new Class(igalleryClass);

	var igalleryMain'.$uniqueid.' = new igalleryInt
	({
		allowComments: '.$profile->allow_comments.',
		allowRating: '.$profile->allow_rating.',
		alRatingsContainer: \'main_alratings'.$uniqueid.'\',
		catid: \''.$catid.'\',
		desContainer: \'main_des_container'.$uniqueid.'\',
		desPostion: \''.$profile->photo_des_position.'\',
		downArrow: \'main_down_arrow'.$uniqueid.'\',
		downloadType: \''.$profile->download_image.'\',
		downloadId: \'main_download_button'.$uniqueid.'\',
		host: \''.IG_HOST.'\',
		fadeDuration: '.$profile->fade_duration.',
		facebookContainer: \'main_facebook_share'.$uniqueid.'\',
		facebookShare: '.$profile->share_facebook.',
		idArray: idArray'.$uniqueid.',
		imageAssetPath: \''.IG_IMAGE_ASSET_PATH.'\',
		jCommentsMain: \'main_jcomments_wrapper'.$uniqueid.'\',
		jCommentsLbox: \'lbox_jcomments_wrapper'.$uniqueid.'\',
		joomCommentContainer: \'main_joomcomment_wrapper'.$uniqueid.'\',
		jsonImages: jsonImagesObject'.$uniqueid.',
		jsonImagesImageType: jsonImagesObject'.$uniqueid.'.main,
		largeImage: \'main_large_image'.$uniqueid.'\',
		lboxDark: \'lbox_dark'.$uniqueid.'\',
		lboxWhite: \'lbox_white'.$uniqueid.'\',
		lboxScalable: '.$profile->lbox_scalable.',
		lightboxWidth: '.$galleryLboxWidth.',
		lightboxOn: '.$profile->lightbox.',
		leftArrow: \'main_left_arrow'.$uniqueid.'\',
		magnify: '.$profile->magnify.',
		main: 1,
		mainWrapper: \'main_images_wrapper'.$uniqueid.'\',
		numPics: '.count($photoList).',
		numberingOn: '.$profile->show_numbering.',
		numberingContainer: \'main_img_numbering'.$uniqueid.'\',
		preload: '.$profile->preload.',
		prefix: \'main\',
		resizePath: \''.IG_IMAGE_HTML_RESIZE.'\',
		refreshMode: \''.$profile->refresh_mode.'\',
		reportImage: '.$profile->report_image.',
		reportContainer: \'main_report'.$uniqueid.'\',
		rightArrow: \'main_right_arrow'.$uniqueid.'\',
		scrollBoundary: '.$profile->scroll_boundary.',
		scrollSpeed: '.$profile->scroll_speed.',
		showDescriptions: '.$profile->show_descriptions.',
		showUpDown: '.$profile->arrows_up_down.',
		showLeftRight: '.$profile->arrows_left_right.',
		showLargeImage: '.$profile->show_large_image.',
		showThumbs: '.$profile->show_thumbs.',
		showSlideshowControls: '.$profile->show_slideshow_controls.',
		showTags: '.$profile->show_tags.',
		slideshowAutostart: '.$profile->slideshow_autostart.',
		slideshowPause: '.$profile->slideshow_pause.',
		slideshowForward: \'slideshow_forward'.$uniqueid.'\',
		slideshowPlay: \'slideshow_play'.$uniqueid.'\',
		slideshowRewind: \'slideshow_rewind'.$uniqueid.'\',
		tagsContainer: \'main_tags_container'.$uniqueid.'\',
		thumbContainer: \'main_thumb_container'.$uniqueid.'\',
		thumbPostion: \''.$profile->thumb_position.'\',
		thumbTable: \'main_thumb_table'.$uniqueid.'\',
		uniqueid: \''.$uniqueid.'\',
		style: \''.$profile->style.'\',
		upArrow: \'main_up_arrow'.$uniqueid.'\'
	});
	';
	if($profile->lightbox == 1)
	{
		$headJs .= '
	var igalleryLbox'.$uniqueid.' = new igalleryInt
	({
		allowComments: '.$profile->lbox_allow_comments.',
		allowRating: '.$profile->lbox_allow_rating.',
		alRatingsContainer: \'lbox_alratings'.$uniqueid.'\',
		catid: \''.$catid.'\',
		closeImage: \'closeImage'.$uniqueid.'\',
		desContainer: \'lbox_des_container'.$uniqueid.'\',
		desPostion: \''.$profile->lbox_photo_des_position.'\',
		downArrow: \'lbox_down_arrow'.$uniqueid.'\',
		downloadId: \'lbox_download_button'.$uniqueid.'\',
		downloadType: \''.$profile->lbox_download_image.'\',
		host: \''.IG_HOST.'\',
		fadeDuration: '.$profile->lbox_fade_duration.',
		facebookShare: '.$profile->lbox_share_facebook.',
		facebookContainer: \'lbox_facebook_share'.$uniqueid.'\',
		idArray: idArray'.$uniqueid.',
		imageAssetPath: \''.IG_IMAGE_ASSET_PATH.'\',
		jsonImages: jsonImagesObject'.$uniqueid.',
		jsonImagesImageType: jsonImagesObject'.$uniqueid.'.lbox,
		joomCommentContainer: \'lbox_joomcomment_wrapper'.$uniqueid.'\',
		largeImage: \'lbox_large_image'.$uniqueid.'\',
		lboxDark: \'lbox_dark'.$uniqueid.'\',
		lboxWhite: \'lbox_white'.$uniqueid.'\',
		lboxScalable: '.$profile->lbox_scalable.',
		lightboxWidth: '.$galleryLboxWidth.',
		leftArrow: \'lbox_left_arrow'.$uniqueid.'\',
		lightboxOn: '.$profile->lightbox.',
		mainWrapper: \'lbox_white'.$uniqueid.'\',
		magnify: '.$profile->magnify.',
		main: 0,
		numPics: '.count($photoList).',
		numberingOn: '.$profile->lbox_show_numbering.',
		numberingContainer: \'lbox_img_numbering'.$uniqueid.'\',
		preload: '.$profile->lbox_preload.',
		prefix: \'lbox\',
		resizePath: \''.IG_IMAGE_HTML_RESIZE.'\',
		reportImage: '.$profile->lbox_report_image.',
		reportContainer: \'lbox_report'.$uniqueid.'\',
		rightArrow: \'lbox_right_arrow'.$uniqueid.'\',
		refreshMode: \'javascript\',
		scrollBoundary: '.$profile->lbox_scroll_boundary.',
		scrollSpeed: '.$profile->lbox_scroll_speed.',
		showDescriptions: '.$profile->lbox_show_descriptions.',
		showUpDown: '.$profile->lbox_arrows_up_down.',
		showLeftRight: '.$profile->lbox_arrows_left_right.',
		showLargeImage: 1,
		showThumbs: '.$profile->lbox_show_thumbs.',
		showTags: '.$profile->lbox_show_tags.',
		showSlideshowControls: '.$profile->lbox_show_slideshow_controls.',
		slideshowAutostart: '.$profile->lbox_slideshow_autostart.',
		slideshowForward: \'lbox_slideshow_forward'.$uniqueid.'\',
		slideshowPlay: \'lbox_slideshow_play'.$uniqueid.'\',
		slideshowRewind: \'lbox_slideshow_rewind'.$uniqueid.'\',
		slideshowPause: '.$profile->lbox_slideshow_pause.',
		style: \''.$profile->style.'\',
		tagsContainer: \'lbox_tags_container'.$uniqueid.'\',
		thumbContainer: \'lbox_thumb_container'.$uniqueid.'\',
		thumbPostion: \''.$profile->lbox_thumb_position.'\',
		thumbTable: \'lbox_thumb_table'.$uniqueid.'\',
		uniqueid: \''.$uniqueid.'\',
		upArrow: \'lbox_up_arrow'.$uniqueid.'\'
	});

	igalleryMain'.$uniqueid.'.lboxGalleryObject = igalleryLbox'.$uniqueid.';
	igalleryLbox'.$uniqueid.'.mainGalleryObject = igalleryMain'.$uniqueid.';
	';
	}
	$headJs .= '
}
});

';

		return $headJs;
	}
}