<?php
/**
 * copyright (C) 2008 GWE Systems Ltd - All rights reserved
 */

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

/**
 * HTML View class for the component frontend
 *
 * @static
 */
class DefaultModCalendarPlusView
{
	var $_modid = null;

	/* parameters form module or component */
	var $displayLastMonth		= null;
	var $disp_lastMonthDays		= null;
	var $disp_lastMonth			= null;

	var $displayNextMonth		= null;
	var $disp_nextMonthDays		= null;
	var $disp_nextMonth			= null;

	var $linkCloaking			= null;

	/* component only parameter */
	var $com_starday			= null;

	/* module only parameters */
	var $minical_showlink		= null;
	var $minical_prevyear		= null;
	var $minical_prevmonth		= null;
	var $minical_actmonth		= null;
	var $minical_actyear		= null;
	var $minical_nextmonth		= null;
	var $minical_nextyear		= null;

	/* class variables */
	var $catidsOut				= null;
	var $modcatids				= null;
	var $catidList				= "";
	var $aid					= null;
	var $lang					= null;
	var $myItemid				= 0;
	var $cat 					= "";

	/* modules parameter object */
	var $modparams				= null;

	// data model for module
	var $datamodel				= null;

	function __construct($params, $modid){

		$this->_modid = $modid;

		$user = JFactory::getUser();

		$cfg = JEVConfig::getInstance();
		$jev_component_name  = JEV_COM_COMPONENT;
		$db	= JFactory::getDBO();

		$this->datamodel = new JEventsDataModel();

		// component config object
		$jevents_config		= JEVConfig::getInstance();

		$this->modparams	= & $params;
		$this->aid			= $user->aid;
		$tmplang			= JFactory::getLanguage();

		// get params exclusive to module
		$this->minical_showlink		= $this->modparams->get('minical_showlink', 1);;
		$this->minical_prevyear		= $this->modparams->get('minical_prevyear', 1);;
		$this->minical_prevmonth	= $this->modparams->get('minical_prevmonth', 1);;
		$this->minical_actmonth		= $this->modparams->get('minical_actmonth', 1);;
		$this->minical_actmonth		= $this->modparams->get('minical_actmonth', 1);;
		$this->minical_actyear		= $this->modparams->get('minical_actyear', 1);;
		$this->minical_nextmonth	= $this->modparams->get('minical_nextmonth', 1);;
		$this->minical_nextyear		= $this->modparams->get('minical_nextyear', 1);;

		// get params exclusive to component
		$this->com_starday	= intval($jevents_config->get('com_starday',0));

		// make config object (module or component) current
		if (intval($this->modparams->get('modcal_useLocalParam',  0)) == 1) {
			$myparam	= & $this->modparams;
		} else {
			$myparam	= & $jevents_config;
		}

		// get com_event config parameters for this module
		$this->displayLastMonth		= $myparam->get('modcal_DispLastMonth', 'NO');
		$this->disp_lastMonthDays	= $myparam->get('modcal_DispLastMonthDays', 0);
		$this->linkCloaking			= $myparam->get('modcal_LinkCloaking', 0);

		$t_datenow = JEVHelper::getNow();
		$this->timeWithOffset = $t_datenow->toUnix(true);

		switch($this->displayLastMonth) {
			case 'YES_stop':
				$this->disp_lastMonth = 1;
				break;
			case 'YES_stop_events':
				$this->disp_lastMonth = 2;
				break;
			case 'ALWAYS':
				$this->disp_lastMonthDays = 0;
				$this->disp_lastMonth = 1;
				break;
			case 'ALWAYS_events':
				$this->disp_lastMonthDays = 0;
				$this->disp_lastMonth = 2;
				break;
			case 'NO':
			default:
				$this->disp_lastMonthDays = 0;
				$this->disp_lastMonth = 0;
				break;
		}

		$this->displayNextMonth		= $myparam->get('modcal_DispNextMonth', 'NO');
		$this->disp_nextMonthDays	= $myparam->get('modcal_DispNextMonthDays', 0);

		switch($this->displayNextMonth) {
			case 'YES_stop':
				$this->disp_nextMonth = 1;
				break;
			case 'YES_stop_events':
				$this->disp_nextMonth = 2;
				break;
			case 'ALWAYS':
				$this->disp_nextMonthDays = 0;
				$this->disp_nextMonth = 1;
				break;
			case 'ALWAYS_events':
				$this->disp_nextMonthDays = 0;
				$this->disp_nextMonth = 2;
				break;
			case 'NO':
			default:
				$this->disp_nextMonthDays = 0;
				$this->disp_nextMonth = 0;
				break;
		}

		// find appropriate Itemid and setup catids for datamodel
		$this->myItemid = $this->datamodel->setupModuleCatids($this->modparams);

		$this->cat = $this->datamodel->getCatidsOutLink(true);

		$this->linkpref = 'index.php?option='.$jev_component_name.'&Itemid='.$this->myItemid.$this->cat.'&task=';

	}

