<?php
require_once('common/header.php');
require("common/menu.php");

if(!empty($_GET['table'])){
    $tableName = $_GET['table'];
}else{
    die("Please select a table!");
}


$table = new Table($tableName);
$id = !empty($_GET['id']) ? $_GET['id'] : 0;
//oneRowTables have only one default row and users cannot add to it
if(!$table->isCrudEnabled() && empty($id)){
    redirect_to("dashboard.php");
}
?>
<section>
    <!-- Page content-->
    <div class="content-wrapper">

        <div id='loader'>
            <div class="panel panel-default"  style="border: 0;background-color: transparent;">
                <div class="panel-body loader-demo" style="border: 0;padding-top: 20%;">
                    <div class="ball-scale-ripple-multiple" >
                        <div></div>
                        <div></div>
                        <div></div>
                    </div>
                </div>
            </div>
        </div>

        <div >
            <?php include(ADMIN_PATH.DS."common/generateForm.php"); ?>
        </div>
        <!-- TinyMCE -->

    </div>

</section>


<?php require_once('common/footer.php'); ?>

<script type="text/javascript" src="<?php echo ADMIN_PATH_HTML;?>/js/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="<?php echo ADMIN_PATH_HTML;?>/js/tinymce/jquery.tinymce.min.js"></script>

<script type="text/javascript">
    // Create the tooltips only on document load
    $(document).ready(function()
    {
        // By suppling no content attribute, the library uses each elements title attribute by default
        $('.tooltipMessage[title]').qtip({

        });

        // NOTE: You can even omit all options and simply replace the regular title tooltips like so:
        // $('#content a[href]').qtip();
    });
</script>



<script type="text/javascript">
    // initialize editors
    initMCE();

    $(document).ready(function(){
        if ( $('input[placeholder=Slug]') && $('input[placeholder=Slug]').val() == '' ) {
            // if ( $('input[placeholder=Title]') || $('input[placeholder=Name]') ) {
            // var field = ( $('input[placeholder=Title]') ) ? $('input[placeholder=Title]') : $('input[placeholder=Name]');
            // field.keyup(function(){
            // $('input[placeholder=Slug]').val(string_to_slug($(this).val()));
            // });
            // }
        }
        if ($('input[placeholder=Permalink]')) {
            if ($('input[placeholder=Title]')) {
                $('input[placeholder=Title]').keyup(function(){
                    if  ( $('input[placeholder=Permalink]').val() == '') {
                        $('input[placeholder=Permalink]').val(string_to_slug($(this).val()));
                    }
                });
            }
        }
        if ($('input[placeholder=Slug]')) {
            if ($('input[placeholder=Title]')) {
                $('input[placeholder=Title]').keyup(function(){
                    if  ( $('input[placeholder=Slug]').val() == '') {
                        $('input[placeholder=Slug]').val(string_to_slug($(this).val()));
                    }
                });
            }
        }


        var lastID = "";
        if($("input[name=data\\[videos\\]\\[youtube_id\\]]")){
            updateYoutubeInfo("Invalid Youtube ID");
            $("input[name=data\\[videos\\]\\[youtube_id\\]]").on("keyup", function(){
                var youtubeID = $("input[name=data\\[videos\\]\\[youtube_id\\]]").val();
                if(validYoutube("https://www.youtube.com/watch?v=" + youtubeID) && lastID != youtubeID){
                    lastID = youtubeID;
                    var apiURL = "https://www.googleapis.com/youtube/v3/videos?id=" + youtubeID + "&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails";
                    $.ajax({
                        async: false,
                        type: 'GET',
                        url: apiURL,
                        success: function(data) {
                            if (data.items.length > 0) {
                                var duration = convert_time(data.items[0].contentDetails.duration);
                                var title = data.items[0].snippet.title;
                                if($("input[name=data\\[videos\\]\\[duration\\]]").length > 0){
                                    $("input[name=data\\[videos\\]\\[duration\\]]").val(duration);
                                }

                                updateYoutubeInfo("Loaded Title: <b>" + title + "</b>" + "<br>Duration: " + duration);
                            }else{
                                updateYoutubeInfo("Invalid Youtube ID");
                            }

                        }
                    });
                }
            });
        }
    });

    function updateYoutubeInfo(message) {
        console.log(message);
        if ($('#youtubeInfo').length == 0) {
            $("input[name=data\\[videos\\]\\[youtube_id\\]]").parent().removeClass("col-md-10").addClass("col-md-6");
            $("input[name=data\\[videos\\]\\[youtube_id\\]]").parent().after("<div class='col-md-4' id='youtubeInfo'>" + message + "</div>");
        } else {
            $('#youtubeInfo').html(message);
        }
    }

    function validYoutube(url) {
        var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
        var match = url.match(regExp);
        if (match && match[2].length == 11) {
            return true;
        } else {
            return false;
        }
    }

    function convert_time(duration) {
        var a = duration.match(/\d+/g);

        if (duration.indexOf('M') >= 0 && duration.indexOf('H') == -1 && duration.indexOf('S') == -1) {
            a = [0, a[0], 0];
        }

        if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1) {
            a = [a[0], 0, a[1]];
        }
        if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1 && duration.indexOf('S') == -1) {
            a = [a[0], 0, 0];
        }

        duration = 0;

        if (a.length == 3) {
            duration = duration + parseInt(a[0]) * 3600;
            duration = duration + parseInt(a[1]) * 60;
            duration = duration + parseInt(a[2]);
        }

        if (a.length == 2) {
            duration = duration + parseInt(a[0]) * 60;
            duration = duration + parseInt(a[1]);
        }

        if (a.length == 1) {
            duration = duration + parseInt(a[0]);
        }
        var h = Math.floor(duration / 3600);
        var m = Math.floor(duration % 3600 / 60);
        var s = Math.floor(duration % 3600 % 60);
        return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s);
    }

    function string_to_slug(str) {
        str = str.replace(/^\s+|\s+$/g, ''); // trim
        str = str.toLowerCase();

        // remove accents, swap ñ for n, etc
        var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
        var to   = "aaaaeeeeiiiioooouuuunc------";
        for (var i=0, l=from.length ; i<l ; i++) {
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
            .replace(/\s+/g, '-') // collapse whitespace and replace by -
            .replace(/-+/g, '-'); // collapse dashes

        return str;
    }
</script>
<!-- /TinyMCE -->
