/*      Facebook Quiz App V.2.1.1
 *      Auth @arirah 
 *      
 *      Login Box JS 
 *      Using Animate CSS Effets 
 * */
// Login Page 
function varticalCenterStuff() {
    var windowHeight = $(window).height();
    var loginBoxHeight = $('.login-box').innerHeight();
    var welcomeTextHeight = $('.welcome-text').innerHeight();
    var loggedIn = $('.logged-in').innerHeight();
    var mathLogin = (windowHeight / 2) - (loginBoxHeight / 2);
    var mathWelcomeText = (windowHeight / 2) - (welcomeTextHeight / 2);
    var mathLoggedIn = (windowHeight / 2) - (loggedIn / 2);
    $('.login-box').css('margin-top', mathLogin);
    $('.welcome-text').css('margin-top', mathWelcomeText);
    $('.logged-in').css('margin-top', mathLoggedIn);
}
$(window).resize(function() {
    varticalCenterStuff();
});
varticalCenterStuff();
// Awesomeness
/* Login page */
$('.btn-login').click(function() {
    $(this).parent().fadeOut(function() {
        $('.login-box').fadeIn();
    })
});
// Login page Cancel buttong action
$('.btn-cancel-action').click(function(e) {
    e.preventDefault(); // Prevent default action
    $(this).parent().parent().parent().fadeOut(function() {
        $('.welcome-text').fadeIn();
    })
});

// Login button submit
$('.btn-login-submit').click(function(e) {
    $('#auth-check').html('<i class="fa fa-spin fa-spinner"></i> Authentication your Login Credential ... ');
    e.preventDefault();
    var element = $(this).parent().parent().parent();
    var usernameEmail = $('#username-email').val();
    var password = $('#password').val();
    if (usernameEmail == '' || password == '') {

// Wigle Effect and show notification
// Wigle
        var element = $(this).parent().parent().parent();
        $(element).addClass('animated rubberBand');
        $(element).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(element).removeClass('animated rubberBand');
        });
        // Notification
        // reset
        $('.notification.login-alert').removeClass('bounceOutRight notification-show animated bounceInRight');
        // show notification
        $('.notification.login-alert').addClass('notification-show animated bounceInRight');
        $('.notification.login-alert').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            setTimeout(function() {
                $('.notification.login-alert').addClass('animated bounceOutRight');
            }, 2000);
        });
        $('#auth-check').html('');
    } else {
        $url = $('form').attr('action');
        $values = $('form').serialize(); // Login form serialize data 
        $.post($url, $values).done(function(d) {
            if (d.success == 1) {
                $('#auth-check').html('<i class="fa fa-check"></i> Login success!');
                window.location = '/admin';
            } else {
                var element = $(this).parent().parent().parent();
                $(element).addClass('animated rubberBand');
                $(element).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                    $(element).removeClass('animated rubberBand');
                });
                // Notification
                // reset
                $('.notification.login-alert').removeClass('bounceOutRight notification-show animated bounceInRight');
                // show notification
                $('.notification.login-alert').addClass('notification-show animated bounceInRight');
                $('.notification.login-alert').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                    setTimeout(function() {
                        $('.notification.login-alert').addClass('animated bounceOutRight');
                    }, 2000);
                });
                $('#auth-check').html('');
            }
        });
    }
});
// Logout Button Action 
$('.btn-logout').click(function() {
    $('.logged-in').fadeOut(function() {
        $('.welcome-text').fadeIn();
        // Notification
        $('.notification.logged-out').removeClass('bounceOutRight notification-show animated bounceInRight');
        // show notification
        $('.notification.logged-out').addClass('notification-show animated bounceInRight');
        $('.notification.logged-out').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            setTimeout(function() {
                $('.notification.logged-out').addClass('animated bounceOutRight');
            }, 2000);
        });
    });
});

/*  Login end */
/*----------------------------------------*/
// JS for admin panel .Code for secure area 
// All forms manages by ajax 
// and prevent form default actions 
/*----------------------------------------*/
/* Manage Quiz */
$('.delete_quiz').click(function() {
    var quiz_id = $(this).attr('data-quiz-id');
    modalCall('Confirmation', '<i class="fa fa-notification"></i>  Are you sure, you want to delete this quiz ?? <br><br><br>\n\
    \n\
    <button class="btn btn-sm btn-info" onclick="deleteQuiz(' + quiz_id + ')"> Yes</button> <msg></msg> ');
});