	function getAjaxCal($modid=0, $month, $year){
		// capture module id so that we can use it for ajax type navigation
		if ($modid!=0) {
			$this->_modid=$modid;
		}
		$document = JFactory::getDocument();
		$user = JFactory::getUser();

		$db	= JFactory::getDBO();

		$cfg = JEVConfig::getInstance();

		$year = JRequest::getVar( 'jev_current_year', 0 );
		$month = JRequest::getVar( 'jev_current_month', 0 );

		$reg = JFactory::getConfig();
		$reg->set("jev.modparams",$this->modparams);

		$data = $this->datamodel->getCalendarData($year,$month,1,false, 0);

		$events = $this->getEventsArray($data);

		$result = new JResponseJson($events);

		echo $result;

	} // function getSpecificCal

	function getTheme(){	
		$theme = JEV_CommonFunctions::getJEventsViewName();
		return $theme;

	}

	function getEventsArray($data)
	{
		$events = array();
		foreach ($data['dates'] as $day_index)
		{
			foreach($day_index['events'] as $event)
			{
				$eventArray['date'] = $day_index['year'] ."-".$day_index['month']."-".$day_index['d0']. " " .date("H:i",$event->getUnixStartTime());

				$title = str_replace("'", "&#39;", $event->title());
				$eventArray['title'] = str_replace('"', "&#34;", $title);
				$eventArray['safeTitle'] = addslashes($event->title());
				$link = $event->viewDetailLink($day_index['year'], $day_index['month'], $day_index['d0'], false, $this->myItemid) . $this->datamodel->getCatidsOutLink();
				$eventArray['link'] = JRoute::_($link );
				$eventArray['linkInPopup'] = JRoute::_($link . "&tmpl=component");
				//$eventArray['link'] = $link;
				$events[] = $eventArray;
			}
		}

		return $events;
	}

	function getEventListFormatJS($detailInPopup=0)
	{
		if(!$detailInPopup)
		{
			if( $this->modparams->get('jevcalplus_newwindow', true) )
			{
				$string = 'moment(event.date).format("HH:mm")+" - " + "<a href=\'"+event.link+"\' title=\'"+event.safeTitle+"\' target=\'_blank\'>"+event.title+"</a>"';
			}
			else
			{
				$string = 'moment(event.date).format("HH:mm")+" - " + "<a href=\'"+event.link+"\' title=\'"+event.safeTitle+"\' target=\'_top\'>"+event.title+"</a>"';
			}
		}
		else
		{
			$string = 'moment(event.date).format("HH:mm")+" - " + "<a href=\'#\' title=\'"+event.safeTitle+"\' onClick=\'showPopup(\""+event.safeTitle+"\",\""+event.linkInPopup+"\")\' >"+event.title+"</a>"';
		}


		return $string;
	}

