<?php 
require_once("dll.php");
$variables->getSafeVars(array_keys($_REQUEST));
$sectionID = $system->getTableSectionID($section);
$registeredDates = array();
if($dates->isDate($dates->makeTimestamp($d))){
	$formatedDate = $d;
	$daysOfEvent = (is_numeric($daysOfEvent)) ? abs($daysOfEvent) : 1;
	$d = explode("/", $d);
	$day = $d[0];
	$month = $d[1];
	$year = $d[2];
	if($day < 1 || $day > 31) exit;
	if($month < 1 || $month > 12) exit;
	if(empty($year) || strlen($year) != 4) exit;
	$lastIDs = array();
	for($i=0; $i<$daysOfEvent; $i++){
		$timestamp = gmmktime(0,0,0,$month,$day,$year) + ($i*86400);
		$d = getdate($timestamp);
		$thisday = $d["mday"];
		$thismonth = $d["mon"];
		$thisyear = $d["year"];
		// lets see if event date exists in order to  save only new event dates
		$urlPart = "index.php?section=".$section."&view=node&id=".$itemID;
		$q = "select content_events.mainID from events, content_events 
		where events.id=content_events.mainID 
		and events.day='$thisday' 
		and events.month='$thismonth' 
		and events.year='$thisyear' 
		and content_events.url like '".$urlPart."%' 
		group by content_events.title";
		if(!$db->getNumRows($q)){ // save it only if does not exists
			$eventAlias = "event_".$thisday."_".$thismonth."_".$thisyear;
			$active = 1;
			$private = 1;
			$db->query("insert into events values(null, '$active', '$private', '$eventAlias', '0', '$thisday', '$thismonth', '$thisyear')");
			$lastIDs[$i] = $db->lastID(); // store to array in order to use it later for content_events table (see bellow in multilingual support)
		}
	}

	$Lresult = $db->getRecords("SELECT * FROM languages WHERE active=1 ");
	foreach($Lresult as $Lrow) {
		$languageID = $Lrow->id;
		for($i=0; $i<$daysOfEvent; $i++){
			$title = $content->getValue($section, $itemID, "title", $languageID);
			$thisID = $lastIDs[$i];			
			if(!empty($title) && !empty($thisID)){ // add entry only if $thisID > 0 and a title of this language exists for $itemID record 
				$q = "select day, month, year from events where id='$thisID'";
				$record = $db->getRecord($q);
				$formatedDate = $record->day."/".$record->month."/".$record->year;
				$urlView = ($section == "pages") ? "render" : "node";
				$eventCalendarURL = (${"url".$extension}) ? ${"url".$extension} : "index.php?section=".$section."&view=".$urlView."&id=".$itemID."&langID=".$languageID;
				$db->query("insert into content_events values(null, '$thisID', '$languageID', '$title', '$eventCalendarURL' )");
				if($registeredDates[$formatedDate] != "added"){
					echo "<div class='date_tag'><a href='javascript:void(0)' onclick='removeTag(this, \"" .$formatedDate. "\");'></a><tag>" .$formatedDate. "</tag></div>";
					$registeredDates[$formatedDate] = "added";
				}
			}
		}
	}
}
?>