$(document).ready(function() {
  language.add(languageForJs);
  language.load('common/filemanager');

  (function() {
    var special = jQuery.event.special,
      uid1 = 'D' + +new Date(),
      uid2 = 'D' + (+new Date() + 1);

    special.scrollstart = {
      setup: function() {
        var timer,
          handler = function(evt) {
            var _self = this,
              _args = arguments;

            if (timer) {
              clearTimeout(timer);
            } else {
              evt.type = 'scrollstart';
              jQuery.event.handle.apply(_self, _args);
            }

            timer = setTimeout(function() {
              timer = null;
            }, special.scrollstop.latency);
          };

        jQuery(this)
          .bind('scroll', handler)
          .data(uid1, handler);
      },
      teardown: function() {
        jQuery(this).unbind('scroll', jQuery(this).data(uid1));
      },
    };

    special.scrollstop = {
      latency: 300,
      setup: function() {
        var timer,
          handler = function(evt) {
            var _self = this,
              _args = arguments;

            if (timer) {
              clearTimeout(timer);
            }

            timer = setTimeout(function() {
              timer = null;
              evt.type = 'scrollstop';
              jQuery.event.handle.apply(_self, _args);
            }, special.scrollstop.latency);
          };

        jQuery(this)
          .bind('scroll', handler)
          .data(uid2, handler);
      },
      teardown: function() {
        jQuery(this).unbind('scroll', jQuery(this).data(uid2));
      },
    };
  })();

  function notificationImage(title, message) {
    $('#notification').remove();

    var html = '<div id="notification">';
    html += '<div id="notification-container">';
    html += '<span id="notification-title">' + title + '</span>';
    html += '<span id="notification-message">' + message + '</span>';
    html += '</div>';
    html += '</div>';

    $('body').append(html);

    $('#notification').css({
      position: 'fixed',
      width: '100vw',
      height: '100vh',
      cursor: 'pointer',
      top: '0',
      left: '0',
      background: 'rgba(0,0,0,.3)',
    });

    $('#notification-container').css({
      position: 'fixed',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      background: '#fff',
      padding: '24px',
      'box-shadow': '0px 16px 32px rgba(0,0,0,0.5)',
      'font-family': 'sans-serif',
      width: '200px',
      'border-left': '4px solid #d9534f',
    });

    $('#notification-title').css({
      'font-size': '16px',
      'font-weight': 'bold',
      display: 'block',
      'margin-bottom': '8px',
      color: '#222',
    });

    $('#notification-message').css({
      'font-size': '14px',
      color: '#777',
    });

    $('#notification').on('click', function(event) {
      event.preventDefault();
      $(this).remove();
    });
  }

  $('#column-right').bind('scrollstop', function() {
    $('#column-right a').each(function(index, element) {
      var height = $('#column-right').height();
      var offset = $(element).offset();

      if (
        offset.top > 0 &&
        offset.top < height &&
        $(element)
          .find('img')
          .attr('src') == url_link.no_image
      ) {
        $.ajax({
          url:
            url_link.list +
            '&file=' +
            encodeURIComponent(
              'data/' +
                $(element)
                  .find("input[name='file']")
                  .attr('value')
            ),
          dataType: 'html',
          success: function(html) {
            $(element)
              .find('img')
              .replaceWith('<img src="' + html + '" alt="" title="" />');
          },
        });
      }
    });
  });

  $('#column-left').tree({
    data: {
      type: 'json',
      async: true,
      opts: {
        method: 'post',
        url: url_link.directory,
      },
    },
    selected: 'top',
    ui: {
      theme_name: 'classic',
      animation: 700,
    },
    types: {
      default: {
        clickable: true,
        creatable: false,
        renameable: false,
        deletable: false,
        draggable: false,
        max_children: -1,
        max_depth: -1,
        valid_children: 'all',
      },
    },
    callback: {
      beforedata: function(NODE, TREE_OBJ) {
        if (NODE == false) {
          TREE_OBJ.settings.data.opts.static = [
            {
              data: url_link.folder,
              attributes: {
                id: 'top',
                directory: '',
              },
              state: 'closed',
            },
          ];

          return { directory: '' };
        } else {
          TREE_OBJ.settings.data.opts.static = false;

          return { directory: $(NODE).attr('directory') };
        }
      },
      onselect: function(NODE, TREE_OBJ) {
        $.ajax({
          url: url_link.files,
          type: 'post',
          data: 'directory=' + encodeURIComponent($(NODE).attr('directory')),
          dataType: 'json',
          success: function(json) {
            html = '<div>';

            if (json) {
              if (json) {
                for (i = 0; i < json.length; i++) {
                  html +=
                    '<a class="files-img"><img src="' +
                    url_link.no_image +
                    '" alt="" title="" /><br />' +
                    (json[i]['filename'].length > 15 ? json[i]['filename'].substr(0, 15) + '..' : json[i]['filename']) +
                    '<br />' +
                    json[i]['size'] +
                    '<input type="hidden" name="file" data-linkdireto="' +
                    json[i]['linkdireto'] +
                    '" value="' +
                    json[i]['file'] +
                    '" /></a>';
                }
              }
            }

            html += '</div>';

            html += '<script>';
            html += '$(".copiar").off();';
            html += '$(".copiar").on("click", function() {';
            html += 'if ($(this).prev(".linkdireto").val()) {';
            html += '$(this).prev(".linkdireto").select();';
            html += 'try {';
            html += 'var successful = document.execCommand("copy");';
            html += '$(this).prev(".linkdireto").blur();';
            html += 'var msg = successful ? "URL Copiada!" : "Erro: A URL não foi copiada";';
            html += 'alert(msg);';
            html += '} catch (err) {';
            html += 'alert("Erro: A URL não foi copiada, tente usar Crtl + C.");';
            html += '}';
            html += '} else {';
            html += 'alert("Primeiro selecione uma imagem!");';
            html += '}';
            html += '});';

            html += '$(".files-img").click(function(){';
            html += '$(".linkdireto").val($(this).find("input").data("linkdireto"));';
            html += '});';

            html += '$("#column-left").click(function(){';
            html += '$(".linkdireto").val("");';
            html += '});';

            html += '$(".linkdireto").click(function(){';
            html += '$(this).select();';
            html += '});';
            html += '</script>';

            $('#column-right').html(html);
            $('#column-right').trigger('scrollstop');
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      },
    },
  });

  $('#column-right a').live('click', function() {
    if ($(this).attr('class') == 'selected') {
      $(this).removeAttr('class');
    } else {
      $('#column-right a').removeAttr('class');

      $(this).attr('class', 'selected');
    }
  });

  $('#column-right a').live('dblclick', function() {
    var $type = $('.js-type-image').data('type-image'),
      $path = $(this)
        .find("input[name='file']")
        .attr('value'),
      $srcthumb = $(this)
        .find('img')
        .attr('src');

    switch ($type) {
      case Type_ImageUpload.Tp_Danfe:
        $image = new Image();
        $image.src = $('.linkdireto').val();
        $image.onload = function() {
          var $height = this.height,
            $width = this.width,
            $imgExt = $(this)
              .attr('src')
              .split('.')
              .pop(),
            $extPermitidas = ['jpg', 'png'];

          if ($width > 250 || $height > 250) {
            notificationImage('Imagem muito grande', 'A imagem deve ter no máximo 250px por 250px.');
            return false;
          } else if ($width !== $height) {
            notificationImage('Proporção inválida', 'A imagem deve ser quadrada.');
            return false;
          } else if ($extPermitidas.indexOf($imgExt) == -1) {
            notificationImage('Imagem inválida', 'Extensão da imagem não suportada.');
            return false;
          } else {
            parent.$('#' + field).attr('value', 'data/' + $path);
            closeDialog($srcthumb);
          }
        };
        break;
      case Type_ImageUpload.Tp_WireCardLogoBoleto:
        $image = new Image();
        $image.src = $('.linkdireto').val();
        $image.onload = function() {
          var $height = this.height,
            $width = this.width,
            $imgExt = $(this)
              .attr('src')
              .split('.')
              .pop(),
            $extPermitidas = ['jpg', 'png'];

          if ($width > 80 || $height > 25) {
            notificationImage('Imagem muito grande', 'A imagem deve ter no máximo 80px por 25px.');
            return false;
          } else if ($extPermitidas.indexOf($imgExt) == -1) {
            notificationImage('Imagem inválida', 'Extensão da imagem não suportada.');
            return false;
          } else {
            parent.$('#' + field).attr('value', 'data/' + $path);
            closeDialog($srcthumb);
          }
        };
        break;
      case Type_ImageUpload.Tp_Icon:
        $image = new Image();
        $image.src = $('.linkdireto').val();
        $image.onload = function() {
          var $height = this.height,
            $width = this.width,
            $imgExt = $(this)
              .attr('src')
              .split('.')
              .pop(),
            $extPermitidas = ['png', 'jpg'];

          if ($width > 32 || $height > 32) {
            notificationImage('Imagem muito grande', 'A imagem deve ter no máximo 32px por 32px.');
            return false;
          } else if ($width !== $height) {
            notificationImage('Proporção inválida', 'A imagem deve ser quadrada.');
            return false;
          } else if ($extPermitidas.indexOf($imgExt) == -1) {
            notificationImage('Imagem inválida', 'Extensão da imagem não suportada.');
            return false;
          } else {
            parent.$('#' + field).attr('value', 'data/' + $path);
            closeDialog($srcthumb);
          }
        };
        break;
      default:
        parent.$('#' + field).attr(
          'value',
          'data/' +
            $(this)
              .find("input[name='file']")
              .attr('value')
        );
        closeDialog($srcthumb);
        break;
    }
  });

  function closeDialog($srcthumb) {
    if (parent.$('#' + field)[0]) {
      parent.$('#' + field)[0].dataset.srcthumb = $srcthumb;
    }
    parent.$('#dialog').dialog('close');
    parent.$('#dialog').remove();
  }

  $('#create').bind('click', function() {
    var tree = $.tree.focused();

    if (tree.selected) {
      $('#dialog').remove();

      html = '<div id="dialog">';
      html +=
        language.get('entry_folder') +
        ' <input type="text" name="name" value="" /> <input type="button" value="' +
        language.get('button_submit') +
        '" />';
      html += '</div>';

      $('#column-right').prepend(html);

      $('#dialog').dialog({
        title: language.get('button_folder'),
        resizable: false,
      });

      $("#dialog input[type='button']").bind('click', function() {
        $.ajax({
          url: url_link.create,
          type: 'post',
          data:
            'directory=' +
            encodeURIComponent($(tree.selected).attr('directory')) +
            '&name=' +
            encodeURIComponent($("#dialog input[name='name']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              tree.refresh(tree.selected);

              alert(json.success);
            } else {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      });
    } else {
      alert(language.get('error_directory'));
    }
  });

  $('#delete').bind('click', function() {
    path = $('#column-right a.selected')
      .find("input[name='file']")
      .attr('value');

    if (path) {
      $.ajax({
        url: url_link.delete,
        type: 'post',
        data: 'path=' + encodeURIComponent(path),
        dataType: 'json',
        success: function(json) {
          if (json.success) {
            var tree = $.tree.focused();

            tree.select_branch(tree.selected);

            alert(json.success);
          }

          if (json.error) {
            alert(json.error);
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        },
      });
    } else {
      var tree = $.tree.focused();

      if (tree.selected) {
        $.ajax({
          url: url_link.delete,
          type: 'post',
          data: 'path=' + encodeURIComponent($(tree.selected).attr('directory')),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              tree.select_branch(tree.parent(tree.selected));

              tree.refresh(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      } else {
        alert(language.get('error_select'));
      }
    }
  });

  $('#move').bind('click', function() {
    $('#dialog').remove();

    html = '<div id="dialog">';
    html +=
      language.get('entry_move') +
      ' <select name="to"></select> <input type="button" value="' +
      language.get('button_submit') +
      '" />';
    html += '</div>';

    $('#column-right').prepend(html);

    $('#dialog').dialog({
      title: language.get('button_move'),
      resizable: false,
    });

    $("#dialog select[name='to']").load(url_link.folders);

    $("#dialog input[type='button']").bind('click', function() {
      path = $('#column-right a.selected')
        .find("input[name='file']")
        .attr('value');

      if (path) {
        $.ajax({
          url: url_link.move,
          type: 'post',
          data: 'from=' + encodeURIComponent(path) + '&to=' + encodeURIComponent($("#dialog select[name='to']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              var tree = $.tree.focused();

              tree.select_branch(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      } else {
        var tree = $.tree.focused();

        $.ajax({
          url: url_link.move,
          type: 'post',
          data:
            'from=' +
            encodeURIComponent($(tree.selected).attr('directory')) +
            '&to=' +
            encodeURIComponent($("#dialog select[name='to']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              tree.select_branch('#top');

              tree.refresh(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      }
    });
  });

  $('#copy').bind('click', function() {
    $('#dialog').remove();

    html = '<div id="dialog">';
    html +=
      language.get('entry_copy') +
      ' <input type="text" name="name" value="" /> <input type="button" value="' +
      language.get('button_submit') +
      '" />';
    html += '</div>';

    $('#column-right').prepend(html);

    $('#dialog').dialog({
      title: language.get('button_copy'),
      resizable: false,
    });

    $("#dialog select[name='to']").load(url_link.folders);

    $("#dialog input[type='button']").bind('click', function() {
      path = $('#column-right a.selected')
        .find("input[name='file']")
        .attr('value');

      if (path) {
        $.ajax({
          url: url_link.copy,
          type: 'post',
          data:
            'path=' + encodeURIComponent(path) + '&name=' + encodeURIComponent($("#dialog input[name='name']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              var tree = $.tree.focused();

              tree.select_branch(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      } else {
        var tree = $.tree.focused();

        $.ajax({
          url: url_link.copy,
          type: 'post',
          data:
            'path=' +
            encodeURIComponent($(tree.selected).attr('directory')) +
            '&name=' +
            encodeURIComponent($("#dialog input[name='name']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              tree.select_branch(tree.parent(tree.selected));

              tree.refresh(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      }
    });
  });

  $('#rename').bind('click', function() {
    $('#dialog').remove();

    html = '<div id="dialog">';
    html +=
      language.get('entry_rename') +
      ' <input type="text" name="name" value="" /> <input type="button" value="' +
      language.get('button_submit') +
      '" />';
    html += '</div>';

    $('#column-right').prepend(html);

    $('#dialog').dialog({
      title: language.get('button_rename'),
      resizable: false,
    });

    $("#dialog input[type='button']").bind('click', function() {
      path = $('#column-right a.selected')
        .find("input[name='file']")
        .attr('value');

      if (path) {
        $.ajax({
          url: url_link.rename,
          type: 'post',
          data:
            'path=' + encodeURIComponent(path) + '&name=' + encodeURIComponent($("#dialog input[name='name']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              var tree = $.tree.focused();

              tree.select_branch(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      } else {
        var tree = $.tree.focused();

        $.ajax({
          url: url_link.rename,
          type: 'post',
          data:
            'path=' +
            encodeURIComponent($(tree.selected).attr('directory')) +
            '&name=' +
            encodeURIComponent($("#dialog input[name='name']").val()),
          dataType: 'json',
          success: function(json) {
            if (json.success) {
              $('#dialog').remove();

              tree.select_branch(tree.parent(tree.selected));

              tree.refresh(tree.selected);

              alert(json.success);
            }

            if (json.error) {
              alert(json.error);
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
        });
      }
    });
  });

  new AjaxUpload('#upload', {
    action: url_link.upload,
    name: 'file',
    autoSubmit: false,
    responseType: 'json',
    onChange: function(file, extension) {
      var tree = $.tree.focused();
      var size = window.size;
      if (tree.selected) {
        if (size) {
          this.setData({
            directory: $(tree.selected).attr('directory'),
            size: 500000,
          });
        } else {
          this.setData({ directory: $(tree.selected).attr('directory') });
        }
      } else {
        this.setData({ directory: '' });
      }

      this.submit();
    },
    onSubmit: function(file, extension) {
      $('#upload').append('<img src="../assets/img/loading-black.svg" class="loading" style="padding-left: 5px;" />');
    },
    onComplete: function(file, json) {
      if (json.success) {
        var tree = $.tree.focused();

        tree.select_branch(tree.selected);

        alert(json.success);
      }

      if (json.error) {
        alert(json.error);
      }

      $('.loading').remove();
    },
  });

  $('#refresh').bind('click', function() {
    var tree = $.tree.focused();

    tree.refresh(tree.selected);
  });
});
