(function( $ ) {
	'use strict';

    var max_length = null,
        increment = null,
        today_max_length = null,
        today_increment = null;

        liveTable();
        todayTable();

    function liveTable() {

        $.post(ajaxurl, {action:"live-visitors"}, function(response){

            var data = $.parseJSON(response);

            //Make sure there is some data returned
            if ( data.length ){

                //Check this is the first load
                if ( !$("table.live-table").length ){

                    //Create the table
                    var table = Handlebars.compile( $("#live-table").html() );
                    $(".users-live:not(.today)").after( table( {table_class:"live-table"} ) );

                    //Create table head
                    var table_head = Handlebars.compile( $("#live-table-head").html() );
                    $("table.live-table").prepend(table_head({
                        user : data_array.user,
                        current_page : data_array.current_page,
                        browser : data_array.browser,
                        time_on_site : data_array.time_on_site,
                        pages_visited : data_array.pages_visited
                    }));

                }

                if ( $("table.live-table tbody tr").length != data.length ) {

                    $("table.live-table tbody").empty();

                    max_length = $("table.live-table").attr("data-length");
                    increment = $("table.live-table").attr("data-increment");

                    //Create table rows for each user on the site
                    for ( var i = 0; i < data.length; i++ ) {

                        var row = Handlebars.compile( $("#live-table-row").html() );
                        $("table.live-table tbody").append( row({

                            class_name    : ( i >= max_length ) ? "hide" : "",
                            user          : ( data[i].user_name ) ? data[i].user_name : data[i].user_ip,
                            current_page  : data[i].user_current_page,
                            browser       : data[i].user_browser,
                            time_on_site  : data[i].user_total_time,
                            time_on_site_live : "00:00:00",
                            pages_visited : data[i].user_total_pages,
                            iso : data[i].user_iso

                        }) );
                    }

                    liveTableTime();

                    //If there are hidden rows then show the load more button
                    if ($("table.live-table tbody tr.hide").length && !$("button.live-table").length) {

                        var button = Handlebars.compile( $("#live-table-load-more").html() );
                        $("table.live-table").after( button );
                    }

                } else {

                    for ( var i = 0; i < data.length; i++ ) {

                        $("table.live-table tbody tr:nth-child("+ (i + 1) +") td.page a").html(data[i].user_current_page);
                        $("table.live-table tbody tr:nth-child("+ (i + 1) +") td.page a").attr("href", data[i].user_current_page);
                        $("table.live-table tbody tr:nth-child("+ (i + 1) +") td.page a").attr("title", data[i].user_current_page);
                        $("table.live-table tbody tr:nth-child("+ (i + 1) +") td.page").attr("data-tooltip", data[i].user_current_page);
                        $("table.live-table tbody tr:nth-child("+ (i + 1) +") td.pages_visited span").html(data[i].user_total_pages);

                    }

                }


            } else {

                $("table.live-table").remove();
            }


            if ( data.length )
                $(".users-live:not(.today) span").html( data.length );
            else
                $(".users-live:not(.today) span").html( 0 );

        });
    }

    function liveTableTime() {

        $(".time_on_site_span").each(function(){

            var start = $(this).attr("data-time");
            var self = this;

            var interval = setInterval(function(){

                var s = moment(start);
                var now = moment().format("YYYY-MM-DD H:m:ss");
                var diff = moment().diff(moment(start, "DD-MM-YYYY hh:mm A"), "milliseconds");
                var diff = parseInt(diff.toString().replace("-", ""));



                var x = diff / 1000
                var seconds = x % 60
                x /= 60
                var minutes = x % 60
                x /= 60
                var hours = x % 24


                hours = (Math.floor(hours).toString().length == 1) ? "0" + (Math.floor(hours)) : Math.floor(hours);
                minutes = (Math.floor(minutes).toString().length == 1) ? "0" + (Math.floor(minutes)) : Math.floor(minutes);
                seconds = (Math.floor(seconds).toString().length == 1) ? "0" + (Math.floor(seconds)) : Math.floor(seconds);


                s = hours + ":" + minutes + ":" + seconds;
                $(self).html(s);

            }, 1000);

        });


    }

    function todayTable() {

        $.post(ajaxurl, {action:"today-live-visitors"}, function(response){

            if ( $("[data-child-open]").attr("data-child-open") != 1 ) {

                var data = $.parseJSON(response);

                if ( data.length ){

                    //Check this is the first load
                    if ( !$("table.today-table").length ){

                        //Create the table
                        var table = Handlebars.compile( $("#live-table").html() );
                        $(".users-live.today").after( table( {table_class:"today-table"} ) );

                        //Create table head
                        var table_head = Handlebars.compile( $("#today-table-head").html() );
                        $("table.today-table").prepend(table_head({
                            user : data_array.user,
                            browser : data_array.browser,
                            time_on_site : data_array.time_on_site,
                            pages_visited : data_array.pages_visited
                        }));

                        $("table.today-table").attr("data-child-open", 0);
                    }

                    today_max_length = $("table.today-table").attr("data-length");
                    today_increment = $("table.today-table").attr("data-increment");

                    $("table.today-table tbody").empty();

                    for ( var i = 0; i < data.length; i++ ) {

                        var row = Handlebars.compile( $("#today-table-row").html() );
                        $("table.today-table > tbody").append( row({

                            class_name    : ( i >= today_max_length ) ? "hide" : "",
                            user          : ( data[i].user_name ) ? data[i].user_name : data[i].user_ip,
                            browser       : data[i].user_browser,
                            time_on_site  : data[i].user_total_time,
                            pages_visited : data[i].user_total_pages,
                            row           : i,
                            iso : data[i].user_iso

                        }) );

                        var subtable_row = Handlebars.compile( $("#subtable-parent-row").html() );
                        var subtable = build_history_table( data[i] );

                        $("table.today-table > tbody").append( subtable_row({
                            row_parent : i,
                            subtable : subtable
                        }) );


                    }

                    //If there are hidden rows then show the load more button
                    if ($("table.today-table > tbody > tr.hide:not([data-row-parent])").length && !$("button.today-table").length) {

                        var button = Handlebars.compile( $("#today-table-load-more").html() );
                        $("table.today-table").after( button );
                    }

                }else {

                    $("table.today-table").remove();

                }

                if ( data.length )
                    $(".users-live.today span").html( data.length );
                else
                    $(".users-live.today span").html( 0 );

            }

        });
    }

    setInterval(function(){

        liveTable();
        todayTable();

    }, 10000);

    $(document).on("click", "button.live-table", function(){

        load_more( "table.live-table", "button.live-table" );

    });

    $(document).on("click", "button.today-table", function(){

        load_more( "table.today-table", "button.today-table" );

    });

    function load_more( table, button ) {

        var table = $(table);

        var show = parseInt(table.attr("data-length"));
        var limit = parseInt(table.attr("data-increment"));

        table.find("tbody tr.hide:not([data-row-parent])").each(function( i ){

            if ( i < show )
                $(this).removeClass("hide");


        });

        table.attr("data-length", limit + show);

        if ( !table.find("tbody tr.hide:not([data-row-parent])").length )
            $(button).remove();

    }

    function build_history_table( data ){

        var body = "";
        for ( var i = 0; i < data.user_history.length; i++ ){

            var subtable_row = Handlebars.compile( $("#subtable-row").html() );

            body = body + subtable_row({

                page : data.user_history[i].live_visitor_page_view_page_url,
                start_time : data.user_history[i].live_visitor_page_view_start_time,
                end_time : data.user_history[i].live_visitor_page_view_end_time,
                time_on_page : data.user_history[i].diff

            });
        }

        var table = Handlebars.compile( $("#subtable").html() );

        return table({
            body : body,
            page : data_array.page,
            start_time : data_array.start_time,
            end_time : data_array.end_time,
            time_on_page : data_array.time_on_page
        });
    }

    $(document).on("click", ".load-subtable", function(){

        var id = $(this).closest("tr").attr("data-row");

        if ($("[data-row-parent='"+ id +"']").hasClass("hide")){
            $("[data-row-parent='"+ id +"']").removeClass("hide");

            $(this).find("i").removeClass("fa-plus-circle").addClass("fa-minus-circle");
            $("[data-child-open]").attr("data-child-open", 1);

        }else {
            $("[data-row-parent='"+ id +"']").addClass("hide");
            $(this).find("i").removeClass("fa-minus-circle").addClass("fa-plus-circle");
            $("[data-child-open]").attr("data-child-open", 0);
        }


    });

    $(document).on("click", ".purchase-code-container .error span.hover", function(){


        $(this).parent(".error").slideUp(function(){
            $(this).find("span.text").html("");
        });

    });

    $(document).on("click", "button.purchase-code-check", function(e){

        e.preventDefault();

        if ( $("input[name='purchase-code-input']").val().trim() == "" ){

            $(".purchase-code-container .error").find("span.text").html("Please enter a Purchase Code");
            $(".purchase-code-container .error").slideDown();

            setTimeout(function(){

                $(".purchase-code-container .error").slideUp(function(){
                    $(this).find("span.text").html("");
                });

            }, 3000);

            return;

        }else {

            var purchaseCode = $("input[name='purchase-code-input']").val();

            $.post(ajaxurl, {action:"verify_plugin", purchaseCode:purchaseCode, apiAction:"newVerify"}, function(data){
                console.log(data);
                if (data.charAt(0) == "\""){

                    var data = data.replace(/\\/g, "");
                    var data = data.substring(0, data.length - 1);
                    var data = data.substring(1);

                }

                var json = $.parseJSON(data);

                if ( json.status_code != 1 ){

                    $(".purchase-code-container .error").find("span.text").html(json.message);
                    $(".purchase-code-container .error").slideDown();

                    setTimeout(function(){

                        $(".purchase-code-container .error").slideUp(function(){
                            $(this).find("span.text").html("");
                        });

                    }, 3000);

                    return;

                }else {

                    $(".purchase-code-container .success").html(json.message);
                    $(".purchase-code-container .success").slideDown();

                    $.post(ajaxurl, {action:"addPurchaseCodeOption", purchaseCode:purchaseCode}, function(){
                        location.reload();
                    });

                    return;
                }

            });

        }

    });



})( jQuery );
