<?php
//define this module's name and path
$mn = basename(__FILE__ , ".php");
include("modules/modules.php");

/*
Available variables:
All system classes
All request variables
$p (the template path)
$mp (the module path)
$sufixID (id sufix for this module's divs)
*/

$marginTop = ($moduleParameters['marginTop'] == "__EMPTY__" || empty($moduleParameters['marginTop'])) ? 0 : $moduleParameters['marginTop'];
$marginRight = ($moduleParameters['marginRight'] == "__EMPTY__" || empty($moduleParameters['marginRight'])) ? 0 : $moduleParameters['marginRight'];
$marginBottom = ($moduleParameters['marginBottom'] == "__EMPTY__" || empty($moduleParameters['marginBottom'])) ? 0 : $moduleParameters['marginBottom'];
$marginLeft = ($moduleParameters['marginLeft'] == "__EMPTY__" || empty($moduleParameters['marginLeft'])) ? 0 : $moduleParameters['marginLeft'];
$paddingTop = ($moduleParameters['paddingTop'] == "__EMPTY__" || empty($moduleParameters['paddingTop'])) ? 0 : $moduleParameters['paddingTop'];
$paddingRight = ($moduleParameters['paddingRight'] == "__EMPTY__" || empty($moduleParameters['paddingRight'])) ? 0 : $moduleParameters['paddingRight'];
$paddingBottom = ($moduleParameters['paddingBottom'] == "__EMPTY__" || empty($moduleParameters['paddingBottom'])) ? 0 : $moduleParameters['paddingBottom'];
$paddingLeft = ($moduleParameters['paddingLeft'] == "__EMPTY__" || empty($moduleParameters['paddingLeft'])) ? 0 : $moduleParameters['paddingLeft'];
$useModuleContainer = ($moduleParameters['useModuleContainer'] == "__EMPTY__" || empty($moduleParameters['useModuleContainer'])) ? 0 : (int)$moduleParameters['useModuleContainer'];
$widthInPixels = ($moduleParameters['widthInPixels'] == "__EMPTY__" || empty($moduleParameters['widthInPixels'])) ? null : (int)$moduleParameters['widthInPixels'];

if(empty($marginTop) && empty($marginRight) && empty($marginBottom) && empty($marginLeft)){
	$Mmargin = "0";
}else{
	$Mmargin = $marginTop." ".$marginRight." ".$marginBottom." ".$marginLeft." ";
}
if(empty($paddingTop) && empty($paddingRight) && empty($paddingBottom) && empty($paddingLeft)){
	$Mpadding = "0";
}else{
	$Mpadding = $paddingTop." ".$paddingRight." ".$paddingBottom." ".$paddingLeft." ";
}

$useCaptcha = ((int)$moduleParameters['useCaptcha'] > 0) ? true : false;
$onlyRegistered = ((int)$moduleParameters['onlyRegistered'] > 0) ? true : false;
$showCommentsToUnregistered = ((int)$moduleParameters['showCommentsToUnregistered'] > 0) ? true : false;
if(empty($onlyRegistered)) $showCommentsToUnregistered = true;
$saveAsInactive = ((int)$moduleParameters['saveAsInactive'] > 0) ? true : false;
$sendMail = ((int)$moduleParameters['sendMail'] > 0 || $saveAsInactive) ? true : false; // αν αποθηκεύονται ως ανενεργά τα σχόλια, να κάνει overwrite και να στέλνει email οπωσδήποτε 
$evenColor = ($moduleParameters['evenColor']) ? $moduleParameters['evenColor'] : "transparent";
$oddColor = ($moduleParameters['oddColor']) ? $moduleParameters['oddColor'] : "transparent";
$refreshRate = (int)$moduleParameters['refreshRate']; // value in seconds
$refreshRate = $refreshRate * 1000; // convert to milliseconds

global $auth;
global $published;
global $title;
global $name;
global $alias;
global $body;
global $active;
global $sectionID;
global $articleID;
global $userID;
global $domain_name;

// Uncomment the 3 following lines in order to enable comments only in certain categories of the section (works only for one section selected)
//global $catID;
//$validCategories = array("6", "7"); // the catIDs we must have comments
//if(!in_array($catID, $validCategories)) return;

if(!$auth->getLoginStatus()){
	$userID = 0;
}else{
	$userID = $_SESSION['userID'];
	$name = $_SESSION['userUsername'];
}