$('.edit_quiz').click(function() {
    $('.modal-content').addClass('bounceInLeft animated');
    $('.quiz-form').html('<i class="fa fa-spin fa-spinner"></i> Loading ...');
    $path = $(this).attr('path');
    $.get($path, function(d) {
        $('.quiz-form').html(d);
    });
});
// Quiz Delete function 
function deleteQuiz(q)
{
    $.post('/admin/quiz-delete', {'q_id': q}, function(d) {
        if (d.success == 1) {
            $('msg').html(d.msg);
            window.location.reload();
        } else {
            window.location.reload();
        }
    });
}
// On Modal close event 
$('#myModal').on('hide.bs.modal', function(e) {
    $('.quiz-form').html('');
})
// Add more options 
$('#add_quiz_opt').click(function()
{
    var opt_count = 0;
    opt_count = $('input[name="addoptn"]').length;
    if (opt_count > 6) { // If needs more than 6 options change here 
        modalCall('Alert', ' You can not add more option ! ');
        return false;
    }
    // Option Input html 
    var html = '<div class="clearfix optn-rmv">&nbsp;</div>' +
            '<div class="input-group optn-rmv">' +
            '<span class="input-group-addon">' +
            '<input type="radio" name="addoptn" aria-label="" value="">' +
            '</span>' +
            '<input type="text" name="option_text[]" class="form-control input-sm opt" placeholder = "Quiz Option">' +
            '<span class = "input-group-addon btn"  onclick="removeOpt($(this))">' +
            '<i class = "fa fa-times" > </i>' +
            '</span>' +
            '</div>';
    $('.quiz-append').prepend(html);
    $('input[name="addoptn"]').each(function(i) {
        $(this).val(i);
    });
});

/* Modal function 
 * Using bootstrap modal 
 * Prepend to html tag then open 
 * */
function modalCall(heading, text)
{
    var html = '<div style="" class="modal fade bs-example-modal-sm" id="alert" 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="col-xs-12 text-right">'
            + '<button type="button" class="btn btn-danger btn-sm close-modal" data-dismiss="modal">Close</button>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>';
    $('body').prepend(html);
    $('#alert').modal({'backdrop': 'static'});
    $('#alert').addClass('animated bounce');
    $('#alert').on('hidden.bs.modal', function(e) {
        $('#alert').remove();
    });
}
// Remove option
function removeOpt(param)
{
    var item = param.parent().closest('.optn-rmv');
    var next = item.prev('.optn-rmv');
    next.remove();
    item.remove();
}
// Form validation  
$('#save_quiz').click(function() {
    var input_text = $("#add_quiz_form :input[type=text]");
    var form_submit = 1;
    var error = 0;
    input_text.each(function() {
        $(this).removeClass('has-error animated bounce');
        if ($(this).val() == '')
        {
            $(this).addClass('has-error animated bounce');
            form_submit = 0;
            error = 1;
        }
    });
    if ($('input[name="addoptn"]').is(':checked') === false) {
        form_submit = 0;
        error = 2;
    }
    if ($('#quiz_group').val() == 0) {
        form_submit = 0;
        error = 3;
    }
    if (form_submit == 0 && error == 1) {
        modalCall('Input Error!', 'Please fill in the quiz and options!');
    }
    else if (form_submit == 0 && error == 2) {
        modalCall('Input Error!', 'Please check the correct answer!');
    }
    else if (form_submit == 0 && error == 3) {
        modalCall('Input Error!', 'Please select a group!');
    } else {
        $("#add_quiz_form").submit();
    }

});

// Quiz form submit .. prevent default action .
$("#add_quiz_form").submit(function(e)
{
    var submit_action = $(this).attr('action');
    $('.quiz-loader').html('<i class="fa fa-spinner fa-spin"></i>');
    var inputs = $(this).serialize(); // Serialize form input data to array 
    $.post(submit_action, inputs).done(function(data) {
        var obj = $.parseJSON(data);
        if (obj.success == 1) {
            $('.quiz-loader').html(obj.msg);
            $("#reset_quiz_form").click();
            window.location.reload();
        }
        else
        {
            $('.quiz-loader').html(obj.msg);
            window.location.reload();
        }
    });
    e.preventDefault();
    //return false;
});

