/*      Vinnorokom Facebook Quiz App V.2.1.1
 *      Arirah@vinnorokom     
 *      --------------------------- 
 *      Facebook Login Button
 *      Facebook loging loading bar counting 
 *      Not connecting real server side , just a demo show :) 
 *      Call Timer JS */




$('#facebook-btn').click(function() {
    $('.progress').removeClass('hide');
    var count = 0;
    // Login status bar 
    var timer = $.timer(function() {      // Start Timer assign to timer variable
        count = Math.round(1.7 * (++count));// 
        $('.progress-bar').css({'width': count + '%'});
        if (count > 100)
        {
            count = 100;
            timer.pause; // Timer pause 
        }
        $('.progress-parcent').html('Connecting to facebook ... ' + count + '%');
    });
    timer.set({time: 1000, autostart: true});
});



$('.facebook-connection').click(function() {
    var btn_elem = $(this);
    var btn_html = btn_elem.html();
    btn_elem.html('');
    btn_elem.html(btn_html + ' <i class="fa fa-spinner fa-pulse"></i>');

});

/* QUIZ button Next button Active */
$('input[name="option"]').click(function() {
    var elem = $('.quiz-btn');
    elem.removeClass('disabled');
    elem.removeAttr('disabled');
});

/* Modal call */
function modalCall(heading, text, body)
{
    var html = '<div style="" class="modal fade bs-example-modal-sm" id="modalCall" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">'
            + '<div class="modal-dialog modal-sm">'
            + '<div class="modal-content" style="padding: 15px"><h3>' + heading + '</h3>'
            + '<h4 style="">' + text + '</h4>'
            + '<div class="clearfix">&nbsp;</div>'
            + '<div class="">' + body + '</div>'
            + '<div class="col-xs-12 text-right">'
            + '<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>';
    $('body').prepend(html);
    $('#modalCall').modal({'backdrop': 'static'});
    $('#modalCall').addClass('animated bounce');
    $('#modalCall').on('hidden.bs.modal', function(e) {
        $('#modalCall').remove();
    });
}


