/********************************** modal ***********************************/
//pushstate
if (history.pushState) {
    $('body').on('loaded.bs.modal', '.modal', function(e){
        var $modal = $(this);
        if ($modal.data('state_pushed')) {
            window.history.pushState({modal: '#'+$modal.attr('id'), url: $modal.data('state_pushed'), content: $modal.find('.modal-content').html() }, '', $modal.data('state_pushed'));
        }
    });
    $('body').on('show.bs.modal', '.modal', function(e){
        var $invoker = $(e.relatedTarget);
        var url = $invoker.attr('href');
        if (!url) return;
        $(this).data('state_pushed', url);
    });
    $('body').on('hidden.bs.modal', '.modal', function () {
        var $modal = $(this);
        if ($modal.data('state_pushed')) {
            window.history.back();
            $modal.removeData('state_pushed');
        }
    });
    window.onpopstate = function(e) {
        if (e.state !== null && 'modal' in e.state) {
            var $modal = $(e.state.modal);
            $modal.find('.modal-content').html(e.state.content);
            $modal.data('state_pushed', e.state.url).modal();
            return;
        } else {
            $('.modal').each(function(){
                var $modal = $(this);
                if ($modal.data('state_pushed')) {
                    $modal.removeData('state_pushed');
                    $modal.modal('hide');
                }
            });
        }
    };
}
//allow reloading
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});
/****************************** datepickers ***********************************/
$('.datepicker').each(function(){
    var $this = $(this);
    $this.datetimepicker({
        language: LOCALE,
        pickDate: $this.data('pick_date'),
        pickTime: $this.data('pick_time'),
        useSeconds: false,
        defaultDate: $this.data('default_date')
    });
    $this.on("dp.change",function (e) {
        var id = $this.attr('id');
        var date = $this.data('DateTimePicker').getDate();
        var $sfDate = $this.siblings('input:hidden[rel=' + id + ']');
        $sfDate.filter('.datepicker_year').val(date.year());
        $sfDate.filter('.datepicker_month').val(date.month()+1);
        $sfDate.filter('.datepicker_day').val(date.date());
        $sfDate.filter('.datepicker_hour').val(date.hour());
        $sfDate.filter('.datepicker_minute').val(date.minute());
    });
});
/***************************** images in mobile *******************************/
if ($(window).width() < 768) $('img.hidden-xs, .hidden-xs img').attr('src', '');
if ($(window).width() < 992) $('img.hidden-sm, .hidden-sm img').attr('src', '');
if ($(window).width() < 1200) $('img.hidden-md, .hidden-md img').attr('src', '');
/******************************** login ***************************************/
$login = $('.dropdown.login');
$login.on('shown.bs.dropdown', function(){
    $(this).find('#login_email').focus();
});
$login.find('form').on('submit', function(){
    $(this).find('button[type="submit"]').button('loading');
});
/****************************** latest news ***********************************/
//open news
$('#latest_news').on('click', 'a.title', function(e) {
    e.preventDefault();
    var $this = $(this);
    var id = $this.attr('rel');
    $('#latest_news_body_'+id).slideToggle();
    $this.toggleClass('unfolded');
});
/***************************** subscription ***********************************/
//send form
$(document).on('submit', '.subscription_form', function(event){
    event.preventDefault();
    var $form = $(this);
    var $button = $form.find('.btn');
    $form.find('.alert').addClass('hidden');
    $button.button('loading');
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        dataType: 'json',
        success: function(data){
            $button.button('reset');
            $form.find('.alert-' + data.result).html(data['message']).removeClass('hidden');
            if (data.result === 'success') $form.find('#subscription_input_email').val('');
        }
    });
});
/**************************** additional fields *******************************/
//subfields
$('[id$=__SUBFORM]').each(function(){
    var $subform = $(this);
    var $masterField = $('#' + $subform.attr('id').replace('__SUBFORM', ''));
    if ($masterField.is(':checkbox')) {
        //trigger on load
        $subform.toggle($masterField.is(':checked'));
        //event
        $masterField.change(function(){
            $subform.slideToggle($masterField.is(':checked'));
        });
    } else if ($masterField.is(':radio')) {
        //trigger on load
        $subform.toggle($masterField.is(':checked'));
        //event
        $('input:radio[name="' + $masterField.attr('name') + '"]').click(function(){
            var $radio = $(this);
            if ($radio.attr('id') === $masterField.attr('id')) {
                $subform.slideDown();
            } else {
                $subform.hide();
            }
        });
    } else if ($masterField.is('select')) {
        //to do
    }
});
/****************************** registration ***********************************/
//repeat password
$('.registration #repeat_password, .forgot-password #repeat_password').on('keyup', function() {
    var $container = $(this).closest('.form-group');
    $container.removeClass('has-error has-success has-feedback')
              .find('#repeat_password_ok, #repeat_password_err').addClass('hidden');
    if ($('#repeat_password').val() !== $('#attendee_password').val()){
        $container.addClass('has-error has-feedback')
                  .find('#repeat_password_err').removeClass('hidden');
    }else{
        $container.addClass('has-success has-feedback')
                  .find('#repeat_password_ok').removeClass('hidden');
    }
});
/***************************** submission ************************************/
//invitation
$('.paper_submit.needs_invitation').on('click', function(e) {
    e.preventDefault();
    $('#paper_invitation_div_' + $(this).attr('rel')).slideToggle();
});
//send form
$('.paper_invitation_form').on('submit', function(e){
    e.preventDefault();
    var $form = $(this);
    var $btn = $form.find('.btn');
    var $err = $form.find('.alert-danger');
    $btn.button('loading');
    $err.addClass('hidden');
    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        data: $form.serialize()
    }).done(function(data){
        data = $.trim(data);
        if (data != 'ok'){
            $err.html(data).removeClass('hidden');
        }else{
            location.href = $form.data('goto');
        }
    }).fail(function(){
        $err.html($err.data('default')).removeClass('hidden');
    }).always(function(){
        $btn.button('reset');
    });
});
//abstract max chars
var $textarea = $('#paper_text');
var $chars = $('#paper_text_chars');
var maxChars = $textarea.data('max_chars');
if (maxChars) {
    var paperTextCountChars = function()
    {
        var left = maxChars - $textarea.val().length;
        if (left >= 0) {
            var text = $chars.data('text_left');
            $chars.html(text.replace(/%num%/i, left));
            $chars.removeClass('bg-danger');
        } else {
            var text = $chars.data('text_exceeded');
            $chars.html(text.replace(/%limit%/i, maxChars).replace(/%used%/i, $textarea.val().length));
            $chars.addClass('bg-danger');
        }
    }
    $textarea.on('input', function(){
        paperTextCountChars();
    });
    paperTextCountChars();
}
//coauthors
var $coauthorsContainer = $('#coauthors_container');
if ($coauthorsContainer.length) {
    
    $coauthorsContainer.data('next_ord', 0);
    var coauthorSetOrder = function() {
        $coauthorsContainer.data('next_ord', 0);
        $coauthorsContainer.find('[id^="coauthor_node_"], #coauthor_author_node').each(function(i){
            var $this = $(this);
            if ($this.attr('id') === 'coauthor_author_node'){
                $this.find('#paper_attendee_ord').val(i);
            }else{
                var idx = $this.attr('id').replace('coauthor_node_','');
                $('#paper_Coauthor_rel_'+idx+'_ord').val(i);
            }
            $coauthorsContainer.data('next_ord', i+1);
        });
    };
    
    //initialize: order coauthors, reassign orders and make sortable
    $coauthorsContainer.find('[id^="coauthor_node_"], #coauthor_author_node').sortElements(function(a, b){
        var idx_a = $(a).attr('id').replace('coauthor_node_','');
        var idx_b = $(b).attr('id').replace('coauthor_node_','');
        var val_a = ($(a).attr('id') == 'coauthor_author_node') ? ($coauthorsContainer.find('#paper_attendee_ord').val()) : ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_a+'_ord').val());
        var val_b = ($(b).attr('id') == 'coauthor_author_node') ? ($coauthorsContainer.find('#paper_attendee_ord').val()) : ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_b+'_ord').val());
        return val_a > val_b ? 1 : -1;
    });
    coauthorSetOrder();
    $coauthorsContainer.sortable({
        items: '[id^="coauthor_node_"], #coauthor_author_node',
        handle:'.handle',
        update: function(event, ui) {
            coauthorSetOrder()
        }
    });
    //edit
    $coauthorsContainer.on('click', '[id^="coauthor_edit_"]', function(event) {
        event.preventDefault();
        var idx = $(this).attr('id').replace('coauthor_edit_','');
        $coauthorsContainer.find('#coauthor_info_'+idx).slideUp();
        $coauthorsContainer.find('#coauthor_form_'+idx).slideDown();
    })
    //delete
    $coauthorsContainer.on('click', '[id^="coauthor_delete_"]', function(event) {
        event.preventDefault();
        var $this = $(this);
        var idx = $this.attr('id').replace('coauthor_delete_','');
        if (confirm($this.data('confirm_text'))){
            $coauthorsContainer.find('#coauthor_node_'+idx).fadeTo('fast', 0, function() {
                $(this).slideUp('slow', function() {
                    $(this).remove();
                    coauthorSetOrder();
                });
            });
        }
    });
    //close
    $coauthorsContainer.on('click', '[id^="coauthor_close_"]', function(event) {
        event.preventDefault();
        var idx = $(this).attr('id').replace('coauthor_close_','');
        //if no values, just delete node
        if ($coauthorsContainer.find('#coauthor_form_'+idx).find('input:text[value!=""]').length == 0){
            $coauthorsContainer.find('#coauthor_form_'+idx).slideUp(function(){
                $coauthorsContainer.find('#coauthor_node_'+idx).remove();
            });
            return;
        }
        if ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_name').val() && $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_lastname').val()) {
            var html = $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_lastname').val() + ', ' + $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_name').val();
            $coauthorsContainer.find('#coauthor_infoname_'+idx).html(html);
        }else{
            $coauthorsContainer.find('#coauthor_infoname_'+idx).html('('+$coauthorsContainer.find('#coauthor_infoname_'+idx).data('error_text')+')');
        }
        $coauthorsContainer.find('#coauthor_info_'+idx).show().fadeTo(0,0);
        $coauthorsContainer.find('#coauthor_form_'+idx).slideUp(function(){
            $coauthorsContainer.find('#coauthor_info_'+idx).fadeTo('slow',1);
        });
    });
    //add
    $coauthorsContainer.find('#coauthor_add').click(function(event) {
        event.preventDefault();
        var countNodes = $coauthorsContainer.data('count_nodes');
        var nextOrd    = $coauthorsContainer.data('next_ord');
        //add node
        var html = $('#coauthor_tpl').html();
        html = $('#coauthor_tpl').html().replace(/\$\$index\$\$/g, countNodes).replace(/__index__/g, countNodes);
        $(this).parent().before(html);
        //assign order
        $coauthorsContainer.find('#paper_Coauthor_rel_'+countNodes+'_ord').val(nextOrd);
        //animate show
        $coauthorsContainer.find('#coauthor_info_'+countNodes+', #coauthor_form_'+countNodes).hide();
        $coauthorsContainer.find('#coauthor_form_'+countNodes).slideDown();
        //update for next
        $coauthorsContainer.data('next_ord', nextOrd+1);
        $coauthorsContainer.data('count_nodes', countNodes+1);
    });
    //check email
    $coauthorsContainer.on('keyup change', '[id^="paper_Coauthor_rel_"][id$="_email"]', function(){
        //abort call in process
        try{ clearTimeout(check_email_timeout); check_email_in_process.abort() }catch(e){ null }
        //new call
        if ($(this).val().length > 5){
            $check_email_context = $(this);
            check_email_timeout = setTimeout(function(){
                check_email_in_process = $.ajax({
                    type: 'POST',
                    url: $check_email_context.data('url_check_email'),
                    data: 'email=' + $check_email_context.val(),
                    dataType: 'json'
                }).done(function(data){
                      var idx = $check_email_context.attr('id').replace('paper_Coauthor_rel_','').replace('_email','');
                      if (data !== false) {
                          $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_email').val(data['email']);
                          $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_name').val(data['name']).hide().fadeIn();
                          $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_lastname').val(data['lastname']).hide().fadeIn();
                          $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_institution').val(data['institution']).hide().fadeIn();
                          $coauthorsContainer.find('#paper_Coauthor_rel_'+idx+'_country').val(data['country']).hide().fadeIn();
                          $coauthorsContainer.find('#coauthor_email_found_'+idx).closest('.form-group').addClass('has-success').delay(2000).removeClass('has-success');
                          $coauthorsContainer.find('#coauthor_email_found_'+idx).show().delay(2000).fadeOut();
                      }
                })
            }, 1000);
        }
    });
    //order alphabetically
    var cleanAccents = function(s){
        var r=s.toLowerCase();
        r = r.replace(new RegExp("\\s", 'g'),"");
        r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
        r = r.replace(new RegExp("æ", 'g'),"ae");
        r = r.replace(new RegExp("ç", 'g'),"c");
        r = r.replace(new RegExp("[èéêë]", 'g'),"e");
        r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
        r = r.replace(new RegExp("ñ", 'g'),"n");                            
        r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
        r = r.replace(new RegExp("œ", 'g'),"oe");
        r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
        r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
        r = r.replace(new RegExp("\\W", 'g'),"");
        return r;
    };
    $('#coauthors_order_abc').click(function(event){
        event.preventDefault();
        $coauthorsContainer.find('[id^="coauthor_node_"], #coauthor_author_node').sortElements(function(a, b){
            var idx_a = $(a).attr('id').replace('coauthor_node_','');
            var idx_b = $(b).attr('id').replace('coauthor_node_','');
            if ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_a+'_lastname').length && $.trim($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_a+'_lastname').val()) === '') return 1;
            if ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_b+'_lastname').length && $.trim($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_b+'_lastname').val()) === '') return -1;
            var val_a = ($(a).attr('id') === 'coauthor_author_node') ? ($('#coauthor_author_name').html()) : ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_a+'_lastname').val()+', '+$coauthorsContainer.find('#paper_Coauthor_rel_'+idx_a+'_name').val());
            var val_b = ($(b).attr('id') === 'coauthor_author_node') ? ($('#coauthor_author_name').html()) : ($coauthorsContainer.find('#paper_Coauthor_rel_'+idx_b+'_lastname').val()+', '+$coauthorsContainer.find('#paper_Coauthor_rel_'+idx_b+'_name').val());
            return cleanAccents(val_a.toLowerCase()) > cleanAccents(val_b.toLowerCase()) ? 1 : -1;
        });
        coauthorSetOrder();
    });
}
/***************************** invited sessions ********************************/
//invited sessions max chars
var $invTextarea = $('#invited_session_text');
var $invChars = $('#invited_session_text_chars');
var invMaxChars = $invTextarea.data('max_chars');
if (invMaxChars) {
    var invitedsessionTextCountChars = function()
    {
        var left = invMaxChars - $invTextarea.val().length;
        if (left >= 0) {
            var text = $invChars.data('text_left');
            $invChars.html(text.replace(/%num%/i, left));
            $invChars.removeClass('bg-danger');
        } else {
            var text = $invChars.data('text_exceeded');
            $invChars.html(text.replace(/%limit%/i, invMaxChars).replace(/%used%/i, $invTextarea.val().length));
            $invChars.addClass('bg-danger');
        }
    }
    $invTextarea.on('input', function(){
        invitedsessionTextCountChars();
    });
    invitedsessionTextCountChars();
}
/******************************* papers ****************************************/
//see more
$('[id^="paper_link_see_more__"]').click(function(event){
    event.preventDefault();
    var idx = $(this).attr('id').split('__')[1];
    $('#paper_text_see_more__'+idx).hide();
    $('#paper_text_complete__'+idx).slideDown();
})
//TODO MC: jquery para asignar popup al enlace del mode=reduced
/******************************* sessions *************************************/
$('.session_title').click(function(event) {
    event.preventDefault();
    var $this = $(this);
    var $context = $this.parent();
    if (!$context.find('ul').is(':visible')){
        $context.find('.loading').show();
        $.ajax({
            url: $this.data('url_papers'),
            data: 'id=' + $this.data('session_id'),
            type: 'POST'
        }).done(function(data){
            $context.find('ul').html(data).slideDown();
        }).always(function(){
            $context.find('.loading').hide();
        })
    }else{
        $context.find('ul').slideUp();
    }
})
/****************************** my information ********************************/
$('#myinformation_password_edit').click(function(event){
    event.preventDefault();
    var $this = $(this);
    var $changing = $('#attendee_changing_password');
    var $container = $('#myinformation_password');
    
    $container.slideToggle();
    
    if ($changing.val() === '0'){
        $changing.val('1');
        $this.html($this.data('notchange_text'));
    }else{
        $changing.val('0');
        $this.html($this.data('change_text'));
    }
});
//repeat password
$('.my-information #repeat_password').on('keyup', function() {
    var $container = $(this).closest('.form-group');
    $container.removeClass('has-error has-success has-feedback')
              .find('#repeat_password_ok, #repeat_password_err').addClass('hidden');
    if ($('#repeat_password').val() !== $('#attendee_new_password').val()){
        $container.addClass('has-error has-feedback')
                  .find('#repeat_password_err').removeClass('hidden');
    }else{
        $container.addClass('has-success has-feedback')
                  .find('#repeat_password_ok').removeClass('hidden');
    }
});
/******************************** enrollment **********************************/
var $enrollment = $('.enrollment');
if ($enrollment.length) {
    
    if ($('#price_summary_total').length) {
        //funcion to calculate and display prices
        calculate_price_summary = function()
        {
            var price_summary_subtotal = 0;
            var price_summary_vat = 0;
            var price_summary_total = 0;
            $enrollment.find('input[id^="enrollment_grp_"], input[id^="enrollment_fee_"]').filter(':checked').each(function(){
                var $fee = $(this);
                var $multipliers = $enrollment.find('[data-fee_multiplier][rel="' + $fee.attr('id') + '"]');
                var multiplier = 1;
                $multipliers.each(function(){
                    var $subfee = $(this);
                    multiplier *= $subfee.is('select') ? $subfee.find(':selected').text() : $subfee.val();
                });
                price_summary_subtotal += enrollment.fee_prices[$fee.val()] * multiplier;
            });
            price_summary_vat = price_summary_subtotal * enrollment.vat / 100;
            price_summary_total = price_summary_subtotal + price_summary_vat;
            //display
            $enrollment.find('#price_summary_subtotal').hide().html(price_summary_subtotal).formatNumber({format:"#,###.00", locale: LOCALE }).fadeIn();
            $enrollment.find('#price_summary_vat').hide().html(price_summary_vat).formatNumber({format:"#,###.00", locale: LOCALE }).fadeIn();
            $enrollment.find('#price_summary_total').hide().html(price_summary_total).formatNumber({format:"#,###.00", locale: LOCALE }).fadeIn();
        }
        //event and display
        $enrollment.find('input[id^="enrollment_grp_"], input[id^="enrollment_fee_"], [data-fee_multiplier]').change(function(){
            calculate_price_summary();
        });
        //trigger when loading
        calculate_price_summary();
    }
    //in case of incomplete payment
    $enrollment.find('#enrollment_start_again').click(function(event){
        event.preventDefault();
        $enrollment.find('#enrollment_container').slideDown();
    });
    
    //go to payment
    $('#enrollment_button_checkout').click(function(){
        $('#enrollment_buttons').hide();
        $('#payment_method_content').slideDown();
    });
    
    //go to payment method
    $('[id^="button_payment_"]').click(function(event){
        event.preventDefault();
        var $btn = $(this);
        var psp_id = $btn.attr('id').replace('button_payment_','');
        $('#hidden_payment_psp_id').val(psp_id);
        //send form
        $btn.button('loading');
        $.ajax({
            type: $('#form_payment_gateway').attr('method'),
            url: $('#form_payment_gateway').attr('action'),
            data: $('#form_payment_gateway').serialize()
        }).done(function(data) {
            $('#form_payment_newform').html(data);
            //send new form
            $('#form_payment_redirect').submit();
        }).fail(function() {
            $('#error_payment').show();
            $btn.button('reset');
        })
    })
}
/************************** schedule *****************************/
$('.schedule a.title').click(function(event){
    event.preventDefault();
    $(this).parent().siblings('.subform').slideToggle();
})
$('.schedule h3 a').click(function(event){
    event.preventDefault();
    $(this).parent().next('ul.sessions').slideToggle();
})
/************************** authors ******************************/
//papers of authors
$('.authors').on('click', '.authors_content > li > a', function(event){
    event.preventDefault();
    var $this = $(this);
    var $content = $('.authors .authors_content');
    var $loading = $this.siblings('.loading');
    var $subform = $this.siblings('.subform');
    
    if ($subform.is(':visible')){
        $subform.slideUp();
    }else{
        $loading.show();
        $.ajax({
            url: $content.data('urlpapers'),
            type: 'POST',
            data: 'type=' + $this.data('type') + '&id=' + $this.data('id') + '&entity=' + $this.data('entity')
        }).always(function(){
            $loading.hide();
        }).done(function(data){
            $subform.html(data).slideDown();
        });
    }
});
//hijack pagination
$('.authors').on('click', '.nav a', function(event){
    event.preventDefault();
    var $this = $(this);
    var $authors = $('.authors');
    var $content = $authors.find('.authors_content');
    $content.html('
')
    $.ajax({
        url: $(this).attr('href')
    }).done(function(data){
        $content.html(data);
        $authors.find('.nav .active').removeClass('active');
        $this.closest('li').addClass('active');
    });
});
/************************ gallery ***************************/
var $gallery = $('.gallery');
var $galleryModal = $gallery.find('#modal-photo-preview');
var $countBadge = $gallery.find('.panel .panel-heading .badge');
$galleryModal.on('show.bs.modal', function (event) {
    var $thumb = $(event.relatedTarget);
    var $modal = $(this);
    var $image = $modal.find('.modal-body img');
    var $status = $modal.find('.modal-header h4 small');
    var $delete = $modal.find('.modal-footer button.delete');
    $image.attr('src', $thumb.data('image'));
    $status.html($thumb.data('status')).addClass($thumb.data('status-class'));
    $delete.siblings('input[name="id"]').val($thumb.data('id'));
});
$galleryModal.find('button.delete').on('click', function(e){
    e.preventDefault();
    var $button = $(this);
    $button.button('loading');
    var $form = $button.closest('form');
    var id = $form.find('input[name="id"]').val();
    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        data: $form.serialize()
    }).done(function(data) {
        //remove thumb
        var $thumb = $gallery.find('.photo-mine[data-id="'+id+'"]');
        $thumb.remove();
        //count
        $countBadge.html(parseInt($countBadge.html()) - 1);
        //close modal
        $galleryModal.modal('hide');
    }).always(function() {
        $button.button('reset');
    });
});
//upload
var canUpload = function() {
    //input file supported
    var elem = document.createElement('input');
    elem.type = 'file';
    if (elem.disabled) return false;
    //canvas supported
    var elem = document.createElement('canvas');
    if (!(elem.getContext && elem.getContext('2d'))) return false;
    //else
    return true;
}
if (canUpload()) {
    var $btnUpload = $gallery.find('.photo-mine-upload');
    var $formUpload = $btnUpload.find('form');
    var $inputFile = $gallery.find('input[type="file"]');
    var $base64File = $formUpload.find('#gallery_photo_base64_file');
    var $uploadError = $gallery.find('.alert-danger');
    $btnUpload.on('click', function(e) {
        e.preventDefault();
        $inputFile.click();
    });
    $inputFile.on('change', function(e){
        loadImage(
            e.target.files[0],
            function (canvas) {
                if (canvas.type === 'error') {
                    $uploadError.html($uploadError.data('error-type')).removeClass('hide');
                    return;
                } else {
                    $uploadError.addClass('hide');
                }
                $base64File.val(canvas.toDataURL('image/jpeg', 0.8));
                $btnUpload.find('.glyphicon').addClass('hide');
                $btnUpload.find('.loading').removeClass('hide');
                $.ajax({
                    'url' : $formUpload.attr('action'),
                    'type': $formUpload.attr('method'),
                    'data': $formUpload.serialize()
                }).done(function(response) {
                    $btnUpload.before(response);
                    //count
                    $countBadge.html(parseInt($countBadge.html()) + 1);
                }).fail(function(jqXHR) {
                    $uploadError.html(jqXHR.responseText).removeClass('hide');
                }).always(function() {
                    $btnUpload.find('.glyphicon').removeClass('hide');
                    $btnUpload.find('.loading').addClass('hide');
                    //reset
                    $base64File.val('');
                    $inputFile.wrap('