$('#update_quiz').click(function()
{
    $('#update_quiz_form').submit();
});
$('#save_group_form').submit(function(e) {
    if ($('#groupinput').val() == '')
    {
        modalCall('Input Error!', 'Please provide a group name!');
        return false;
    }
    var submit_action = $(this).attr('action');
    $('#group_loader').html('<i class="fa fa-spinner fa-spin"></i>');
    var inputs = $(this).serialize(); // Serialize form input data to array 
    $.post(submit_action, inputs).done(function(data) {
        var obj = data;
        if (obj.success == 1) {
            $('#group_loader').html('<i class="fa fa-check"></i> Successfully added ! ');
            window.location.reload(); // Page reload
        } else
        {
            window.location.reload();
        }
    });
    e.preventDefault();
    // return false;
});
$('#save_group').click(function() {
    $('#save_group_form').submit();
});
function deleteGroupName(group_id)
{
    $.post('/admin/group-delete', {'g_id': group_id}, function(d) {
        if (d.success == 1) {
            $('msg').html(d.msg);
            window.location.reload(); // Page reload 
        } else
        {
            $('msg').html(d.msg);
            window.location.reload();
        }
    });
}

$('.delete_group').click(function() {
    var group_id = $(this).attr('data-group-id');
    modalCall('Confirmation', '<i class="fa fa-notification"></i>  Are you sure you want to delete this group ?? <br><br><br>\n\
    \n\
    <button class="btn btn-sm btn-info" onclick="deleteGroupName(' + group_id + ')"> Yes</button> <msg></msg> ');
});
$('.edit_group').click(function() {
    $('.modal-content').addClass('bounceInLeft animated');
    $path = $(this).attr('path');
    $.get($path, function(d) {
        $('.group-form').html(d);
    });
});
$('#save_quiz_setting_form').submit(function(e) {
    if ($('#quiz_group').val() == 0)
    {
        modalCall('Input Error!', 'Please select a quiz group name!');
        return false;
    }
    var submit_action = $(this).attr('action');
    $('#group_loader').html('<i class="fa fa-spinner fa-spin"></i>');
    var inputs = $(this).serialize(); // Serialize form input data to array 
    $.post(submit_action, inputs).done(function(data) {
        var obj = data;
        if (obj.success == 1) {
            $('#group_loader').html('<i class="fa fa-check"></i> ' + obj.msg);
            window.location.reload();  // Page reload 
        } else
        {
            $('#group_loader').html('<i class="fa fa-times"></i> ' + obj.msg);
            window.location.reload();
        }
    });
    e.preventDefault();
    // return false;

});
$('#save_quiz_setting').click(function() {
    $('#save_quiz_setting_form').submit();
});
/* File button click */

$("#uploadBtnHeader").change(function() {
    $('#uploadFileHeader').val($(this).val());
});

$("#uploadBtnFooter").change(function() {
    $('#uploadFileFooter').val($(this).val());
});

/* Save setting */
$('#save_page_setting').click(function()
{
    $('#page_loader').html('<i class="fa fa-spin fa-spinner"></i>');
    tinyMCE.triggerSave();
    $('#page_setting_form').submit();
});

$('#page_setting_form').submit(function(e) {
    var submit_action = $(this).attr('action');
    $.ajax({
        url: submit_action, // Url to which the request is send
        type: "POST", // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false, // The content type used when sending data to the server.
        cache: false, // To unable request pages to be cached
        processData: false, // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
            var obj = data;
            if (obj.success === 1) {
                //$('#page_loader').html('<i class="fa fa-check"></i> ' + obj.msg); // If success 
                //window.location.reload();  // Page reload 
                $('#page_loader').html('');
                $.notify(obj.msg, 'success'); // Notify JS 
            } else
            {
                $('#page_loader').html('<i class="fa fa-times"></i> ' + obj.msg);
                window.location.reload();
            }
        }
    });
    e.preventDefault();

});
// Block Users 
$('.block-user').click(function() {
    $(this).html('<i class="fa fa-spinner fa-spin"></i>');
    var uid = $(this).attr('uid'); // User Id 
    var url = $(this).attr('url'); // Get URL 
    $.post(url, {'uid': uid}).done(function(d) {
        if (d.success == 1)
        {
            window.location.reload();  // Page reload 
        } else
        {
            $(this).html('Failed!');
        }
    });
});


/* New Updates */

/* Schedule delete */
function deleteSchedule(schedule_id)
{
    $.post('/admin/schedule-delete', {'schedule_id': schedule_id}, function(d) {
        if (d.success == 1) {
            $('msg').html(d.msg);
            window.location.reload(); // Page reload 
        } else
        {
            $('msg').html(d.msg);
            window.location.reload();
        }
    });
}
/* Schedule delete confirmation modal call */
$('.schedule-delete').click(function() {
    var schedule_id = $(this).attr('schedule_id');
    modalCall('Confirmation', '<i class="fa fa-notification"></i>  Are you sure, you want to delete this quiz Schedule? <br><br><br>\n\
    \n\
    <button class="btn btn-sm btn-info" onclick="deleteSchedule(' + schedule_id + ')"> Yes</button> <msg></msg> ');
});


