<?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";

global $auth;
global $published;
global $title;
global $name;
global $alias;
global $body;
global $active;
global $sectionID;
global $articleID;
global $userID;
global $protocol;
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() == 2){ // guest
    $userID = 0;
}else{
    $userID = $_SESSION['userID'];
    $name = $_SESSION['userUsername'];
}

$rating_enabled = $parameters->getParameter("rating");

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;?>{
	<?php
	$alignRule = ($moduleParameters['moduleAlign'] == "center") ? "text-align" : "float";
	echo $alignRule.": ".$moduleParameters['moduleAlign'].";".PHP_EOL;
	?>
	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
            }
            ?>
        </style>
        <?php
    }
    ?>
    <script type="text/javascript">
        // initialization
        window.numOfComments = 0;
        window.startrecord = 0;
        window.presults = 1;

        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;?>";
            var rate = $('#rate').val();

            jQuery.ajax({
                type: "POST",
                url: "<?php echo $protocol . "://".$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 + "&rate=" + rate,
                dataType: "json",
                async: false,
                success: function(response){
                    //console.log(response);
                    var saved = false;
                    var msg = response[0].msg;
                    var commentID = response[0].id;
                    //console.log(msg);
                    if(msg){
                        if(msg == "ok_inactive"){
                            var saved = true;
                            msg = "<?php echo t("Το σχόλιο σας θα δημοσιευθεί αφού ελεγχθεί από την συντακτική επιτροπή");?>";
                        }
                        if(msg == "ok_active"){
                            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;
                                }
                            }
                            if(!name){
                                <?php
                                $name = ($auth->getLoginStatus() == 2) ? "Guest" : $content->getValue("users", $userID, "title", $langID);
                                ?>
                                name = "<?php echo $name;?>";
                            }
                            var comment = '<li style="background-color: #' + color + '"><h2 class="comments_name">' + name + '</h2>' + getRate(commentID) + '<p>' + nl2br(message) + '</p></li>';
                            if(!$('#comments').length) $('#comments_list').append($('<ul id="comments"></ul>'));
                            $('#no_reviews').hide();
                            $('#comments').prepend(comment);
                            window.numOfComments ++;
                            $('#numOfComments').text(window.numOfComments);
                            msg = "<?php echo t("Το σχόλιο σας δημοσιεύθηκε επιτυχώς");?>";
                            for(var idx=1; idx<=5; idx++){
                                $('#star' + idx).removeClass("star_active");
                            }
                            document.getElementById('comment_form').reset();
                            $('html,body').animate({ scrollTop: $("#commentsStart").offset().top}, 500);
                            $('#comment_form').hide();
                        }
                        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 userID = "<?php echo $userID;?>";
            var langID = "<?php echo $langID;?>";
            jQuery.ajax({
                type: "POST",
                url: "<?php echo $protocol . "://".$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 commentID = response[index].id;
                            var name = response[index].name;
                            var published = response[index].published;
                            var text = nl2br(response[index].text);
                            var comment = '<li style="background-color: ' + color + '"><h2 class="comments_name">' + name + '</h2> <span><?php echo t("έγραψε στις");?> ' + published+ '</span>' + getRate(commentID) + '<p>' + text + '</p></li>';
                            console.log(comment);
                            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 getRate(commentID){
            var rate;
            var langID = "<?php echo $langID;?>";
            jQuery.ajax({
                type: "POST",
                url: "<?php echo $protocol . "://".$domain_name."/".$mp;?>ajax.php",
                data: "action=get_rate&commentID=" + commentID + "&langID=" + langID,
                dataType: "json",
                async: false,
                success: function(response){
                    //console.log(response);
                    rate = response[0].rate;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log("error: " + textStatus);
                    console.log("errorThrown: " + errorThrown);
                }
            });
            var html = '<div style="height:15px;">';
            for(var idx=1; idx <=5; idx++){
                var cssClass = (idx <= rate) ? " star_small_active" : "";
                html += '<span class="star_small' + cssClass + '"></span>';
            }
            html += '</div>';
            return html;
        }

        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>
    <a id="commentsStart"></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);


    // 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")." <span id='numOfComments'>".$numOfComments."</span> ".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;?>">
                            <h2 class="comments_name"><?php echo $comment->name;?></h2> <span> <?php echo t("έγραψε στις");?> <?php  echo $dates->makeDateFromTimestamp($comment->published);?></span>
                            <script type="text/javascript">document.write(getRate("<?php echo $comment->id;?>"));</script>
                            <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
            }
            }else{
            ?>
                <div id="no_reviews"><?php echo t("Δεν βρέθηκαν δημοσιευμένες κριτικές");?></div>
                <?php
            }
            if(!$onlyRegistered || ($onlyRegistered && $userID)){
                ?>
                <a id="write_review" href="javascript:void(0)" onclick="$('#comment_form').show(); $(this).hide()"><?php echo t("γράψτε μια κριτική");?></a>
                <?php
            }
            ?>
        </div>
        <?php
    }

    if(!$_POST['submitComments'] || $hasErrors){ // display form
        if(empty($onlyRegistered) || ($onlyRegistered && $userID)){
        if($_POST['submitComments'] || $_GET['presults']){
            ?>
            <script>
                $(document).ready(function() {
                    $('html,body').animate({ scrollTop: $("#commentsStart").offset().top}, 500);
                    <?php
                    if($hasErrors){
                    ?>
                    $('#comment_form').show();
                    <?php
                    }
                    ?>
                });
            </script>
        <?php
        }
        ?>
            <script type="text/javascript" src="js/rating.js"></script>
            <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">


                    <?php
                    if(!empty($userID)) $name = $content->getValue("users", $userID, "title", $langID); // get registered user's name
                    if(empty($rate) && $rating_enabled) $rate = 1;
                    ?>
                    <div style="margin: 0 auto;" class="form_container">
                        <div class="formLabel left"><?php echo t('Το όνομά σας');?></div>
                        <div>
                            <input id="name" name="name" type="text" class="textbox" value="<?php echo str_replace('"', "'", stripslashes($name));?>">
                        </div>
                    </div>
                    <?php
                    if($rating_enabled){
                        ?>
                        <div style="margin: 0 auto;" class="form_container">
                            <div class="formLabel left"><?php echo t('Η βαθμολογία σας');?></div>
                            <div style="padding-bottom: 10px;">
                        <span id="rating">
                        	<span class="star star_active" id="star1" data-value="1" title="<?php echo t("Κακό");?>"></span>
                            <span class="star" id="star2" data-value="2" title="<?php echo t("Μέτριο");?>"></span>
                            <span class="star" id="star3" data-value="3" title="<?php echo t("Καλό");?>"></span>
                            <span class="star" id="star4" data-value="4" title="<?php echo t("Πολύ Καλό");?>"></span>
                            <span class="star" id="star5" data-value="5" title="<?php echo t("Εξαιρετικό!");?>"></span>
                        </span>
                            </div>
                        </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 id="rate" name="rate" type="hidden" value="<?php echo $rate;?>">
                    <input name="section" type="hidden" value="products">
                    <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{
            $messages->addMessage(t("Πρέπει να συνδεθείτε για να μπορείτε να αξιολογείτε προϊόντα"));
            $messages->printSystemMessages();
        }
    }

    if($useModuleContainer ){
    ?>
</div>
<?php
}
?>

