// Views javascript functions

var viewrotationenabled = false;
var viewrotationpaused = false;
var currentviewnum = 0;
var currentviewid = "";
var viewrotationspeed = 5;
var currentviewtitle = "";
var currentviewurl = "";


// return a true or false depending on if
// we have any views or not
function have_views() {

    // we name the views' ids statically, so if view_0 doesnt exist
    // that means we have no views, and we need to disable rotation temporarily
    // so that the main.php views page can be shown proper
    if ($("#view_0").length == 0)
        return 0;

    return 1;
}


$(document).ready(function() {

    get_user_meta('view_rotation_enabled', function(rotation_enabled) {

        rotation_enabled = parseInt(rotation_enabled);
        if (isNaN(rotation_enabled))
            rotation_enabled = 0;

        if (!have_views())
            rotation_enabled = 0;

        if (rotation_enabled == 0) {

            $('.viewspeed-slider-box').hide();
            $('.rotation-stopped').show();
            $('.btn-view-pr').html('<i class="fa fa-stop"></i>');
            $('.btn-view-pr').prop('disabled', true);

            post_ajax_data_with_callback('get_views_text', { str: "start" }, function(text) {
                $('.rotatemyviewslink a').html('<i class="fa fa-play"></i>&nbsp;' + text);
            });
        }
    });

    ///////////////////////////////////////////////////////////////////////////////
    // ADD TO MY VIEWS
    ///////////////////////////////////////////////////////////////////////////////

    $("#addtomyviews a").click(function() {
    
        show_throbber();
        var theurl = $('#maincontentframe').contents()[0].URL;
        hide_throbber();

        var opts = {
            "theurl": theurl
            };

        post_ajax_data_with_callback('get_add_to_views_form', opts, function(data) {

            $("#popup_container").html(data);
            hide_throbber();
            display_popup();

            $("#addview_form").submit(function() {

                hide_throbber();
                var params = {};
                $(this) 
                    .find(":input, :password, :checkbox, :radio, :submit, :reset")
                    .each(function() { 
                        params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
                    });
            
                params["nsp"] = nsp_str;

                $.ajax({
                    type: "POST",
                    url: this.getAttribute("action"),
                    data: params,
                    beforeSend: function(XMLHttpRequest) {
                        get_ajax_data_html('get_add_to_views_submitting', 0, $("#popup_container"));
                    },
                    success: function(msg) {
                        get_ajax_data_html('get_add_to_views_success', 0, $("#popup_container"));
                    },
                    error: function(msg) {
                        get_ajax_data_html('get_add_to_views_error', 0, $("#popup_container"));
                    }
                });
                return false;
            });
        });
    });

    $("#leftnav").on('click', 'li.rotatemyviewslink a', function() {
        if (viewrotationenabled || viewrotationpaused) {
            stop_view_rotation();
        } else {
            start_view_rotation(currentviewnum + 1);
        }
    });

    $("#leftnav").on('click', 'li.managemyviews a', function() {
        if (viewrotationenabled == true) {
            pause_view_rotation();
        }
    });
        
    // get current set speed and set slider
    get_user_meta('view_rotation_speed', function(viewrotationspeed) {

        viewrotationspeed = viewrotationspeed_sanity(viewrotationspeed);

        // start rotation
        get_user_meta('view_rotation_enabled', function(rotation_enabled) {
            
            rotation_enabled = parseInt(rotation_enabled);
            if (isNaN(rotation_enabled))
                rotation_enabled = 1;

            if (!have_views())
                rotation_enabled = 0;

            if (rotation_enabled) {
                start_view_rotation(0);
            } else {
                show_new_view(0);
            }

            // set the slider
            $("#myviewspeedslider").slider({
                value: viewrotationspeed, 
                step: 5,
                min: 5, 
                max: 60,
                slide: function(event, ui) { },
                change: function(event, ui) {

                    pause_view_rotation();
                    viewrotationspeed = ui.value;
                    
                    var opts = {
                        "keyname": "view_rotation_speed",
                        "keyvalue": viewrotationspeed,
                        "autoload": false
                        };

                    set_user_meta_with_success(opts, function () {

                        show_throbber();
                        resume_view_rotation(currentviewnum + 1);
                        hide_throbber();
                    });
                }
            }); // set the slider

        }); // start totation
    }); // get current speed  

    $(".btn-view-pr").click(function() {

        show_throbber();
        pauseresume_view_rotation();
        hide_throbber();
    });    

    $("#leftnav").on('click', 'a.mymenulink', function() {

        // Stop view rotation
        stop_view_rotation();
        
        var theparent = this.parentNode;
        var url = this.href;
        var title = this.innerHTML;
        var rawid = this.id;
        var id = rawid.substr(5);
        
        var num = parseInt(get_ajax_data("getviewnumfromid", id));
        currentviewnum = num;
        
        fill_view_screen(title, url, id);
        return;
    });

});


///////////////////////////////////////////////////////////////
// VIEW FUNCTIONS
///////////////////////////////////////////////////////////////

function highlight_views_menu_item(id)
{
    $("#"+id).removeClass("menulink").addClass("activemenulink");
}

