<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );


class getGoogleImages {

	function placeImagesHere ($product_name, $product_image= '<img src="noimage.jpg">', $imageblocktitle  = 'Google:', $width="100%",$height="300px;", $images_number = 4, $scroll="auto", $show_noimage ='true', $strip_nonlatin = true , $before_first_comma=true) {
		/************************ Вставка для зображень з Гугла  у випадку, коли нема власного зображення **********/
		/* Перевіряю чи зображення зветься noimage */		

		preg_match ( "|<.*?src=.*?/(noimage)\.(.{3}).*?alt=.*?>|", $product_image, $matches);
		if (isset($matches[1]) && $matches[1]=="noimage") {
			if ($show_noimage ) {
				echo $product_image;
			}

			$search_phrase = $this->prepareSearchPhrase ($product_name, $strip_nonlatin , $before_first_comma);
			$this->getImagesFromGoogle($search_phrase, $product_name, $width, $height, $images_number, $scroll, $imageblocktitle   );
		}
		else {
			echo $product_image;
		}
		

	}
	function prepareSearchPhrase ($search_phrase, $strip_nonlatin= true , $before_first_comma=true   ) {

		if ( !$strip_nonlatin &&  !$before_first_comma   ) {
			return $search_phrase;
		}
//		if ($before_first_comma ) {
//			$search_phrase = explode (",",$search_phrase );
//			$search_phrase = $search_phrase [0];
//		}

if ($before_first_comma ) {


$search_phrase = explode (",",$search_phrase);

if (!empty($search_phrase[1]) && JString::strlen($search_phrase[0]<10)) 

{
$search_phrase = $search_phrase[0].','.$search_phrase[1];
}

else {
$search_phrase = $search_phrase[0];
}
}

$search_phrase1 = explode ("(",$search_phrase);
$search_phrase = $search_phrase1[0].'('.$search_phrase1[1];



		if ( $strip_nonlatin) {
			$search_phrase_preseve = $search_phrase;
			$search_phrase = preg_replace("/[^a-zA-Z0-9\s\.!@#\$%\^&\*\:]/Ui", "", $search_phrase );
			if (JString::strlen ($search_phrase ) < 4 ) {
				$search_phrase = $search_phrase_preseve ;
			}
		}
		else {
			$search_phrase = preg_replace('/"/Ui', "", $search_phrase );
		}


		return $search_phrase ;
	}

//	function getImagesFromGoogle( $search_phrase = 'УНСО', $product_name='УНСО', $width="100%",$height="300px;", $images_number = 4, $scroll="auto", $imageblocktitle ='Google:') {
	function getImagesFromGoogle( $search_phrase = 'УНСО', $product_name='УНСО', $width="100%",$height="100%;", $images_number = 4, $scroll="auto", $imageblocktitle ='Google:') {
		// $images_number = 4; //Вкажіть кількість зображень

		$document =& JFactory::getDocument();
		$document->addScript('http://www.google.com/jsapi' );
		$document->addScriptDeclaration ("google.load('search', '1');" );

		$zagruzka_delete = uniqid( 'zagruzka_delete');
		$google_image = uniqid( 'google_image');
		$searchComplete = uniqid( 'searchComplete');
		
		
		$style= '#'.$google_image.' {    overflow:'.$scroll.';    width:'.$width.';    height:'.$height.';           }';
		$document->addStyleDeclaration($style );
		
		
		//ob_start();

		?>
			
		<script type="text/javascript">
			 /*
			 *  How to search for images and restrict them by size.
			 *  This demo will also show how to use Raw Searchers, aka a searcher that is
			 *  not attached to a SearchControl.  Thus, we will handle and draw the results
			 *  manually.
			 */
			 
			 
			 
			 function <?php echo $searchComplete ?>(searcher) {
				// Check that we got results
				if (searcher.results && searcher.results.length > 0) {
					  // Grab our content div, clear it.
					  var contentDiv = document.getElementById('<?php echo $google_image ?>');
					  //contentDiv.innerHTML = '';
				 
					  // Loop through our results, printing them to the page.
					  var results = searcher.results;
					  for (var i = 0; i < <?php echo $images_number; ?>; i++) {
						 // For each result write it's title and image to the screen
						 var result = results[i];

						 if (result === undefined)  {
							
							break;								 
						 }
						 
						 var imgContainer = document.createElement('div');
						 
						 var title = document.createElement('h2');
						 // We use titleNoFormatting so that no HTML tags are left in the title
						 title.innerHTML = result.titleNoFormatting;
						 title.innerHTML = result.unescapedUrl;
						 
						 
								 
						 var newImg = document.createElement('img');
						 // There is also a result.url property which has the escaped version
						 
						 newImg.src = result.tbUrl;
						 newImg.width = '150';
newImg.height = '125';
						
						 var newA = document.getElementById(i+'<?php echo $google_image ?>').getFirst();    
						 //var newA = document.createElement('a');
						 //var href = document.createAttribute('href');
//newA.href=result.url;
						 
						 <?php 
							$title_img = iconv('UTF-8', 'Windows-1251', $product_name);
							$title_img = ereg_replace  ( "(&quot;)"  , '"' , $title_img ); 
							$title_img = ereg_replace  ( "'"  , '' , $title_img );
							$title_img = iconv('Windows-1251', 'UTF-8', $title_img); 
							//$title_img = mb_ereg_replace  ( "(&quot;)"  , '"' , $product_name, "UTF-8" ); 
							//$title_img = mb_ereg_replace  ( "'"  , '' , $title_img, "UTF-8" );

						 ?>
						 newA.title='<?php echo $imageblocktitle.' '.$title_img ?>';
						 newA.alt='<?php echo $imageblocktitle.' '.$title_img ?>';
						 newA.className = "modal";
//newA.target='_blank';
						 newA.id='test'+i;
						 newA.style.display='block';
						 
						 newA.innerHTML = '<img src="'+newImg.src+'">';
						
						 imgContainer.appendChild(newA);
						
						 
						 //imgContainer.appendChild(title);
						 //imgContainer.appendChild(newImg);
						 
						 // Put our title + image in the content
						 contentDiv.appendChild(imgContainer);

						 
					 }
					 document.getElementById('<?php echo $zagruzka_delete ?>').style.display='none';
				} else {
					document.getElementById('<?php echo $zagruzka_delete ?>').innerHTML='Ничего не найдено';						
				}      
			 }
			 
			 function OnLoad() {
				// Our ImageSearch instance.
				var imageSearch = new google.search.ImageSearch();
				 
				// Restrict to extra large images only
				imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
				google.search.ImageSearch.IMAGESIZE_MEDIUM);
				
				//imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_COLORFILTER,
				//                           google.search.ImageSearch.COLOR_WHITE);
				
				// Here we set a callback so that anytime a search is executed, it will call
				// the searchComplete function and pass it our ImageSearch searcher.
				// When a search completes, our ImageSearch object is automatically
				// populated with the results.
				imageSearch.setSearchCompleteCallback(this, <?php echo $searchComplete ?>, [imageSearch]);
				 
				// Find me a beautiful car.
				
				imageSearch.execute("<?php echo  $search_phrase; ?>");
			 }
			 google.setOnLoadCallback(OnLoad);    
		</script>		
			<?php 
				//echo $search_phrase;
			?>
<?php echo $imageblocktitle ?>			
			<div id="<?php echo $google_image ?>" ; style="height:135px">
				<span id="<?php echo $zagruzka_delete ?>">Загрузка...</span>
				<?php
					for ($i=0; $i<$images_number; $i++) { ?>
						<b id="<?php echo $i.$google_image; ?>"  ><!--noindex--><a  rel="nofollow" class="modal"  style="display:none" href="/images/blank.png"><img src="/images/blank.png" /></a><!--/noindex--></b>
				<?php } ?>
				<?php JHTML::_('behavior.modal'); ?>
			</div>

		<?php 
	} //end getImageFromGoogle
} ?>