if($useModuleContainer ){
?>
<div id="<?php echo $mn.$sufixID;?>" data-editable="editable">
<?php
}
if($moduleParameters['moduleAlign'] && $moduleParameters['moduleHR']){ // there are system parameters...
?>
<style type="text/css">
<?php
if($useModuleContainer ){
?>
#<?php echo $mn.$sufixID;?>{
	text-align: <?php echo $moduleParameters['moduleAlign'];?>;
	margin : <?php echo $Mmargin;?>;
	padding : <?php echo $Mpadding;?>;
<?php
if($widthInPixels){
	?>
	width: <?php echo $widthInPixels;?>px;
	<?php
}	
if($moduleParameters['moduleHR'] == "top" || $moduleParameters['moduleHR'] == "bottom"){
?>
	border-<?php echo $moduleParameters['moduleHR'];?> : 1px solid black;
<?php	
}
?>	
}
<?php
}
if($moduleParameters['use_colors']){
?>
#<?php echo $mn.$sufixID;?>{
	color: #<?php echo $moduleParameters['footer_text_color'];?>;	
}
#<?php echo $mn.$sufixID;?> a{
	color: #<?php echo $moduleParameters['link_text_color'];?>;	
}
<?php
}
?>
#comments_added{
	display: none;
	position: fixed;
	top: 10px;
	right:10px;
	background-color: #060;
	padding: 3px 20px;
	color: #FFF;
	text-shadow: 1px 1px 1px #000;
	font-size: 0.85em;
	border-radius: 6px; 
}
</style>
<?php
} 
?>
<script type="text/javascript">
// initialization
window.numOfComments = 0;
window.startrecord = 0;
window.presults = 1;
<?php
if($refreshRate){
?>
jQuery().ready(function(){
	setInterval(refreshComments, <?php echo $refreshRate;?>);
});
<?php
}
?>

function submitComment(){
	var name = $('#name').val();
	var message = $('#message').val();
	var sectionID = "<?php echo $system->getTableSectionID($section);?>";
	var articleID = "<?php echo $id;?>";
	var userID = "<?php echo $userID;?>";
	var langID = "<?php echo $langID;?>";
	var useCaptcha = "<?php echo $useCaptcha;?>";
	var security_code = $('#security_code').val();
	var sendMail = "<?php echo $sendMail;?>";
	var saveAsInactive = "<?php echo ($saveAsInactive) ? 1 : 0;?>";
	
	jQuery.ajax({
		type: "POST",
		url: "<?php echo "http://".$domain_name."/".$mp;?>ajax.php",
		data: "action=add&name=" + name + "&message=" + message + "&sectionID=" + sectionID + "&articleID=" + articleID + "&userID=" + userID + "&langID=" + langID + "&useCaptcha=" + useCaptcha + "&security_code=" + security_code + "&sendMail=" + sendMail + "&saveAsInactive=" + saveAsInactive,
		dataType: "json",
		async: false,
		success: function(response){
			//console.log(response);
			var saved = false;
			var msg = response[0].msg;
			if(msg){
				if(msg == "ok_inactive"){
					var saved = true;
					msg = "<?php echo t("Το σχόλιο σας θα δημοσιευθεί αφού ελεγχθεί από την συντακτική επιτροπή");?>";
				}
				if(msg.indexOf("ok_active") != -1){
					var data = msg.split("~|~");
					msg = data[0];
					var timestamp = data[1];
					var saved = true;
					var color = "<?php echo $evenColor;?>";
					var oddColor = "<?php echo $oddColor;?>";
					if($('#comments li:nth-child(1)').length){
						var rgb_color = $('#comments li:nth-child(1)').css("background-color");
						var hexColor;
						if(rgb_color == "#"){
							hexColor = rgb_color;
						}else{
							hexColor = rgb2hex(rgb_color);
						}
						if(hexColor == "#" + color){
							color = oddColor;
						}
					}
					var comment = '<li style="background-color: #' + color + '" data-timestamp="'+timestamp+'" data-articleID="'+articleID+'"><b>' + name + '</b><p>' + nl2br(message) + '</p></li>';
					if(!$('#comments').length) $('#comments_list').append($('<ul id="comments"></ul>'));
					$('#comments').prepend(comment);
					window.numOfComments ++;
					msg = "<?php echo t("Το σχόλιο σας δημοσιεύθηκε επιτυχώς");?>";
				}	
				if(saved){
					document.getElementById('comment_form').reset();
					goto('comments_list');
				}
				if(msg != "ok_inactive" && msg != "ok_active" && msg) alert(msg);
				return;
			}
		}, 
		error: function (jqXHR, textStatus, errorThrown) { 
			console.log("error: " + textStatus);
			console.log("errorThrown: " + errorThrown);
		}
	});	
}