// Add more options 
$('#add_poll_opt').click(function()
{
    var opt_count = 0;
    opt_count = $('input[name="addoptn"]').length;
    if (opt_count > 6) { // If needs more than 6 options change here 
        modalCall('Alert', ' You can not add more option ! ');
        return false;
    }
    // Option Input html 
    var html = '<div class="clearfix optn-rmv">&nbsp;</div>' +
            '<div class="input-group optn-rmv">' +
            '<input type="text" name="option_text[]" class="form-control input-sm opt" placeholder = "Poll Option">' +
            '<span class = "input-group-addon btn"  onclick="removeOpt($(this))">' +
            '<i class = "fa fa-times" > </i>' +
            '</span>' +
            '</div>';
    $('.poll-append').prepend(html);
    $('input[name="addoptn"]').each(function(i) {
        $(this).val(i);
    });
});

// Poll Form validation  
$('.save_poll').click(function() {
    var input_text = $("#add_poll_form :input[type=text]");
    var form_submit = 1;
    var error = 0;
    input_text.each(function() {
        $(this).removeClass('has-error animated bounce');
        if ($(this).val() == '')
        {
            $(this).addClass('has-error animated bounce');
            form_submit = 0;
            error = 1;
        }
    });

    if (form_submit == 0 && error == 1) {
        modalCall('Input Error!', 'Please fill in the red marked field.!');
        return false;
    }
    else {
        $("#add_poll_form").submit();
    }
});

// Quiz form submit .. prevent default action .

$("#add_poll_form").submit(function(e)
{
    var submit_action = $(this).attr('action');
    $('.poll-loader').html('<i class="fa fa-spinner fa-spin"></i>');
    var inputs = $(this).serialize(); // Serialize form input data to array 
    $.post(submit_action, inputs).done(function(data) {
        var obj = data;
        if (obj.success == 1) {
            $('.poll-loader').html(obj.msg);
            $("#reset_poll_form").click();
            window.location.reload();
        }
        else
        {
            $('.poll-loader').html(obj.msg);
            window.location.reload();
        }
    });
    e.preventDefault();
    //return false;
});



$('#load-meadia').click(function() {
    var btn = $(this);
    btn_content = btn.html();
    btn.html('<i class="fa fa-spinner fa-spin"></i>');
    var files = '';
    var html = '';
    $.ajax('/admin/load-ajax-media-files').done(function(obj) {
        if (obj.success == 1) {
            modalCall('Media files', '<h5>Add files from <strong><a href="/admin/media-manager">Media option</a></strong></h5><br>' + obj.msg);
            btn.html(btn_content);
        } else
        {
            window.location.reload();
        }
        $('.add-img').on('click', function() {
            var img_url = $(this).attr('img');
            $('#file_name').val(img_url);

            $('#poll_img').attr('src', img_url);
            $('#poll_img').removeClass('hide');
            $('.close-modal').click();

        });

    });
    //modalCall('Media files', '<h5>Add files from <strong><a href="/admin/media-manager">Media option</a></strong></h5><br>'+html);
});

$('#save_file').click(function() {
    if ($('.filestyle').val() == '')
    {
        modalCall('Input Error', '<h4>Please browse and add file.</h4>');
        return false;
    }
    $('#add_media_form').submit();
});

$('#add_media_form').submit(function(e) {
    var submit_action = $(this).attr('action');
    $('#page_loader').html('<i class="fa fa-spinner fa-spin"></i>Please wait...'); // Uploading progress...
    $.ajax({
        url: submit_action, // Url to which the request is send
        type: "POST", // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false, // The content type used when sending data to the server.
        cache: false, // To unable request pages to be cached
        processData: false, // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
            var obj = data;
            if (obj.success === 1) {
                $.notify(obj.msg, 'success'); // Notify JS 
                // $('#page_loader').html('<i class="fa fa-check"></i> ' + obj.msg); // If success 
                window.location.reload();  // Page reload 
            } else
            {
                $('#page_loader').html('<i class="fa fa-times"></i> ' + obj.msg);
                window.location.reload();
            }
        }
    });
    e.preventDefault();
});

