<?php
/**
 * JE GroupBuy package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2011 - 2012 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

// Check to ensure this file is included in Joomla!
	defined('_JEXEC') or die('Restricted access');

// Import Joomla predefined functions
	jimport( 'joomla.application.component.view' );

class jegroupbuyViewproductdetails  extends JView
{
	protected $state;
	protected $items;
	protected $pagination;
	protected $total;

	function display( $tpl = null )
	{
		$app		= JFactory::getApplication();
		$params 	= $app->getParams();
		$user	=& JFactory::getUser();

		// Get some data from the models
			$state		= $this->get('State');
			$items		= $this->get('Items');
			$pagination	= $this->get('Pagination');
			$total		= $this->get('total');

	// Check for errors.
			  if (count($errors = $this->get('Errors'))) {
				JError::raiseError(500, implode("\n", $errors));
				return false;
			}
		$db	= JFactory::getDBO();
		$pid = JRequest::getInt("pid","");

		$query		= $db->getQuery(true);
		$query->select('count(*)');
		$query->from('#__jegroupbuy_payment AS p');
		$query->where('p.p_id = '.$pid);
		$db->setQuery($query);
		$number_of_bought		= $db->loadResult();

		$total_bought = $items->total_bought;
		$query		= $db->getQuery(true);
		$query->select('*');
		$query->from('#__jegroupbuy_settings');
		$query->where('id = 1');
		$db->setQuery($query);
		$settings	= $db->loadObject();

		$config = $app->getParams();
		$apikey = $config->get( 'apikey' );

		$lat 		= $items->gmap_latitude;
		$long 		= $items->gmap_longitude;
		?>

		<input type="hidden" id="lat" value="<?php echo $lat; ?>" />
		<input type="hidden" id="longi" value="<?php echo $long; ?>" />

		<?php
		$query		= $db->getQuery(true);
		$query->select('s.*, p.id,p.store_id');
		$query->from('#__jegroupbuy_stores AS s');
		$query->leftJoin('#__jegroupbuy_product As p ON s.id = p.store_id');
		$query->where('p.id = '.$pid);
		$db->setQuery($query);
		$shop		= $db->loadObject();

		if(($number_of_bought >= $total_bought) || ($items->expired == "1"))
		{
			$app->Redirect( JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'));
		}

		$sql = "SELECT c.*,u.name FROM #__jegroupbuy_comments AS c LEFT JOIN #__users AS u ON u.id = c.uid  WHERE c.pid='".$pid."' AND c.uid='".$user->id."' ORDER BY c.cdate DESC";
		$db->setQuery($sql);
		$comments = $db->loadObjectList();
		$query		= $db->getQuery(true);
		$query->select('count(*)');
		$query->from('#__extensions');
		$query->where('type = "component" AND element = "com_acymailing" AND enabled = 1');
		$db->setQuery($query);
		$com_count		= $db->loadResult();

		$getGoogleMap = $this->getGoogleMap($items,$apikey);
		$this->assignRef('com_count', 		$com_count);
		$this->assignRef('items', 		$items);
		$this->assignRef('total',		$total);
		$this->assignRef('pagination',	$pagination);
		$this->assignRef('params',		$params);
		$this->assignRef('number_of_bought',	$number_of_bought);
		$this->assignRef('googlemap',		$getGoogleMap);
		$this->assignRef('comments',		$comments);
		$this->assignRef('userid',$user->id);
		$this->assignRef('faceBook',$this->sharetoFacebook());
		$this->assignRef('twitter',$this->sharetoTwitter());
		$this->assignRef('subscribeEmail',$this->subscribeEmail());
		$this->assignRef('settings',$settings);
		$this->assignRef('shop', $shop);

		$params			= &$state->params;

		$this->_prepareDocument();

		parent::display( $tpl );
	}

	public function sharetoFacebook()
	{

		$pid = JRequest::getInt("pid","");
		$uri	= JURI::getInstance();
		$base	= $uri->toString(array('scheme', 'host', 'port'));
		$microbloglink	= $base.JRoute::_('index.php?option=com_jegroupbuy&view=productdetails&pid='.$pid.'&tmpl=component' , false);
		$url			= $this->cleanUrl( $microbloglink, true );
		$text			= JHtml::_('image', 'components/com_jegroupbuy/assets/images/facebook.gif', JText::_('COM_JEGROUPBUY_SHARETOFACEBOOK'), array('title'=>JText::_('COM_JEGROUPBUY_SHARETOFACEBOOK'),'border'=>0), false);
		$facebooklink	= JHtml::_('link', 'http://www.facebook.com/sharer.php?u='.$url, $text, array('class'=>'fb_share_link', 'target'=>'_blank'));

		return $facebooklink;
	}

	public function subscribeEmail()
	{

		$pid = JRequest::getInt("pid","");
		$uri	= JURI::getInstance();
		$base	= $uri->toString(array('scheme', 'host', 'port'));
		$url	= JRoute::_('index.php?option=com_acymailing&view=user&layout=modify' , false);
		$text			= JHtml::_('image', 'components/com_jegroupbuy/assets/images/subscribe.gif', JText::_('COM_JEGROUPBUY_SUBSCRIBE_NEWSLETTER'), array('title'=>JText::_('COM_JEGROUPBUY_SUBSCRIBE_NEWSLETTER'),'border'=>0), false);
		$output = JHTML::_('link',$url, $text);
		return $output;
	}


	public function sharetoTwitter()
	{
		$pid = JRequest::getInt("pid","");
		$uri	= JURI::getInstance();
		$base	= $uri->toString(array('scheme', 'host', 'port'));
		$microbloglink	= $base.JRoute::_('index.php?option=com_jegroupbuy&view=productdetails&pid='.$pid.'&tmpl=component' , false);
		$url			= $this->cleanUrl( $microbloglink, true );
		$text			= JHtml::_('image', 'components/com_jegroupbuy/assets/images/twitter.gif', JText::_('COM_JEGROUPBUY_SHARETOTWITTER'), array('title'=>JText::_('COM_JEGROUPBUY_SHARETOTWITTER'),'border'=>0), false);
		$twitterlink	= JHtml::_('link', 'http://twitter.com/share', $text, array('class'=>'twitter-share-button', 'data-text'=>$microbloglink, 'data-count'=>'horizontal'));
		return $twitterlink;
	}


	function cleanUrl($string='', $urlencode=false)
	{
		$string			= preg_replace( '`([^\:])\/{2}`', '$1/', $string );
		if( $urlencode )
			$string 	= rawurlencode( $string );

		return $string;
	}

	/**
	 * Prepares the document
	 */
	protected function _prepareDocument()
	{
		$app		= JFactory::getApplication();
		$menus		= $app->getMenu();
		$pathway	= $app->getPathway();
		$title		= null;
		$params 	= $app->getParams();
		$menu		= $menus->getActive();

		// because the application sets a default page title, we need to get it
		// right from the menu item itself
		if (is_object($menu)) {
			$menu_params = new JRegistry;
			$menu_params->loadJSON($menu->params);
			if (!$menu_params->get('page_title')) {
				$params->set('page_title',	JText::_('COM_JEGROUPBUY_TITLE_DEAL_PRODUCT_LIST'));
			}
		}
		else {
			$params->set('page_title',	JText::_('COM_JEGROUPBUY_TITLE_DEAL_PRODUCT_LIST'));
		}

		$title = $params->get('page_title');
		if ($app->getCfg('sitename_pagetitles', 0)) {
			$title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title);
		}

		$this->document->setTitle($title);
	}

	function getGoogleMap($items,$apikey)
	{
		$document =& JFactory::getDocument();
		$width = $items->gmap_width;
		$height = $items->gmap_height;
		$lat = $items->gmap_latitude;
		$long = $items->gmap_longitude;
		$zoom = $items->gmap_zoom;
		$mapName = 'map';
		$mapType = 'ROADMAP';
		$js = "http://maps.google.com/maps?file=api&amp;v=2&amp;key=".$apikey;

		$document->addScript($js);

		if($width == '' || $height == '')
		{
			$gmap = '';
		}else
		{
			$gmap = '<div id="map" style="margin-left:auto;margin-right:auto;text-align:center;width:'.$width.'px; height:'.$height.'px"></div>';
		}
		return $gmap;

	}
	function limit_characters ( $str, $n )
	{
		if ( strlen ( $str ) <= $n )
		{
			return $str;
		}
		else {
			return substr ( $str, 0, $n ) . '...';
		}
	}
}