/* Poll voting */
$(document).ready(function() {

    $('#poll-content').html('<i class="fa fa-spinner fa-spin fa-2x"></i>');
    $.get('/polls-today').done(function(e) {
        $('#poll-content').html(e);
 $('#poll-today').html('');
        $('#poll-today .vote').on('click', function() {
            $poll_id = $(this).attr('poll-id');
            $.ajax('/user/poll-form/' + $poll_id).done(function(html) {
               if (html.success == 1) {
                    modalCall('<i class="fa fa-question-circle"></i> Click and vote', '', html.msg);
                }
                else {
                    modalCall('<i class="fa fa-question-circle"></i> Please Login ', '', '<br><br> <a href="/login/fb" class="btn btn-info btn-facebook" id="facebook-btn"><i class="fa fa-facebook"></i> Connect with Facebook  </a>');
                }
           });
      });

   });
    $('.poll-content').each(function() {
        var poll_id = $(this).attr('poll_id');
        var poll_content = $('#poll-content-' + poll_id);
        var content = poll_content;
        content.html('<i class="fa fa-spinner fa-spin fa-2x"></i>');
        $.get('/polls-by-id/' + poll_id).done(function(e) {
            content.html(e);
            // $('#poll-today').html('');
            $(poll_content).find('.vote').on('click', function() {
                var btn = $(this);
                var btn_content = btn.html();
                btn.html('<i class="fa fa-spinner fa-spin"></i>');
                $.ajax('/user/poll-form/' + poll_id).done(function(html) {
                    if (html.success == 1) {
                        modalCall('<i class="fa fa-question-circle"></i> Click and vote', '', html.msg);
                        btn.html(btn_content);
                    }
                    else {
                        modalCall('<i class="fa fa-question-circle"></i>  'Please connect  to cast your vote.', '<br><br> <button onclick="facebookLogin();" class="btn btn-info btn-facebook facebook-btn" id="facebook-btn"><i class="fa fa-facebook"></i> Facebook Login  </button>');
                        btn.html(btn_content);
                    }
                });

            });
            // Share button action
            $('.share').on('click', (function() {
                var url = $(this).attr('short_url');

                FB.ui(
                        {
                            method: 'share',
                            href: url,
                        },
                        function(response) {
                            if (response && !response.error_code) {
                                modalCall('<i class="fa fa-check"></i> Thank you for sharing your vote. ', '', 'Your friends can see and vote here !');
                            } else {
                                // alert('Error while posting.');
                            }
                        }
                );
            }));


        });

    });


});
// Share button action
$('.share').on('click', (function() {
    var url = $(this).attr('short_url');

    FB.ui(
            {
                method: 'share',
                href: url,
            },
            function(response) {
                if (response && !response.error_code) {
                    modalCall('<i class="fa fa-check"></i> Thank you for sharing. ', '', '');
                } else {
                    // alert('Error while posting.');
                }
            }
    );
}));

// View More content load by Ajax 
$('.view-more').click(function() {
    var btn = $(this);
    var btn_content = btn.html();
    btn.html('<i class="fa fa-spinner fa-spin"></i>');
    var content = $('.vote');
    var arrId = [];
    content.each(function(e) {
        arrId[e] = $(this).attr('poll-id');
    });
    $min_id = Math.min.apply(Math, arrId);


    $.get('/polls-view-more/' + $min_id).done(function(e) {
        $html = '<div class="col-md-12 animated fadeIn bg-default poll-content" id="poll-content-' + e.poll_id + '" poll_id="' + e.poll_id + '">'
                + e.view
                + '</div>'
                + '<div class="clearfix">&nbsp;</div>'
                + '<div class="clearfix load-content">&nbsp;</div> ';
        if (e == 0)
        {
            $html = '<div class="col-md-12 animated fadeIn bg-default poll-content" id="poll-content-{{$p->poll_id}}" poll_id="{{$p->poll_id}}">'
                    + 'No more polls !'
                    + '</div>'
                    + '<div class="clearfix">&nbsp;</div>'
                    + '<div class="clearfix load-content">&nbsp;</div> ';
            $('#more').html($html);
            btn.html(btn_content);
        } else
        {
            $($html).insertAfter($('.load-content').last());
            btn.html(btn_content);
        }
        // Scoll down to targeted element 
        $('html, body').animate({
            scrollTop: $('.load-content').last().offset().top
        }, 1000);
        var poll_id = e.poll_id;
        var poll_content = $('#poll-content-' + poll_id);
        var content = poll_content;
        $(poll_content).find('.vote').on('click', function() {
            var btn = $(this);
            var btn_content = btn.html();
            btn.html('<i class="fa fa-spinner fa-spin"></i>');
            $.ajax('/user/poll-form/' + poll_id).done(function(html) {
                if (html.success == 1) {
                    modalCall('<i class="fa fa-question-circle"></i> Click and vote', '', html.msg);
                    btn.html(btn_content);
                }
                else {
                    modalCall('<i class="fa fa-question-circle"></i> Please Login', 'Please connect with facebook to cast your vote.', '<br><br> <button onclick="facebookLogin();"class="btn btn-info btn-facebook facebook-btn" id="facebook-btn"><i class="fa fa-facebook"></i> Login with Facebook  </button>');
                    btn.html(btn_content);
                }
            });
        });

        // Share button action
        $('.share').on('click', (function() {
            var url = $(this).attr('short_url');
            FB.ui(
                    {
                        method: 'share',
                        href: url,
                    },
                    function(response) {
                        if (response && !response.error_code) {
                            modalCall('<i class="fa fa-check"></i> Thank you for sharing your vote. ', '', 'Your friends can see and vote here !');
                        } else {
                            // alert('Error while posting.');
                        }
                    }
            );
        }));
    });

});

$('.facebook-btn').on('click', function() {
    facebookLogin();
});
// Facebook Login 
function facebookLogin()
{
    FB.login(function(response) {
        if (response.authResponse) {
            // console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                //console.log('Good to see you, ' + response.email + '.');
                $.post('/facebook-auth', {'data': response}).done(function(e) {
                    if (e.success == 1)
                    {
                        window.location = '/user/user';
                    }
                });
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, {scope: 'email'});
}

//

// Facebook Login 
function facebookLoginOnPage()
{
    FB.login(function(response) {
        if (response.authResponse) {
            // console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                //console.log('Good to see you, ' + response.email + '.');
                $.post('/facebook-auth', {'data': response}).done(function(e) {
                    if (e.success == 1)
                    {
                        window.location.reload();
                    }
                });
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, {scope: 'email'});
}


// Quiz select from font end 

$('select[name="group_name"]').change(function() {
    $('#page_loader').html('<i class="fa fa-spinner fa-spin fa-1x"></i> ');
    var set_url = $(this).val();
    var url = '/user/user/?quiz_group=' + set_url;
    window.location = url;
});


// Quiz option selection 
$('.options-row').click(function() {
    $('.option').removeClass('ques-row').addClass('options-row');
    var option_id = $(this).attr('option_id');
    if (option_id > 0)
    {
        $('button').removeClass('disabled');
    }
    $('input[name="answer_id"]').val(option_id);
//    $('.option').each(function() {
//        $(this).removeClass('ques-row').addClass('options-row');
//    });
    $(this).toggleClass('options-row').toggleClass('ques-row');
});

// Quiz selection and redirect 
$('.quiz').click(function() {
    var quiz_id = ($(this).attr('quiz_id')) ? $(this).attr('quiz_id') : 0;
    $(this).addClass('slideUp')
    window.location = 'get-started/' + quiz_id;
});


// Number validation

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}


// If guess number page is not logged in user found 
$('.login-first').click(function() {
    modalCall('<i class="fa fa-question-circle"></i> Please login first  !', 'Please connect with facebook for playing guess number ! .', '<br><br> <button onclick="facebookLoginOnPage();" class="btn btn-info btn-facebook facebook-btn" id="facebook-btn"><i class="fa fa-facebook"></i> Connecting with Facebook  </button>');

});