	function getCal($modid=0) {

		if ($modid!=0) {
			$this->_modid=$modid;
		}

		$detailInPopup = $this->modparams->get('detailInPopup', 0);

		$cfg = JEVConfig::getInstance();

		$document = JFactory::getDocument();
		$time = $this->timeWithOffset;
		$cal_year=date("Y",$time);
		$cal_month=date("m",$time);

		$reg = JFactory::getConfig();
		$reg->set("jev.modparams",$this->modparams);

		$data = $this->datamodel->getCalendarData($cal_year,$cal_month,1,false, $this->modparams->get("noeventcheck",0));

		$events = $this->getEventsArray($data);

		$eventsJSON = "var eventArray = ".json_encode(array_values($events));
		$document->addScriptDeclaration($eventsJSON);
		if(!$this->modparams->get('jevcalplus_usebrowserlanguage', false))
		{
			$calendarLanguage = $this->getLanguage();
			$document->addScriptDeclaration($calendarLanguage);
		}				

		$showYearControls = $this->modparams->get('jevcalplus_dispyearcontrols', false);
		$showScroll = $this->modparams->get('jevcalplus_scroll', false);

$script = 'var calendars = {};
			var checkedMonths = ["'.$cal_year.'-'.$cal_month.'"];
(function ($){

	$(document).ready( function() {	
		calendars.clndr1 = $(".jevcalendarplus_calendar").clndr({
			template: $("#template-calendar").html(),
			events: eventArray,
			clickEvents: {
			click: function(target) {
					  if(target.events.length) {
						var listTitle="'.JText::_("JEV_EVENTSFORTHE").' " + moment(target.events[0].date).format("D") + " " + moment(target.events[0].date).format("MMM");
						  listContainer = $("#jevcalendarplus-list-container");
						  $(".jevcalendarplus-row").remove();
						  $.each(target.events, function(index,event){
							  var eventdiv = "<div class=\"jevcalendarplus-row\">" +'.$this->getEventListFormatJS($detailInPopup).' +"</div>";
							  listContainer.append(eventdiv);
						  });
						  var container = $("#jevcalendarplus-container");
						  container.toggleClass("jevcalendarplus-eventslist",true);';

	if($showScroll)
	{
		$script .= 'container.toggleClass("scroll",true);';
		
	}
	else
	{
		$script .= 'var mainCalendar = $(".clndr");
								  var height = $("#jevcalendarplus-list-container").height() + 20;
								  mainCalendar.css("height",height);';
	}

$script .= '$("#jev-close-list").click( function() {
								var mainCalendar = $(".clndr");
								container.toggleClass("jevcalendarplus-eventslist", false);
								container.toggleClass("scroll", false);
								mainCalendar.css("height","");
							});
						  
						  $("#jevcalendarplus-list-header-title").html(listTitle);
					  }
			},
			onMonthChange: function(month){
							var monthToShow = month.format("MM");
							var yearToShow =  month.format("YYYY");
							var index = yearToShow + "-" + monthToShow;
							var container = $("#jevcalendarplus-container");
							var mainCalendar = $(".clndr");
							container.toggleClass("jevcalendarplus-eventslist", false);
							container.toggleClass("scroll", false);
							mainCalendar.css("height","");

							if(checkedMonths.indexOf(index) == -1)
							{
								var parameters = {
										jev_current_month: monthToShow,
										jev_current_year: yearToShow
										};

								var post = $.post("'.Juri::base().'index.php?option=com_jevents&task=getjson.monthevents&modid='.$this->_modid.'&format=json",parameters,
												function(r){
													var eventArrayNext = r.data;
													eventArray = eventArray.concat(eventArrayNext);
													calendars.clndr1.setEvents(eventArray);
													checkedMonths.push(yearToShow + "-" + monthToShow);
												},"json").error(function(e){
														alert("Error in the response");
												});
							}
						}
		  },		    
			showAdjacentMonths: false,
			adjacentDaysChangeMonth: true,
			targets:{
				nextButton:	"jevcalendarplus-next-button",
				previousButton: "jevcalendarplus-previous-button",
				nextYearButton:	"jevcalendarplus-nextyear-button",
				previousYearButton: "jevcalendarplus-previousyear-button"
			}
		  });
	});
})(jQuery);
';

$document->addScriptDeclaration($script);

		$calendarTemplate = '