function update_views_menu(callback) {

    var $el;

    if (inframe) {
        $el = $(".menusectiontitle[data-id='views-mine']", parent.document).parent();
    } else {
        $el = $(".menusectiontitle[data-id='views-mine']").parent();
    }

    get_ajax_data_with_callback("get_my_views_menu", 0, function(data) {

        $el.html(data);

        if (typeof callback !== 'undefined') {
            callback();
        }
    });
}

function fill_view_screen(title, url, id)
{
    update_views_menu(function() { highlight_views_menu_item(id); });

    $("#maincontentframe").attr({src: url});

    currentviewid = id;
    currentviewurl = url;
    currentviewtitle = title;
}
    
function show_new_view(num)
{
    // start over if we reached the end!
    if (!$("#view_" + num).length)
        num = 0;

    var id = "view_" + num;
    if ($("#" + id).length) {

        var view_title = $("li#" + id + " a").html();
        var view_url = $("li#" + id + " a").attr("href");

        fill_view_screen(view_title, view_url, id);

        currentviewnum = num;
    }
}
    
function stop_view_rotation()
{
    $(this).stopTime("viewrotationtimer");
    $('.viewspeed-slider-box').hide();
    viewrotationenabled = false;
    viewrotationpaused = false;

    post_ajax_data_with_callback('get_views_text', { str: "start" }, function(text) {
        $('.rotatemyviewslink a').html('<i class="fa fa-play"></i>&nbsp;' + text);
    });
    
    // Stop countdown timer
    current_time = 0;
    clearInterval(current_timer_id);
    current_time = viewrotationspeed;
    $('#current-time').html('');

    $('.rotation-stopped').show();
    $('.btn-view-pr').html('<i class="fa fa-stop"></i>');
    $('.btn-view-pr').prop('disabled', true);

    var opts = {
        "keyname": "view_rotation_enabled",
        "keyvalue": 0,
        "autoload": false
    };
    set_user_meta(opts);
}
    
function start_view_rotation(num)
{
    if (!have_views())
        return false;

    var $t = $(this);

    get_user_meta('view_rotation_speed', function(viewrotationspeed) {

        viewrotationspeed = viewrotationspeed_sanity(viewrotationspeed);
    
        start_timer_to_next_rotation();
        show_new_view(num);

        $t.stopTime("viewrotationtimer");
        $t.everyTime(viewrotationspeed * 1000, "viewrotationtimer", function(i) {
            
            currentviewnum += 1;
            show_new_view(currentviewnum);
            start_timer_to_next_rotation();
        });

        $('.rotation-stopped').hide();
        $('.btn-view-pr').attr('data-original-title', 'Pause rotation');
        $('.btn-view-pr').html('<i class="fa fa-pause"></i>');
        $('.btn-view-pr').prop('disabled', false);
        
        $(".viewspeed-slider-box").show();
        viewrotationenabled = true;
        viewrotationpaused = false;

        post_ajax_data_with_callback('get_views_text', { str: "stop" }, function(text) {
            $('.rotatemyviewslink a').html('<i class="fa fa-stop"></i>&nbsp;' + text);
        });


        var opts = {
            "keyname": "view_rotation_enabled",
            "keyvalue": 1,
            "autoload": false
        };
        set_user_meta(opts);
    });
}
    
function pause_view_rotation()
{
    $(this).stopTime("viewrotationtimer");
    $('.btn-view-pr').attr('data-original-title', 'Resume rotation');
    $('.btn-view-pr').html('<i class="fa fa-play"></i>');
    viewrotationenabled = false;
    viewrotationpaused = true;
    clearInterval(current_timer_id);
    current_time = viewrotationspeed;
}

function resume_view_rotation(newviewnum)
{
    start_view_rotation(newviewnum);
    $('.btn-view-pr').attr('data-original-title', 'Pause rotation');
    $('.btn-view-pr').html('<i class="fa fa-pause"></i>');
    viewrotationenabled = true;
    viewrotationpaused = false;
}
    
function pauseresume_view_rotation()
{
    if (viewrotationenabled == false) {
        resume_view_rotation(currentviewnum+1);
    } else {
        pause_view_rotation();
    }
}

var current_timer_id = 0;
var current_time = 0;
function start_timer_to_next_rotation()
{
    get_user_meta('view_rotation_speed', function(viewrotationspeed) {

        viewrotationspeed = viewrotationspeed_sanity(viewrotationspeed);

        if (current_timer_id != 0) {
            clearInterval(current_timer_id);
            current_time = viewrotationspeed;
        }

        if (current_time <= 0) {
            current_time = viewrotationspeed;
        }

        // Start a timer
        $('#current-time').html(current_time);
        current_timer_id = setInterval(run_current_timer, 1000);
    });
}

function run_current_timer()
{
    current_time--;
    $('#current-time').html(current_time);
}

// sanity check result from grabbing viewrotationspeed
function viewrotationspeed_sanity(rotationspeed) {

    rotationspeed = parseInt(rotationspeed);
    if (isNaN(rotationspeed))
        rotationspeed = 5;

    if (rotationspeed < 5)
        rotationspeed = 5;
    if (rotationspeed > 60)
        rotationspeed = 60;

    return rotationspeed;
}