<?php
//define this module's name and path
$mn = "odyshop_admin_product_options";
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 . " ";
}

global $row; // access to product data
if (!$row) {
    echo "Critical Error! No product data found";
    return;
}
$productID = $row->id;
$inactiveTitle = t("η εγγραφή αυτή είναι ανενεργή");
$activeTitle = t("κάντε κλικ για επεξεργασία των παραλλαγών");
$eshop = new eshop();


if ($useModuleContainer){
?>

<div id="<?php echo $mn . $sufixID; ?>" data-editable="editable">
    <?php
    }
    ?>

    <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['moduleAlign'] && $moduleParameters['moduleHR']){ // there are system parameters...

if($moduleParameters['moduleHR'] == "top" || $moduleParameters['moduleHR'] == "bottom"){
?>
	border-<?php echo $moduleParameters['moduleHR'];?> : 1px solid black;
<?php 
}
}
?>
}

        <?php
        }
        ?>
    </style>
    <link href="../modules/<?php echo $mn; ?>/css/styles.css" rel="stylesheet" type="text/css">

    <script type="text/javascript">

        odyshop.doCleanUp = true;
        $(document).ready(function () {

            $("#sort-list").sortable({
                handle: '.handle',
                axis: 'y',
                update: function () {
                    var order = $('#sort-list').sortable('serialize');
                    $("#sortInfo").load("sort.php?" + order + "&table=options");
                },
                start: function (evt, ui) {
                    var link = ui.item.find('div.ui-sortable-handle');
                    handleDrag(link, 'start');
                },
                stop: function (evt, ui) {
                    var link = ui.item.find('div.ui-sortable-handle');
                    handleDrag(link, 'stop');
                }
            });

            $("#sort-variants-list").sortable({
                handle: '.handle',
                axis: 'y',
                cancel: $('#add_new'),
                update: function () {
                    var order = $('#sort-variants-list').sortable('serialize');
                    $("#sortVariantsInfo").load("sort.php?" + order + "&table=product_options_variants");
                },
                start: function (evt, ui) {
                    var link = ui.item.find('div.ui-sortable-handle');
                    handleDrag(link, 'start');
                },
                stop: function (evt, ui) {
                    var link = ui.item.find('div.ui-sortable-handle');
                    handleDrag(link, 'stop');
                }
            });

            $('a[data-edit-id]').fancybox({
                beforeShow: function () {
                    var openerLink = $(this.element.context);
                    $('#variants_title').html("<?php echo t("Παραλλαγές επιλογής") . " : <span>";?>" + openerLink.text() + "</span>");
                    var id = openerLink.attr('data-edit-id');
                    $("#variants").attr("data-optionID", id);
                    odyshop.optionID = id;
                    odyshop.lastFancybox = $(this);
                    if (odyshop.doCleanUp) {
                        $('#sort-variants-list li:not("#add_new, #variants_list li")').remove();
                        $('#variants_list').empty();
                        $('#results_info').html("");
                        $('#new_variant').val("");
                    } else {
                        odyshop.doCleanUp = true;
                    }
                },
                afterShow: function () {
                    getVariants();
                    if ($('#sort-variants-list li:not(.admin_form_element)').length > 1) massControls('variants', 'show');
                    $('.chk_container p, .admin_checkbox_wrapper p').on('click', function () {
                        $(this).parent().find('input[type="checkbox"]').trigger('click');
                    });
                },
                beforeClose: function () {
                    hideNewEntry(true);
                },
                afterClose: function () {
                    odyshop.lastFancybox = $(this.element.context);
                    if (odyshop.reOpen) {
                        odyshop.reOpen = false;
                        odyshop.lastFancybox.click();
                    }
                },
                width: 900,
                arrows: false,
                helpers: {
                    overlay: {
                        css: {
                            'background': 'rgba(0, 0, 0, 0.8)'
                        }
                    },
                    title: null
                }
            });

            $("#variants").on("focusin", function () {
                $('a[data-rel="variants_mediabank"]').each(function () {
                    $(this).fancybox({
                        beforeShow: function () {
                            odyshop.variant = $(this.element.context);
                        },
                        afterClose: function () {
                            odyshop.doCleanUp = false;
                            odyshop.lastFancybox.click();
                            if (odyshop.thumb) updateImage(odyshop.variant, odyshop.thumb);
                        },
                        width: 870,
                        height: 600,
                        type: 'iframe',
                        arrows: false,
                        modal: true,
                        helpers: {
                            overlay: {
                                css: {
                                    'background': 'rgba(0, 0, 0, 0.8)'
                                }
                            },
                            title: null
                        }
                    });
                });
            });


            $("#open_select_product_options").fancybox({
                beforeClose: hideGlobalOption,
                arrows: false,
                helpers: {
                    overlay: {
                        css: {
                            'background': 'rgba(0, 0, 0, 0.8)'
                        }
                    },
                    title: null
                }
            });

        });

        function optionExists(optionID) {
            odyshop.returnValue = false;
            $('#optionsList input[type="checkbox"]').each(function () {
                if ($(this).attr("id") == "optionID" + optionID) {
                    odyshop.returnValue = true;
                    return false;
                }
            });
            return odyshop.returnValue;
        }

        function massControls(section, action) {
            if (section == "options") {
                if (action == "show") {
                    $('#no_content').hide();
                    $('.options_select_all').show();
                    $('#optionsMassButtons').show();
                }
                if (action == "hide") {
                    if (!$('#sort-list li').length) $('#no_content').show();
                    $('.options_select_all').hide();
                    $('#optionsMassButtons').hide();
                }
            }
            if (section == "variants") {
                if (action == "show") {
                    $('.variants_select_all').show();
                    $('#variantsMassButtons').show();
                }
                if (action == "hide") {
                    $('.variants_select_all').hide();
                    $('#variantsMassButtons').hide();
                }
            }
        }

        function addProductOptions() {
            var optionIDs = [];
            var optionTexts = [];
            var foundDuplicate = 0;
            $('input[data-id="product_options"]').each(function () {
                var optionID = $(this).val();
                if ($(this).prop("checked")) {
                    if (!optionExists(optionID)) {
                        optionIDs.push($(this).val());
                        optionTexts.push($(this).next().text());
                    } else {
                        foundDuplicate++;
                    }
                }
                $(this).prop("checked", false);
            });

            if (!optionIDs.length) {
                if (!foundDuplicate) {
                    var msg = "<?php echo t("Δεν έχετε επιλέξει καμία επιλογή");?>";
                }
                if (foundDuplicate == 1) {
                    var msg = "<?php echo t("Η επιλογή αυτή είναι ήδη καταχωρημένη σε αυτό το προϊόν");?>";
                }
                if (foundDuplicate > 1) {
                    var msg = "<?php echo t("Οι επιλογές αυτές υπάρχουν ήδη καταχωρημένες σε αυτό το προϊόν");?>";
                }
                if (confirm(msg + "\n<?php echo t("Θέλετε να ακυρώσετε αυτή την ενέργεια;");?>")) {
                    $.fancybox.close();
                }
                return false;
            }
            var query = "";
            for (var n = 0; n < optionIDs.length; n++) {
                query += "&optionIDs[]=" + optionIDs[n];
            }
            jQuery.ajax({
                type: "POST",
                url: "ajax_options.php",
                data: "action=add&productID=<?php echo $productID;?>" + query,
                async: false,
                success: function (response) {
                    response = response.trim();
                    if (response.indexOf("ok_") != -1) {
                        var lastIDs = response.split("ok_")[1];
                        odyshop.lastIDs = lastIDs.split("|");
                        response = "ok";
                    }
                    if (response == "ok") {
                        massControls('options', 'show');
                        for (var n = 0; n < optionIDs.length; n++) {
                            var optionID = optionIDs[n];
                            var optionText = optionTexts[n];
                            var lastID = odyshop.lastIDs[n];
                            var template = $("#tplProductOption").html();
                            $('#sort-list').append(template.format(optionID, optionText, lastID));
                        }
                    } else {
                        popup(response, "popup-warning");
                    }
                }
            });
            $.fancybox.close();
        }

        function addGlobalOption() {
            $('#innerSelectProductsOptions').hide();
            $('#addGlobalOption').show();
            $('#title').focus();
        }

        function hideGlobalOption() {
            $('#innerSelectProductsOptions').show();
            $('#addGlobalOption').hide();
        }

        function saveOption(categories) {
            var title = $('#title').val();
            var has_image = $('#has_image').val();
            if (!title) {
                alert("<?php echo t("Η ονομασία πρέπει να συμπληρωθεί");?>");
                return false;
            }
            jQuery.ajax({
                type: "POST",
                url: "ajax_global_options.php",
                data: "table=product_options&title=" + title + "&has_image=" + has_image + "&related_categories=" + categories,
                async: false,
                success: function (response) {
                    if (response.indexOf("ok_") != -1) {
                        var optionID = response.split("ok_")[1];
                        hideGlobalOption();
                        $('#product_options_wrapper').prepend('<div class="admin_form_element"><div class="admin_checkbox_wrapper"><input data-id="product_options" value="' + optionID + '" type="checkbox"><p>' + title + '</p></div></div>');
                    } else {
                        alert(response);
                        $('#title').val("").focus();
                    }
                }
            });
        }

        function doOptionsActions(elm) {
            var action = ($(elm).hasClass("record_on")) ? "deactivate" : "activate";
            var checkbox = $(elm).prev('input[type="checkbox"]');
            checkbox.prop("checked", true);
            setTimeout(function () {
                massActions(action);
            }, 100);
            var editLink = $(elm).parents('.record_row').find('a[data-type="edit"]');
            if (action == "activate") {
                $(elm).removeClass("record_off").addClass("record_on");
                editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");
            } else {
                $(elm).removeClass("record_on").addClass("record_off");
                editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");
            }
        }

        function doVariantActions(elm) {
            var action = ($(elm).hasClass("record_on")) ? "deactivate" : "activate";
            var checkbox = $(elm).prev('input[type="checkbox"]');
            checkbox.prop("checked", true);
            setTimeout(function () {
                massVariantsActions(action);
            }, 100);
            var editLink = $(elm).parents('.record_row').find('a[data-type="edit"]');
            if (action == "activate") {
                $(elm).removeClass("record_off").addClass("record_on");
                editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");
            } else {
                $(elm).removeClass("record_on").addClass("record_off");
                editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");
            }
        }

        function massActions(action) {
            var IDs = [];
            var massActionsType = $('#massActionsType').val();
            $('#optionsList input[type="checkbox"]').each(function () {
                if ($(this).prop('checked')) {
                    var id = $(this).attr("id").split("optionID")[1];
                    IDs.push(id);
                    $(this).prop("checked", false);
                    $('#selectAllcb').prop("checked", false);
                }
            });
            if (!IDs.length) {
                popup("<?php echo t("Δεν έχετε επιλέξει καμία εγγραφή");?>", "popup-warning");
                return false;
            }

            if (action == "delete") {
                if (IDs.length > 1) {
                    if (massActionsType != "all") {
                        if (!confirm("<?php echo t("Θέλετε να αφαιρέσετε αυτές τις επιλογές από το προϊόν;");?>")) return false;
                    } else {
                        if (!confirm("<?php echo t("Προσοχή! Αυτή η ενέργεια είναι μη αναστρέψιμη");?>\n<?php echo t("Θέλετε να αφαιρέσετε αυτές τις επιλογές και τις παραλλαγές τους από όλα τα παρόμοια προϊόντα;");?>")) return false;
                    }
                } else {
                    if (massActionsType != "all") {
                        if (!confirm("<?php echo t("Θέλετε να αφαιρέσετε αυτή την επιλογή από το προϊόν;");?>")) return false;
                    } else {
                        if (!confirm("<?php echo t("Προσοχή! Αυτή η ενέργεια είναι μη αναστρέψιμη");?>\n<?php echo t("Θέλετε να αφαιρέσετε αυτή την επιλογή και τις παραλλαγές της από όλα τα παρόμοια προϊόντα;");?>")) return false;
                    }

                }
            }
            IDs = IDs.join(",");
            jQuery.ajax({
                type: "POST",
                url: "ajax_options.php",
                data: "productID=<?php echo $productID;?>&action=" + action + "&massActionsType=" + massActionsType + "&IDs=" + IDs,
                async: false,
                success: function (response) {
                    response = response.trim();
                    IDs = IDs.split(",");
                    var msg = "";
                    if (response.indexOf("ok_") != -1) {
                        var parts = response.split("ok_");
                        msg = parts[1];
                        response = "ok";
                    }
                    if (response == "ok") {
                        for (var n = 0; n < IDs.length; n++) {
                            var id = IDs[n];
                            $('#sort-list a[data-id="' + id + '"]').each(function () {
                                if (action == "activate") {
                                    $(this).removeClass("record_off").addClass("record_on");
                                    var editLink = $(this).parents('.record_row').find('a[data-type="edit"]');
                                    editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");
                                }
                                if (action == "deactivate") {
                                    $(this).removeClass("record_on").addClass("record_off");
                                    var editLink = $(this).parents('.record_row').find('a[data-type="edit"]');
                                    editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");
                                }
                                if (action == "delete") {
                                    $(this).parents('.record_row').remove();
                                }
                            });
                        }
                        if (massActionsType == "all") {
                            popup(msg, "popup-info");
                        }
                        if (!$('#sort-list li').length) {
                            massControls('options', 'hide');
                        }
                    } else {
                        popup(response, "popup-warning");
                    }
                }
            });
        }

        function massVariantsActions(action) {
            var IDs = [];
            $('#variants input[type="checkbox"]:not("#selectAllVariantscb")').each(function () {
                if ($(this).prop('checked')) {
                    var id = $(this).prop("value");
                    IDs.push(id);
                    $(this).prop("checked", false);
                    $('#selectAllVariantscb').prop("checked", false);
                }
            });
            if (action == "delete") {
                if (!IDs.length) {
                    popup("<?php echo t("Δεν έχετε επιλέξει καμία εγγραφή");?>", "popup-warning");
                    return false;
                }
                if (IDs.length > 1) {
                    if (!confirm("<?php echo t("Θέλετε να αφαιρέσετε αυτές τις παραλλαγές;");?>")) return false;
                } else {
                    if (!confirm("<?php echo t("Θέλετε να αφαιρέσετε αυτή την παραλλαγή;");?>")) return false;
                }
            }
            IDs = IDs.join(",");
            jQuery.ajax({
                type: "POST",
                url: "ajax_variants.php",
                data: "action=" + action + "&IDs=" + IDs,
                async: false,
                success: function (response) {
                    response = response.trim();
                    IDs = IDs.split(",");
                    if (response == "ok") {
                        for (var n = 0; n < IDs.length; n++) {
                            var id = IDs[n];
                            $('#sort-variants-list li#listItem_' + id).each(function () {
                                var btnAnchor = $(this).find('a.toggler');
                                if (action == "activate") {
                                    btnAnchor.removeClass("record_off").addClass("record_on");
                                    var editLink = btnAnchor.parents('.record_row').find('a[data-type="variant"]');
                                    editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");
                                }
                                if (action == "deactivate") {
                                    btnAnchor.removeClass("record_on").addClass("record_off");
                                    var editLink = btnAnchor.parents('.record_row').find('a[data-type="variant"]');
                                    editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");
                                }
                                if (action == "delete") {
                                    btnAnchor.parents('.record_row').remove();
                                    var editLink = btnAnchor.parents('.record_row').find('a[data-type="variant"]');
                                    var selectOptionID = editLink.attr("data-variant-id");
                                    $('#variants_list input[value="' + selectOptionID + '"]').attr("disabled", false);
                                }
                            });
                        }
                        if (action == "delete") {
                            if ($('#sort-variants-list li:not(.admin_form_element)').length < 2) { // there is always one for new variant
                                $('#results_info').html('<?php echo t("Δεν βρέθηκαν καταχωρημένες παραλλαγές");?>');
                                showNewEntry();
                                massControls('variants', 'hide');
                            }
                            setNewEntryProperties();
                        }
                    } else {
                        popup(response, "popup-warning"); // ajax error
                    }
                }
            });
        }

        function openVariantDetails(elm) {
            hideNewEntry();
            $(elm).next().toggle('fast');
            $('a[data-type="variant"]').each(function () {
                if ($(this).next().attr('id') != $(elm).next().attr('id')) {
                    $(this).next().hide('fast');
                }
            });
            setTimeout(function () {
                $('#variants ul').children('li').each(function () {
                    $(this).css("background-color", "transparent");
                    if ($(this).find("a[data-variant-id]").attr('data-variant-id') == $(elm).attr('data-variant-id')) {
                        if ($(elm).next().is(":visible")) $(this).css("background-color", "silver");
                    }
                });
            }, 200);
        }

        function isAlreadySelected(id) {
            odyshop.returnedValue = false;
            $('a[data-type="variant"]').each(function () {
                if ($(this).attr('data-variant-id') == id) {
                    odyshop.returnedValue = true;
                }
            });
            return odyshop.returnedValue;
        }

        function getVariants() {
            var optionID = odyshop.optionID;
            if ($('#sort-variants-list li').length > 1) {
                massControls('options', 'show');
                return;
            }
            jQuery.ajax({
                type: "POST",
                url: "ajax_variants.php",
                data: "action=get&productID=" + <?php echo $productID;?> +"&optionID=" + optionID,
                async: false,
                success: function (response) {
                    //console.log(response);
                    response = jQuery.parseJSON(response);
                    if (!response.length) {
                        $('#results_info').html('<?php echo t("Δεν βρέθηκαν καταχωρημένες παραλλαγές");?>');
                        showNewEntry();
                        massControls('variants', 'hide');
                    }
                    if (typeof(response) == "object") {
                        for (i in response) {
                            var record = response[i];
                            var id = record.id;
                            var variantID = record.variantID;
                            var active = record.active;
                            active = (active) ? "" : "_deactivate";
                            var image = (record.image && record.image != 'undefined') ? record.image : "";
                            var title = record.title;
                            var variants_modifier = parseFloat(record.variants_modifier).toString();
                            var variants_modifier_type = record.variants_modifier_type;
                            var variants_weight_modifier = parseFloat(record.variants_weight_modifier).toString();
                            var variants_weight_modifier_type = record.variants_weight_modifier_type;
                            var variants_modifier_typeA = (variants_modifier_type == "A") ? " selected='selected'" : "";
                            var variants_modifier_typeP = (variants_modifier_type == "P") ? " selected='selected'" : "";
                            var variants_weight_modifier_typeA = (variants_weight_modifier_type == "A") ? " selected='selected'" : "";
                            var variants_weight_modifier_typeP = (variants_weight_modifier_type == "P") ? " selected='selected'" : "";
                            var has_image = record.has_image;
                            var style = (!parseInt(has_image)) ? ' style="display:none"' : '';
                            var template = $("#tplOptionVariants").html();
                            $('#sort-variants-list').prepend(
                                template.format(
                                    variantID,
                                    title,
                                    active,
                                    image,
                                    variants_modifier,
                                    variants_modifier_typeA,
                                    variants_modifier_typeP,
                                    variants_weight_modifier,
                                    variants_weight_modifier_typeA,
                                    variants_weight_modifier_typeP,
                                    id,
                                    has_image,
                                    style
                                )
                            );
                            if (image) {
                                var variant = $('#sort-variants-list').children(":first").find('a[data-rel="variants_mediabank"]');
                                updateImage(variant, image, variantID);
                            }
                        }
                    } else {
                        popup("Error: " + response, "popup-warning"); // ajax error
                    }
                }
            });

            if (!$('#variants_list li').length) { // auto fill checkboxes with options for add new form
                jQuery.ajax({
                    type: "POST",
                    url: "ajax_option_variants.php",
                    data: "optionID=" + optionID,
                    async: false,
                    success: function (response) {
                        //console.log(response);
                        response = jQuery.parseJSON(response);
                        if (typeof(response) == "object") {
                            for (i in response) {
                                var record = response[i];
                                var id = record.id;
                                var title = record.title;
                                var disable = (isAlreadySelected(id)) ? " disabled" : "";
                                $('#variants_list').append($('<li class="admin_form_element"><div class="admin_checkbox_wrapper"><input name=option_variants[] data-id="variants_list_item" type="checkbox" value="' + id + '" ' + disable + '><p>' + title + '</p></div></li>'));
                            }
                            setNewEntryProperties();
                        } else {
                            popup("Error: " + response, "popup-warning"); // ajax error
                        }
                    }
                });

            }
        }

        function setNewEntryProperties() {
            if ($('#variants_list input:disabled').length == $('#variants_list input').length) {
                // all options are disabled
                $('#variants_list').hide();
                $('#new_entry_label').html("<?php echo t("Δημιουργήστε μια νέα παραλλαγή");?>");
            } else {
                $('#variants_list').show();
                $('#new_entry_label').html("<?php echo t("ή δημιουργία νέας");?>");
            }
        }

        function updateImage(variant, thumb, variantID) {
            var imageEnabled = variant.parents('li').attr('data-hasImage');
            if (!thumb || !imageEnabled) return;
            var img_container = variant.prev();
            img_container.css("background-image", "url(../mediabank/thumbs/small_" + thumb + ")");
            img_container.find('img').attr("src", "../mediabank/thumbs/small_" + thumb);
            variant.next().css("visibility", "visible").next('input[type="hidden"]').val(thumb);
            var browse = variant.parent('.variants_inner').find('a[data-rel="variants_mediabank"]');
            browse.html("<?php echo t("Αλλαγή εικονιδίου");?>");
            if (browse.attr('id') == "new_mediamank_image") $('#add_new_variant').click();
        }

        function removeImage(elm) {
            $(elm).next().val('');
            $(elm).css('visibility', 'hidden');
            $(elm).parent('.variants_inner').find('a[data-rel="variants_mediabank"]').html("<?php echo t("Ορισμός εικονιδίου");?>");
            $(elm).parent('.variants_inner')
                .find('.image_preview').css("background-image", "url(image/blank.gif)")
                .find('img').attr("src", "images/blank.gif");
        }

        function showNewEntry() {
            $('a[data-type="variant"]').each(function () {
                $(this).next().hide('fast');
            });
            var elm = $('#add_new_variant');
            $('#add_details').show('fast');
            $('#add_new_record').val("1");
            $(elm).hide();
            if ($('#sort-variants-list li').length < 2) {
                // hide cancelation button if no other variant exists
                $('#cancel_new_entry').hide();
            } else {
                $('#cancel_new_entry').show();
            }
        }
        function hideNewEntry(noDelay) {
            var speed = (noDelay) ? null : 'fast';
            var elm = $('#add_new_variant');
            $('#add_details').hide(speed);
            $('#add_new_record').val("0");
            $(elm).show();
        }

        function newVariantExists() {
            if ($('#new_variant').val() != "") return false; // a custom variant is ready to be added
            odyshop.nvexists = false;
            var newVariantElm = $('#variants_list');
            $('a[data-variant-id]').each(function () {
                if ($(this).attr('data-variant-id') == newVariantElm.val()) {
                    odyshop.nvexists = true;
                }
            });
            return odyshop.nvexists;
        }

        function saveVariants() {
            if ($('#add_new_record').val() == "1") { // check only when new inserion is activated
                if (newVariantExists()) {
                    popup("<?php echo t("Η παραλλαγή αυτή είναι ήδη καταχωρημένη");?>", "popup-warning");
                    return false;
                }
            }
            var qs = [];
            var form_data = $('#variants').find("*").serializeArray();
            for (i in form_data) qs.push(form_data[i].name + '=' + form_data[i].value);
            qs = qs.join("&");
            jQuery.ajax({
                type: "POST",
                url: "ajax_variants.php",
                data: qs + "&action=save&productID=<?php echo $productID;?>&optionID=" + odyshop.optionID,
                success: function (response) {
                    response = response.trim();
                    if (response.indexOf("ok") != -1) {
                        if ($('#add_new_record').val() == "1") odyshop.reOpen = true; // reopen after new insertion
                        $.fancybox.close();
                    } else {
                        alert(response);
                    }
                }
            });
        }

        function closeVariants() {
            hideNewEntry();
            $.fancybox(close);
        }

        function handleDrag(elm, action) {
            var btn = $(elm).parent().parent().find('a[data-type="variant"]');
            if (action == "start") {
                btn.addClass("drag_active");
                if (btn.next().is(":visible")) btn.click();
                odyshop.cache = $('#add_new');
                $('#add_new').remove();
            }
            if (action == "stop") {
                btn.removeClass("drag_active");
                $('#sort-variants-list').append(odyshop.cache);
            }
        }

        function selectAllVariants(elm) {
            selectAllcb(elm);
            setTimeout(function () {
                $('#sort-list').find('[name^=delID], [name^=selectedID]').each(function () {
                    $(this).prop("checked", false);
                });
            }, 200);
        }

    </script>

    <script type="text/template" id="tplProductOption">
        <li class="record_row" id="listItem_{2}">
            <div>
                <div style="clear:both"></div>
                <div class="chk_container">
                    <input type="checkbox" id="optionID{0}" name="selectedID[]" value="{0}">
                    <a href="javascript:void(0)"
                       data-id="{0}"
                       class="toggler record_on"
                       onClick="doOptionsActions(this);">
                    </a>
                </div>
                <div class="handle ui-sortable-handle" style="float:left; margin: 5px 8px 0 60px">
                    <img src="images/arrow.png" alt="move" align="absmiddle" height="24" width="24">
                </div>
            </div>
            <a data-type="edit" href="#variants" data-edit-id="{0}" class="edit_category">{1}</a>
        </li>
    </script>

    <script type="text/template" id="tplOptionVariants">
        <li class="record_row" id="listItem_{10}" data-hasImage="{11}">
            <div>
                <div style="clear:both"></div>
                <div class="chk_container">
                    <input type="checkbox" id="variantID_{0}" name="selectedID[]" value="{10}">
                    <a href="javascript:void(0)"
                       data-id="{0}"
                       class="toggler record_on"
                       onClick="doVariantActions(this);">
                    </a>
                </div>
                <div class="handle ui-sortable-handle"
                     style="float:left; margin: 5px 8px 0 60px">
                    <img src="images/arrow.png" alt="move" align="absmiddle" height="24" width="24">
                </div>
            </div>
            <a href="javascript:void(0)"
               data-type="variant"
               data-variant-id="{0}"
               class="edit_category{2}"
               onClick="openVariantDetails(this)">
                {1}
            </a>
            <div class="variants_details" id="details_{0}">
                <div class="variants_inner">
                    <?php echo t("Αύξηση τιμής κατά"); ?>
                    <input type="text" id="variants_modifier_{0}" value="{4}" name="variants_modifier[][{0}]" class="listbox modifier" onkeypress="return restrictToFloat(this, event, true)">
                    <select class="listbox modifier" id="variants_modifier_type_{0}" name="variants_modifier_type[][{0}]">
                        <option value="A" {5}><?php echo $eshop->getCurrencyProperty("sign"); ?></option>
                        <option value="P" {6}>%</option>
                    </select>
                </div>

                <div class="variants_inner">
                    <?php echo t("Αύξηση βάρους κατά"); ?>
                    <input type="text" id="variants_weight_modifier_{0}" value="{7}" name="variants_weight_modifier[][{0}]" class="listbox modifier" onkeypress="return restrictToFloat(this, event, true)">
                    <select class="listbox modifier" id="variants_weight_modifier_type_{0}" name="variants_weight_modifier_type[][{0}]">
                        <option value="A" {8}><?php echo $parameters->getParameter("weight_symbol"); ?></option>
                        <option value="P" {9}>%</option>
                    </select>
                </div>

                <div class="variants_inner" {12}>
                    <div class="image_preview"><img src="images/blank.gif"></div>
                    <a href="attachments_variants.php?action=add" data-rel="variants_mediabank" type="button" class="btn btn-info">
                        <?php echo t("Ορισμός εικονιδίου"); ?>
                    </a>
                    <a href="javascript:void(0)" onclick="removeImage(this)" class="remove_image"></a>
                    <input type="hidden" id="variants_image_{0}" name="variants_image[][{0}]" value="{3}">
                </div>
            </div>
        </li>
    </script>
    <div style="position:relative">
        <div class="admin_module_title"><h4><?php echo t("Επιλογές προϊόντος"); ?></h4></div>
    </div>
    <div style="text-align: center; margin:5px;">

        <div id="inventory_forbidden">
            <a id="open_inventory_forbidden" href="#tab7" onclick="setSelected(document.getElementById('option7')); this.blur();"><?php echo t("Απαγορευμένοι Συνδυασμοί"); ?></a>
        </div>
        <div id="inventory">
            <a id="open_inventory" href="#tab6" onclick="setSelected(document.getElementById('option6')); this.blur();"><?php echo t("Συνδυασμοί & απόθεμα"); ?></a>
        </div>
        <div id="add_product_option">
            <a id="open_select_product_options" href="#selectProductsOptions" onclick="this.blur();"><?php echo t("Προσθέστε επιλογές"); ?></a>
        </div>

        <div id="productOptions">
            <?php
            $q = "select po.id, cpo.title, o.id as sortID, o.active from product_options as po, content_product_options as cpo, options as o where  
			po.id=cpo.mainID 
			and cpo.langID='$langID' 
			and po.id=o.optionID 
			and o.productID='$productID' 
			order by o.sort ";
            $records = $db->getRecords($q);
            $hasOptions = count($records);
            $actionText = ($hasOptions) ? 'show' : 'hide';
            ?>
            <div id="no_content"><?php echo t("Δεν υπάρχουν ακόμα καταχωρημένες επιλογές"); ?></div>
            <script type="text/javascript">jQuery(function ($) {
                    massControls('options', '<?php echo $actionText;?>');
                });</script>

            <div class="admin_form_element options_select_all">
                <div class="admin_checkbox_wrapper">
                    <input id="selectAllcb" style="position:absolute; top :-2px;" type="checkbox" onclick="selectAllcb(this)">
                    <p style="font-size: .8em; color: grey; font-style:italic"><?php echo t("Επιλογή όλων"); ?></p>
                </div>
            </div>

            <div id="optionsList">
                <ul class="ui-sortable" id="sort-list">
                    <?php
                    foreach ($records as $record) {
                        $titleATTR = (!$record->active) ? $inactiveTitle : $activeTitle;
                        ?>

                        <li class="record_row" id="listItem_<?php echo $record->sortID; ?>">
                            <div>
                                <div style="clear:both"></div>

                                <div class="chk_container">
                                    <input type="checkbox" id="<?php echo "optionID" . $record->id; ?>" name="selectedID[]" value="<?php echo $record->id; ?>">
                                    <?php
                                    if ($record->active) {
                                        ?>
                                        <a href="javascript:void(0)"
                                           data-id="<?php echo $record->id; ?>"
                                           class="toggler record_on"
                                           onClick="doOptionsActions(this);">
                                        </a>
                                        <?php
                                    } else {
                                        ?>
                                        <a href="javascript:void(0)"
                                           data-id="<?php echo $record->id; ?>"
                                           class="toggler record_off"
                                           onClick="doOptionsActions(this);">
                                        </a>
                                        <?php
                                    }
                                    ?>
                                </div>
                                <div class="handle ui-sortable-handle" style="float:left; margin: 5px 8px 0 60px">
                                    <img src="images/arrow.png" alt="move" align="absmiddle" height="24" width="24">
                                </div>
                            </div>
                            <a data-type="edit"
                               href="#variants"
                               data-edit-id="<?php echo $record->id; ?>"
                               class="edit_category<?php if (!$record->active) {
                                   echo "_deactivate";
                               } ?>"
                               title="<?php echo $titleATTR; ?>">
                                <?php echo $record->title; ?>
                            </a>
                        </li>
                        <?php
                    }
                    ?>
                </ul>
            </div>
            <div id="optionsMassButtons"><?php echo t("με τα επιλεγμένα"); ?>:
        	<span style="white-space: nowrap">
			<input type="button"
                   id="massOptionsDelete"
                   value="<?php echo t("Αφαίρεση"); ?>"
                   class="btn btn-danger btn-medium"
                   onClick="massActions('delete')">
			<input type="button"
                   id="massOptionsActivate"
                   value="<?php echo t("Ενεργοποίηση"); ?>"
                   class="btn btn-success btn-medium"
                   onClick="massActions('activate')">
			<input type="button"
                   id="massOptionsDeactivate"
                   value="<?php echo t("Απενεργοποίηση"); ?>"
                   class="btn btn-inverse btn-medium"
                   onClick="massActions('deactivate')">
            </span>
                <!--
			<input type="button" 
            id="massOptionsApply" 
            value="<?php echo t("Εφαρμογή σε παρόμοια προϊόντα"); ?>"
            class="btn btn-info btn-medium" 
            onClick="massActions('apply')">   
            -->
                <div style="text-align: right; font-size: 0.8em !important;">
                    <?php echo t("Εφαρμογή ενεργειών σε"); ?>
                    <select name="massActionsType" id="massActionsType" class="listbox">
                        <option value="this"><?php echo t("αυτό το προϊόν μόνο"); ?></option>
                        <option value="all"><?php echo t("όλα τα παρόμοια προϊόντα"); ?></option>
                    </select>
                </div>
            </div>
        </div>

        <div id="selectProductsOptions">
            <div id="innerSelectProductsOptions">
                <?php
                $productCategoriesArray = $content->getMultipleValues("products", "catID", $productID);
                $productCategories = implode(",", $productCategoriesArray);
                $SL_sectionID = $system->getTableSectionID('product_options');
                $SL_fieldID = $system->getFieldID('related_categories', $SL_sectionID);

                $q = "select distinct a.id, b.title 
                from product_options as a, 
                content_product_options as b, 
                selectlists as s  
                where a.id=b.mainID 
                and b.langID='$langID' 
                and a.active=1 
                and s.sectionID='$SL_sectionID' 
                and s.fieldID='$SL_fieldID' 
                and s.itemID=a.id 
                and s.optionID IN (" . $productCategories . ") order by a.sort";
                $options = $db->getRecords($q);
                if (!count($options)) {
                    $messages->addMessage(t("Δεν βρέθηκαν διαθέσιμες επιλογές που να σχετίζονται με τις κατηγορίες αυτού του προϊόντος"));
                    ?>
                    <div style="max-width:450px">
                        <?php
                        $messages->printSystemMessages();
                        ?>
                    </div>
                    <?php
                } else {

                    ?>
                    <div class="section_title" style="min-width: 270px; margin-bottom: 30px"><?php echo t("Επιλέξτε τις επιλογές του προϊόντος"); ?></div>
                    <div id="product_options_wrapper">
                        <?php
                        foreach ($options as $option) {
                            ?>
                            <div class="admin_form_element">
                                <div class="admin_checkbox_wrapper">
                                    <input data-id="product_options" type="checkbox" value="<?php echo $option->id; ?>">
                                    <p><?php echo $option->title; ?></p>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>

                    <div style="margin: 10px">
                        <input type="button"
                               class="btn btn-success"
                               value="<?php echo t("Προσθήκη"); ?>"
                               onclick="addProductOptions()">
                    </div>
                    <div class="admin_form_element" style="display:table; margin: 0 auto;">
                        <div class="admin_checkbox_wrapper">
                            <a href="javascript:void(0)"
                               class="plus"
                               onclick="addGlobalOption()"></a>
                            <p style="font-size: .8em; white-space: nowrap;"><?php echo t("Προσθέστε περισσότερες καθολικές επιλογές"); ?></p>
                        </div>
                    </div>
                    <?php
                }
                ?>
            </div>
            <div id="addGlobalOption">
                <div class="section_title" style="min-width: 270px; margin-bottom: 50px; margin-top: 20px"><?php echo t("Προσθήκη καθολικής επιλογής"); ?></div>
                <div class="admin_form_element">
                    <div class="admin_label">
                        <p style="padding-right:20px;">
                            <?php echo t("Ονομασία"); ?> :
                        </p>
                    </div>
                    <div class="normal_wrapper">
                        <input id="title" name="title_gr" class="listbox" type="text" style="width: 250px;">
                    </div>
                </div>

                <div class="admin_form_element" style="display: table; margin: 15px auto -15px;">
                    <div class="admin_checkbox_wrapper">
                        <input name="has_image" id="has_image" value="1" type="checkbox">
                        <p><?php echo t("Με δυνατότητα εικόνας"); ?></p>
                    </div>
                </div>

                <div class="admin_form_element" style="margin-top: 20px;">
                    <input class="btn btn-success" value="<?php echo t("Αποθήκευση"); ?>" type="button" onclick="saveOption('<?php echo $productCategories; ?>')">
                    <input class="btn btn-warning" value="<?php echo t("Ακύρωση"); ?>" type="button" onclick="hideGlobalOption()">
                </div>

                <div class="tip" style="display:table; width: 160px; margin: 20px auto 0 auto;"><b><?php echo t("Προσοχή"); ?>!</b><br>
                    <?php echo t("Ίσως χρειαστεί να ενημερώσετε τις μεταφράσεις"); ?>
                </div>
            </div>
        </div>


        <div id="variants" style="text-align: left" data-optionID="">
            <div class="section_title" id="variants_title" style="min-width: 270px; margin-bottom: 0"><!-- auto complete by js --></div>
            <div class="admin_form_element variants_select_all">
                <div class="admin_checkbox_wrapper">
                    <input id="selectAllVariantscb" type="checkbox" onclick="selectAllVariants(this); ">
                    <p style="font-size: .8em; color: grey; font-style:italic"><?php echo t("Επιλογή όλων"); ?></p>
                </div>
            </div>
            <div id="results_info"></div>
            <ul class="ui-sortable" id="sort-variants-list">
                <li id="add_new">
                    <div id="variantsMassButtons"><?php echo t("με τα επιλεγμένα"); ?>:
                	<span style="white-space: nowrap">
                        <input type="button"
                               id="massOptionsDelete"
                               value="<?php echo t("Αφαίρεση"); ?>"
                               class="btn btn-danger btn-mini"
                               onClick="massVariantsActions('delete')">
                        <input type="button"
                               id="massOptionsActivate"
                               value="<?php echo t("Ενεργοποίηση"); ?>"
                               class="btn btn-success btn-mini"
                               onClick="massVariantsActions('activate')">
                        <input type="button"
                               id="massOptionsDeactivate"
                               value="<?php echo t("Απενεργοποίηση"); ?>"
                               class="btn btn-inverse btn-mini"
                               onClick="massVariantsActions('deactivate')">
                    </span>
                    </div>
                    <a id="add_new_variant" href="javascript:void(0)" onclick="showNewEntry()" title="<?php echo t("Προσθήκη παραλλαγών"); ?>"></a>
                    <div style="clear:both;"></div>
                    <div class="variants_details" id="add_details" style="border-bottom: none !important">
                        <div id="section_title_new_variant" class="section_title" style="min-width: 270px; margin-bottom: 50px">
                            <?php echo t("Προσθήκη παραλλαγών"); ?>
                        </div>
                        <div id="cancel_new_entry">
                            <input type="button"
                                   class="btn btn-danger btn-mini"
                                   style="font-size: .8em !important;"
                                   value="Χ"
                                   onclick="hideNewEntry()">
                        </div>
                        <div class="variants_inner">
                            <ul id="variants_list"></ul>
                            <br>
                    <span style="display: inline-block">
                        &nbsp;&nbsp;<span id="new_entry_label"><?php echo t("ή δημιουργία νέας"); ?></span> :
                        <input type="text" id="new_variant" name="new_variant" style="width: 140px;" class="listbox">
                    </span>
                        </div>
                    </div>
                </li>
            </ul>
            <div style="text-align: right; margin-top: 20px; padding-top: 5px; border-top: 2px solid silver;">
                <input type="hidden" id="add_new_record" name="add_new_record" value="0">
                <input type="button"
                       id="saveVariant"
                       value="<?php echo t("Αποθήκευση"); ?>"
                       onclick="saveVariants()"
                       class="btn btn-success">
                <input type="button"
                       id="closeVariants"
                       value="<?php echo t("Κλείσιμο"); ?>"
                       onclick="closeVariants()"
                       class="btn btn-inverse">
            </div>
        </div>
        <input type="hidden" name="action" value="save">
    </div>

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