?>

<!--<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAARKYMX3qABRwgBGTOLfvdgBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTmhS_LQj6knfNR9GOtLZ_JFxncNQ" type="text/javascript"></script>-->
<script type="text/javascript">

var map;
var icon0;
var newpoints = new Array();

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

addLoadEvent(loadMap);
addLoadEvent(addPoints);

function loadMap() {
	var lat = document.getElementById('lat').value;
var longi = document.getElementById('longi').value;
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng( lat, longi), 10);
	map.setMapType(G_NORMAL_MAP);

	icon0 = new GIcon();
	icon0.image = "http://www.google.com/mapfiles/marker.png";
	icon0.shadow = "http://www.google.com/mapfiles/shadow50.png";
	icon0.iconSize = new GSize(20, 34);
	icon0.shadowSize = new GSize(37, 34);
	icon0.iconAnchor = new GPoint(9, 34);
	icon0.infoWindowAnchor = new GPoint(9, 2);
	icon0.infoShadowAnchor = new GPoint(18, 25);
}

function addPoints() {

var lat = document.getElementById('lat').value;
var longi = document.getElementById('longi').value;
	newpoints[0] = new Array(lat, longi, icon0);

	for(var i = 0; i < newpoints.length; i++) {
		var point = new GPoint(newpoints[i][1],newpoints[i][0]);
		var popuphtml = newpoints[i][4] ;
		var marker = createMarker(point,newpoints[i][2],popuphtml);
		map.addOverlay(marker);
	}
}

function createMarker(point, icon, popuphtml) {
	var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(popuphtml);
	});
	return marker;
}

</script>