function getComments(){
	var articleID = "<?php echo $id;?>";
	var langID = "<?php echo $langID;?>";	
	jQuery.ajax({
		type: "POST",
		url: "<?php echo "http://".$domain_name."/".$mp;?>ajax.php",
		data: "action=get&startrecord=" + window.startrecord + "&presults=" + window.presults + "&articleID=" + articleID + "&langID=" + langID,
		dataType: "json",
		async: false,
		success: function(response){
			response = response.trim();
			//console.log(response);
			var msg = response[0].msg;
			if(msg == "ok"){
				var evenColor = "<?php echo $evenColor;?>";
				var oddColor = "<?php echo $oddColor;?>";	
				evenColor = (evenColor == "transparent") ? evenColor : "#" + evenColor;	
				oddColor = (oddColor == "transparent") ? oddColor : "#" + oddColor;							
				for(index in response){
					if($('#comments li:last-child').length){
						var bgColor = $('#comments li:last-child').css("background-color");
						rgb_color = (bgColor == "rgba(0, 0, 0, 0)") ? "transparent" : bgColor;
						var hexColor = (rgb_color == "transparent") ? "transparent" : rgb2hex(rgb_color);
						var color = (hexColor == evenColor) ? oddColor : evenColor;
					}					
					var name = response[index].name;
					var published = response[index].published;
					var timestamp = response[index].timestamp;
					var text = nl2br(response[index].text);
					var comment = '<li style="background-color: ' + color + '" data-timestamp="' + timestamp + '" data-articleID="' + articleID + '"><b>' + name + '</b> <span><?php echo t("έγραψε στις");?> ' + published+ '</span><p>' + text + '</p></li>';
					if(!$('#comments').length) $('#comments_list').append($('<ul id="comments"></ul>')); // just in case...
					$('#comments').append(comment);					
				}
				var hasMore =(((window.startrecord) + window.presults) < window.numOfComments);					
				if(!hasMore){
					$('#more_results').hide();	
				}else{
					window.startrecord += window.presults;
				}
			}else{
				alert(msg);  // alert the error
			}
		}, 
		error: function (jqXHR, textStatus, errorThrown) { 
			console.log("error: " + textStatus);
			console.log("errorThrown: " + errorThrown);
		}
	});	
}

function refreshComments(){
	var articleID = "<?php echo $id;?>";
	var langID = "<?php echo $langID;?>";	
	var last_timestamp = $('#comments li:first-child').attr('data-timestamp');
	console.log("Getting comments newer than " + last_timestamp + " timestamp");
	jQuery.ajax({
		type: "POST",
		url: "<?php echo "http://".$domain_name."/".$mp;?>ajax.php",
		data: "action=refresh&articleID=" + articleID + "&langID=" + langID + "&last_timestamp=" + last_timestamp,
		dataType: "json",
		async: false,
		success: function(response){
			response = response.trim();
			//console.log(response);
			if(!response.length) return;
			var msg = response[0].msg;
			if(msg == "ok"){
				var evenColor = "<?php echo $evenColor;?>";
				var oddColor = "<?php echo $oddColor;?>";	
				evenColor = (evenColor == "transparent") ? evenColor : "#" + evenColor;	
				oddColor = (oddColor == "transparent") ? oddColor : "#" + oddColor;							
				for(index in response){
					if($('#comments li:last-child').length){
						var bgColor = $('#comments li:last-child').css("background-color");
						rgb_color = (bgColor == "rgba(0, 0, 0, 0)") ? "transparent" : bgColor;
						var hexColor = (rgb_color == "transparent") ? "transparent" : rgb2hex(rgb_color);
						var color = (hexColor == evenColor) ? oddColor : evenColor;
					}					
					var name = response[index].name;
					var published = response[index].published;
					var timestamp = response[index].timestamp;
					var text = nl2br(response[index].text);
					var comment = '<li style="background-color: ' + color + '" data-timestamp="' + timestamp + '" data-articleID="' + articleID + '"><b>' + name + '</b> <span><?php echo t("έγραψε στις");?> ' + published+ '</span><p>' + text + '</p></li>';
					if(!$('#comments').length) $('#comments_list').append($('<ul id="comments"></ul>')); // just in case...
					$('#comments').prepend(comment);
					displayRefreshMsg();					
				}
				var hasMore =(((window.startrecord) + window.presults) < window.numOfComments);					
				if(!hasMore){
					$('#more_results').hide();	
				}else{
					window.startrecord += window.presults;
				}
			}else{
				alert(msg);  // alert the error
			}
		}, 
		error: function (jqXHR, textStatus, errorThrown) { 
			console.log("error: " + textStatus);
			console.log("errorThrown: " + errorThrown);
		}
	});	
}