<div class="jevcalendarplus_container">
    <div class="jevcalendarplus_calendar">
    </div>   
	<script type="text/template" id="template-calendar">
        <div class="jevcalendarplus_calendar_controls">';
		$yearCSSClass = "";
		if($showYearControls)
		{
			$calendarTemplate .= '<div class="jevcalendarplus-previousyear-button">&lsaquo;&lsaquo;</div>';
			$yearCSSClass = "withyears";
		}
			$calendarTemplate .= '<div class="jevcalendarplus-previous-button">&lsaquo;</div>
          <div class="month '.$yearCSSClass.'"><%= month %> <%= year %></div>';
		if($showYearControls)
		{
			$calendarTemplate .= '<div class="jevcalendarplus-nextyear-button">&rsaquo;&rsaquo;</div>';
		}
			$calendarTemplate .= '<div class="jevcalendarplus-next-button">&rsaquo;</div>
        </div>
        <div id="jevcalendarplus-container" class="jevcalendarplus-grid">
          <div class="jevcalendarplus-days-of-the-week">
            <% _.each(daysOfTheWeek, function(day) { %>
              <div class="jevcalendarplus-header-day"><%= day %></div>
            <% }); %>
            <div class="jevcalendarplus-days">
              <% _.each(days, function(day) { %>
                <div class="<%= day.classes %>"><%= day.day %></div>
              <% }); %>
            </div>
          </div>
		  <div class="jevcalendarplus-list" id="jevcalendarplus-list-container">
			<div id="jevcalendarplus-list-header" class="headers">
				<div id="jev-close-list"><i class="icon-undo"></i></div>
				<div id="jevcalendarplus-list-header-title">Events For the day</div>
			</div>
		  </div>
        </div>
		
	</script>
	</div>';
		
		return $calendarTemplate;
	} // function getCal

	function getLanguage()
	{
		$lang = JFactory::getLanguage();

		$script = '	moment.lang("'.$lang->getTag().'", {
						months : "'.JText::_("JEV_JANUARY").'_'.JText::_("JEV_FEBRUARY").'_'.JText::_("JEV_MARCH").'_'.JText::_("JEV_APRIL").'_'.JText::_("JEV_MAY").'_'.JText::_("JEV_JUNE").'_'.JText::_("JEV_JULY").'_'.JText::_("JEV_AUGUST").'_'.JText::_("JEV_SEPTEMBER").'_'.JText::_("JEV_OCTOBER").'_'.JText::_("JEV_NOVEMBER").'_'.JText::_("JEV_DECEMBER").'".split("_"),
						monthsShort : "'.JText::_("JEV_JAN_SHORT").'_'.JText::_("JEV_FEB_SHORT").'_'.JText::_("JEV_MAR_SHORT").'_'.JText::_("JEV_APR_SHORT").'_'.JText::_("JEV_MAY_SHORT").'_'.JText::_("JEV_JUN_SHORT").'_'.JText::_("JEV_JUL_SHORT").'_'.JText::_("JEV_AUG_SHORT").'_'.JText::_("JEV_SEP_SHORT").'_'.JText::_("JEV_OCT_SHORT").'_'.JText::_("JEV_NOV_SHORT").'_'.JText::_("JEV_DEC_SHORT").'".split("_"),
						weekdays : "'.JText::_("JEV_SUNDAY").'_'.JText::_("JEV_MONDAY").'_'.JText::_("JEV_TUESDAY").'_'.JText::_("JEV_WEDNESDAY").'_'.JText::_("JEV_THURSDAY").'_'.JText::_("JEV_FRIDAY").'_'.JText::_("JEV_SATURDAY").'".split("_"),
						weekdaysShort : "'.JText::_("JEV_SUN").'_'.JText::_("JEV_MON").'_'.JText::_("JEV_TUES").'_'.JText::_("JEV_WED").'_'.JText::_("JEV_THU").'_'.JText::_("JEV_FRI").'_'.JText::_("JEV_SAT").'".split("_"),
						weekdaysMin : "'.JText::_("JEV_SUNDAY_CHR").'_'.JText::_("JEV_MONDAY_CHR").'_'.JText::_("JEV_TUESDAY_CHR").'_'.JText::_("JEV_WEDNESDAY_CHR").'_'.JText::_("JEV_THURSDAY_CHR").'_'.JText::_("JEV_FRIDAY_CHR").'_'.JText::_("JEV_SATURDAY_CHR").'".split("_"),
						week : {
							dow : '.$this->com_starday.', // Monday is the first day of the week.
						}
					});';
		/*
		 * THIS SHOULD BE IN THE SCRIPT VARIABLE
		 * longDateFormat : {
							LT : "HH:mm",
							L : "DD/MM/YYYY",
							LL : "D MMMM YYYY",
							LLL : "D MMMM YYYY LT",
							LLLL : "dddd D MMMM YYYY LT"
						},
						calendar : {
							sameDay: "[Aujourd\'hui à] LT",
							nextDay: "[Demain à] LT",
							nextWeek: "dddd [à] LT",
							lastDay: "[Hier à] LT",
							lastWeek: "dddd [dernier à] LT",
							sameElse: "L"
						},
						relativeTime : {
							future : "dans %s",
							past : "il y a %s",
							s : "quelques secondes",
							m : "une minute",
							mm : "%d minutes",
							h : "une heure",
							hh : "%d heures",
							d : "un jour",
							dd : "%d jours",
							M : "un mois",
							MM : "%d mois",
							y : "une année",
							yy : "%d années"
						},
					    ordinal : function (number) {
							return number + (number === 1 ? "er" : "ème");
						}*/
		return $script;
	}
}