$('.delete-file').click(function() {
    var cn = confirm('Do you want to delete this file ?');
    if (cn === true)
    {
        var file_name = $(this).attr('file_name');
        $.post('/admin/delete-media-file', {'file_name': file_name}).done(function(d) {
            if (d.success == 1) {
                window.location.reload();  // Page reload 
            } else
            {
                $(this).html('Failed!');
            }
        });
    } else
    {
        return false;
    }
    //deleteMediaFile
});

$('.delete-poll').click(function() {
    var poll_id = $(this).attr('poll_id');
    modalCall('Confirm Delete', '<h4>Are you sure , you want to delete this poll ? </h4><br><br><a href="/admin/poll-delete/' + poll_id + '" class="btn btn-sm btn-info"> Delete </a>');
});

$('.img-gal').click(function() {
    var img_src = $(this).attr('src');
    modalCall('Image', '<img class="img-responsive" height="70%" src="' + img_src + '">');
});

$('.add-img').on('click', function() {
    var img_url = $(this).attr('img');
    $('#image_name').val(img_url);
});

// Edit poll ajax call 
$('.edit-poll').click(function() {

    var poll_id = $(this).attr('poll-id');
    $.ajax('/admin/poll-edit/' + poll_id).done(function(d) {
        modalCall('Edit Poll', d);
        $('#update-media').on('click', function() {
            var html = '';
            $.ajax('/admin/load-ajax-media-files').done(function(obj) {
                modalCall('Media files', '<h5>Add files from <strong><a href="/admin/media-manager">Media option</a></strong></h5><br>' + obj);

                $('.add-img').on('click', function() {
                    var img_url = $(this).attr('img');
                    $('#file_name').val(img_url);

                    $('#poll_img').attr('src', img_url);

                });

            });
        });
    });



});

function addImageLink(param)
{
    var link = ($(param).attr('link')) ? $(param).attr('link') : '';
    var link_id = ($(param).attr('link_id')) ? $(param).attr('link_id') : '';
    var html = '<input class="form-control input-sm" name="footer_image_link" value="' + link + '" placeholder="http://">\n\
<br><button class="btn btn-sm btn-info" id="save-link">Save Link</button> &nbsp; <span id="save-link"><span>';
    modalCall('Add image link', html);
    $('#save-link').click(function() {
        var link = $('input[name="footer_image_link"]').val();
        var form_action = '/admin/save-page-setting';
        $.post(form_action, {'image_link': link, 'add_image_link': 1, 'link_id': link_id}).done(function(e) {
            $('span#save-link').html(e);
        });
    });

}

$('.remove-slider').click(function() {
    var i = this.parentNode.parentNode.rowIndex;
    document.getElementById("slider-list").deleteRow(i);
});

// New page form submit by JS 
$('.save-btn').click(function() {

    if ($('input[name="page_name"]').val() == '')
    {
        $(this).focus();
        modalCall('Input Error', 'Please provide a page name.');
        return false;
    }
    $('#save_page_form').submit();
});
// Delete page function 
$('.delete-page').click(function() {
    var page_id = $(this).attr('page_id');
    modalCall('Confirm', 'Are you sure , you want to delete this page ? <br><br> <button class="btn btn-sm btn-info confirm-delete">Yes</button>');
    $('.confirm-delete').on('click', function() {
        $.post('/admin/page-delete/' + page_id).done(function(e) {
            if (e.success == 1)
            {
                $.notify(e.msg); // Notify JS 
                // Your application has indicated there's an error
                window.setTimeout(function() {
                    // Move to a new location or you can do something else
                    window.location.href = "/admin/manage-pages";
                }, 2000);

            }
        });
        $('#alert .close-modal').click();

    });

});

// Custom facebook share text and details text 

$('#save_custom_text').click(function() {
    $('#custom_text_form').submit();
});

$('#custom_text_form').submit(function(e) {
    var btn = $('#save_custom_text');
    var btn_content = btn.html();
    btn.html('<i class="fa fa-spinner fa-spin"></i>');
    var submit_action = $(this).attr('action');
    $.ajax({
        url: submit_action, // Url to which the request is send
        type: "POST", // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false, // The content type used when sending data to the server.
        cache: false, // To unable request pages to be cached
        processData: false, // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
            var obj = data;
            if (obj.success === 1) {
                $.notify(obj.msg, 'success'); // Notify JS 
                // $('#page_loader').html('<i class="fa fa-check"></i> ' + obj.msg); // If success 
                //window.location.reload();  // Page reload 
                btn.html(btn_content);
            } else
            {
                $.notify(obj.msg); // Notify JS 
                // $('#page_loader').html('<i class="fa fa-times"></i> ' + obj.msg);
                // window.location.reload();
            }
        }
    });
    e.preventDefault();
});