function displayRefreshMsg(){
	$('#comments_added').fadeIn('slow');
	setTimeout(function(){
		$('#comments_added').fadeOut('slow');
	}, 10000);
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
</script>
<div id="comments_added"><?php echo t("Δημοσιεύθηκαν νεότερα σχόλια");?></div>
<a id="commentsForm"></a>
<?php
	if(!empty($_POST['info'])){ // check for spam
		header ("location: index.php");
		exit;
	}
	
	if($_POST['submitComments']){		
		if($useCaptcha){
			$_POST['security_code'] = strtoupper( $_POST['security_code']); // μονο κεφαλαια στο capcha
			if($_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
				unset($_SESSION['security_code']); // ολα ok με το captcha image
			}else{
				$messages->addError(t("Ο κωδικός ταυτοποίησης που πληκτρολογήσατε δεν είναι σωστός"));
			}
		}
		if(empty($onlyRegistered)){
			if(!$_POST['name']) $messages->addError(t("Πρέπει να πληκτρολογήσετε το όνομά σας"));
		}else{
			if(empty($userID)) $messages->addError(t("Πρέπει να συνδεθείτε για να μπορείτε να σχολιάζετε"));
		}
		if(!$_POST['message']) $messages->addError(t("Πρέπει να πληκτρολογήσετε κάποιο μήνυμα"));
		if(empty($section)) $messages->addError(t("Δεν ορίστηκε η ενότητα"));
		if(empty($id)) $messages->addError(t("Δεν βρέθηκε το id του άρθρου"));
	}

	$hasErrors = $messages->hasErrors;
	if($hasErrors) $messages->printSystemMessages(30000, 0);

	
	if(!$_POST['submitComments'] || $hasErrors){ // display form
		if(empty($onlyRegistered) || ($onlyRegistered && $userID)){
		echo t("Μπορείτε αν θέλετε να σχολιάσετε");
		if($_POST['submitComments'] || $_GET['presults']){
			?>
			<script>
			$(document).ready(function() { 
			    $('html,body').animate({ scrollTop: $("#commentsForm").offset().top}, 500);
			});			
			</script>
			<?php			
		}
		?>		
			<form id="comment_form" action="index.php" method="post" class="contactForm" autocomplete="off">
			<input type="text" name="info" class="required">
				<div class="formTable" style="width:98%; text-align:left">
                
					<div style="text-align:right; color: grey"><span class="req">*</span><i><?php echo t("Απαραίτητα πεδία");?></i></div>
					<?php
					if(empty($userID)){
					?>			
                    <div style="margin: 0 auto;" class="form_container">
                        <div class="formLabel left"><span class="req">*</span><?php echo t('Το όνομά σας');?></div>
                        <div>
                        <input id="name" name="name" type="text" class="textbox" value="<?php echo str_replace('"', "'", stripslashes($name));?>">
                        </div>
                    </div>     
					<?php
					}else{
					?>	
                    <div style="margin: 0 auto;" class="form_container">
                        <div class="formLabel left"><?php echo t('Χρήστης');?> : <?php echo str_replace('"', "'", stripslashes($name));?> </div>
                        <input id="name" name="name" type="hidden" value="<?php echo str_replace('"', "'", stripslashes($name));?>">
                    </div>                    
					<?php
					}
					?>
                    <div style="margin: 0 auto;" class="form_container">
                        <div class="formLabel left"><span class="req">*</span><?php echo t('Σχόλιο');?></div>
                        <div>
                        <textarea id="message" name="message" rows="8" class="multiline_textbox" style="min-width: 80%; font-size:inherit !important"></textarea>
                        </div>
                    </div>
					<?php
					if($useCaptcha){
					?>		
                    <div style="margin: 10px auto 2px auto;" class="form_container">
                        <div class="formLabel left"><span class="req">*</span><?php echo t('Κωδικός ταυτοποίησης');?></div>
                        <div><img src="CaptchaSecurityImages.php?width=100&amp;height=40&amp;characters=5" style="float:left;min-width:100px;" alt="captcha" />
                        &nbsp;<input name="security_code" type="text" id="security_code" class="textbox" style="width:80px"></div>
                        <div class="formLabel left" style="margin-top: 15px;"><?php echo t('Συμπληρώστε τον κωδικό ταυτοποίησης');?></div>
                    </div>
					<?php
					}
					?>
                    
                    <input name="section" type="hidden" value="<?php echo $section;?>">
                    <input name="view" type="hidden" value="<?php echo $view;?>">
                    <input name="id" type="hidden" value="<?php echo $id;?>">
                    <input name="langID" type="hidden" value="<?php echo $langID;?>">
                    <div style="margin: 10px auto; display:table">
                        <div><input name="submitComments" type="button" class="formButton" style="padding: 3px 20px" value="<?php echo t('Αποστολή');?>" onclick="this.blur(); submitComment()"></div>
                    </div>
				</div>
			</form>
				
			<?php 
		}else{
			?>
			<div style="margin-bottom:30px"><?php echo t("Πρέπει να συνδεθείτε για να σχολιάσετε");?></div>
			<?php			
		}
	}
// let's see if we have comments for this article
if($showCommentsToUnregistered || !empty($userID)){
	$comments = $content->getContent("comments",  " comments.articleID=".$id." ", "*", "*", $langID, " published desc");
	?>
	<style>
    #comments li{
        padding: 6px;
        margin: 10px 0;
        list-style-type: none;
        text-align:left;
    }				
    #comments li p{
        margin-top:6px;
        margin-bottom:6px;
        margin-left:20px;
		max-width:600px;
    }
    #comments li span{
        color: grey;
        font-size: 10px;
    }	
	#comments_list{
		<?php
		if(!$comments){
		?>
		border-top:1px solid grey;
		<?php
		}
		?>
		margin-bottom:20px; 
		padding-bottom: 3px;
	}
    </style>    
    <div id="comments_list">
    <?php
	$presults = (int)$system->getPresults("comments");	
	if($comments){
		$numOfComments = count($comments);
		$foundText = ($numOfComments > 1) ? t("Βρέθηκαν", $langID, "null")." ".$numOfComments." ".t("καταχωρημένα σχόλια") :t("Βρέθηκε", $langID, "null")." ".$numOfComments." ".t("καταχωρημένο σχόλιο");
		$hasMore = false;
		if($numOfComments > $presults){
			$maxrows = $numOfComments;
			$ppage = ($ppage > 0) ? $ppage : 1;
			$startrecord=($ppage * $presults) - $presults;
			$startrecord=($startrecord < 0) ? 0 : $startrecord ;
			$comments = $content->getContent("comments", " comments.articleID=".$id." ", "*", "*", $langID, " published desc LIMIT $startrecord, $presults");
			$hasMore =(($startrecord+$presults) < $numOfComments);			
		}
		?>
        <script type="text/javascript">
			window.numOfComments = <?php echo $numOfComments;?>;
			window.presults = <?php echo $presults;?>;	
			window.startrecord = <?php echo $startrecord;?> + window.presults;					
        </script>
		<div style="border-bottom:1px solid grey;margin-bottom:20px; padding-bottom: 3px; text-align: right"><?php echo $foundText;?></div>
		<ul id="comments">
		<?php
		$row = 0;
		$evenColor = ($evenColor == "transparent") ? $evenColor : "#".$evenColor;
		$oddColor = ($oddColor == "transparent") ? $oddColor : "#".$oddColor;
		foreach($comments as $comment){
			$row++;
			$ccolor = ($row % 2) ? $evenColor : $oddColor;
			?>
			<li style="background-color: <?php echo $ccolor;?>" data-timestamp="<?php echo $comment->published;?>" data-articleID="<?php echo $id;?>">
			<b><?php echo $comment->name;?></b> <span> <?php echo t("έγραψε στις");?> <?php  echo $dates->makeDateFromTimestamp($comment->published);?></span>
			<p><?php echo stripslashes(nl2br($comment->body));?></p>
			</li>
			<?php
		}
		?>
		</ul>
		<?php
		if($hasMore){
			?>
            <a id="more_results" href="javascript:void(0)" onclick="getComments()"><?php echo t("περισσότερα σχόλια");?></a>
            <?php
		}
	}
	?>
    </div>
    <?php
}
if($useModuleContainer ){		
?>
</div>
<?php
}
?>

