$(function() {
//  alert("hi");

  var selectHTML = $('#id_category').html();
  $('#id_category').children().eq(0).text("All");
  $('#moveSelectedSelect').html(selectHTML);

  $('#submitFilter').click(function(e) {
    e.preventDefault();
    $('#firstPage').click();
  });

  $('#filterForm').submit(function(e) {
    e.preventDefault();
    var formData = $(this).serializeArray();
    $('#submitFilter').val("Loading...").attr("disabled", "disabled");
    $('#pageData').hide();
    $('#loadingPage').show();
    $('#pageBtnsWrapper').hide();
    $('#previewPane').empty();
    $.post("/files/json_list", formData, function(data) {
      $('#submitFilter').val(" Find ").removeAttr("disabled");
      $('#loadingPage').hide();
      $('#pageData').show();
      $('#pageBtnsWrapper').show();
//      MAAKICHUT = response;
      var files = data.files;
//      console.log(files);
      $('#fileList').empty();
      $('#noOfPages').text(data.noOfPages);
      $('#noOfResults').text(data.noOfResults);
      $('#currentPageNo').text(data.currentPage);
      for (var i=0; i<files.length; i++) {
//        console.log(files[i]);
        var $file = getJQ(files[i]);
        $('#fileList').append($file);
      }
    }, "json");
  });

  $('#firstPage').click(function() {
    $('#page_no').val('1');
    $('#filterForm').submit();
  });

  $('#lastPage').click(function() {
    var last_page = $('#noOfPages').text();
    $('#page_no').val(last_page);
    $('#filterForm').submit();
  });

  $('#filterForm').submit();

  $('#prevBtn').click(function() {
    var $page_no = $('#page_no');
    var currPage = parseInt($page_no.val());
    if (currPage > 1) {
      $page_no.val(currPage - 1);
      $('#filterForm').submit();
    }
  });

  $('#nextBtn').click(function() {
    var $page_no = $('#page_no');
    var currPage = parseInt($page_no.val());
    $page_no.val(currPage + 1);
    $('#filterForm').submit();
  });

  $('#deleteSelectedBtn').click(function(e) {
    e.preventDefault();
    var $this = $(this);
    $this.attr("disabled", "disabled");
    var ids = getSelectedIds();
    if (!confirm("Are you sure you want to delete " + ids.length + " items?")) {
      return false;
    }
    var url = "/files/deleteFiles/";
    var params = {'ids': JSON.stringify(ids)};
    $.post(url, params, function(response) {
      if (response.status == 'fail') {
        alert(response.error);
      }
      $this.removeAttr("disabled");
      $('#filterForm').submit();
    });
  });

  $('#moveSelectedBtn').click(function(e) {
    e.preventDefault();
    var $this = $(this);
    $this.attr("disabled", "disabled");
    var ids = getSelectedIds();
    var url = "/files/moveFiles/";
    if (!confirm("Are you sure you wish to move " + ids.length + " items?")) {
      return false;
    }    
    var study_id = $('#moveSelectedSelect').val();
    var params = {
      'ids': JSON.stringify(ids),
      'study': study_id
    }

    $.post(url, params, function(response) {
      if (response.status == 'fail') {
        alert(response.error);
      }
      $this.removeAttr("disabled");
      $('#filterForm').submit();
    }, "json");
  });

  $(document).keydown(function(e) {
    var k = e.keyCode;
    if (k==40) {
      e.preventDefault();
      moveListDown();
    }
    if (k==38) {
      e.preventDefault();
      moveListUp();
    } 
  });

  $(window).resize(function() {
    var minuser = 320;
    var winHeight = $(window).height();
    var listHeight = winHeight - minuser;
    $('#fileList').css("height", listHeight + "px");
  });

  $(window).resize();
});

function getJQ(f) {
  var jq = getListElement(f);
//  var jq = $("<div />").data("data", f).addClass("fileItem").text(f.type + ": " + f.title);
  jq.click(function() {
    var $this = $(this);
    $('.selectedItem').removeClass("selectedItem");
    $this.addClass("selectedItem");
    var d = $this.data("data");
    var $pane = $('<div />').addClass("previewPane");
    var $previewObj = $('<div />').addClass("previewObject").appendTo($pane);
    var html = '';
    switch (d.type) {
      case "image":
        html += "<img width='400' src='" + d.thumbnail + "' />";
        break;
      case "video":
        html += "<video controls='controls' width='400' src='" + d.url + "' />";
        break;
      case "audio":
        html += "<audio controls='controls' width='400' src='" + d.url + "' />";
        break;
      default:
        html += "";
        break;    
    };
    html += "<br />";
    html += "<a href='" + d.url + "' target='_blank'>View Original</a>"; 
    $previewObj.html(html);
    $itemForm = getItemForm(f);
    $itemForm.appendTo($pane);
    $('#previewPane').empty();
    $('#previewPane').append($pane);
  });
  return jq;
}

function getItemForm(f) {
  var $form = $('<div />').addClass("itemForm");
  var $leftCol = $('<div />').addClass("leftCol").appendTo($form);
  var $title = $('<p />').addClass("editTitle").appendTo($leftCol);
  var $titleLabel = $('<span />').addClass("itemFormLabel").addClass("titleLabel").text("Title").appendTo($title);
  var $titleInput = $('<input />').addClass("itemTitle").val(f.title).appendTo($title);



  if (f.can_edit) {
    var $pvt = $('<p />').addClass("editPrivate").appendTo($leftCol);
    var $privateLabel = $('<span />').addClass("pvtLabel").text("Private ").appendTo($pvt);
    var $pvtCheckbox = $('<input />').attr("type", "checkbox").addClass("privateCheck").attr("checked", f.is_private).appendTo($pvt);
    $pvtCheckbox.change(function() {
      var checked = $(this).is(":checked");
      if (checked) {
        var url = "/files/makePrivate/";
      } else {
        var url = "/files/makePublic/";
      }
      var item = $('.selectedItem')
      var f = item.data("data");
      f.is_private = checked;
      item.data("data", f);
      var parent = $(this).parents(".itemForm");
      var id = parent.find(".itemId").val();
      var params = {'id': id}
      $.post(url, params, function(response) {
        if (response.status == 'fail') {
          alert(response.error);
        }
      }, "json");
    });
  }
  var $rightCol = $("<div />").addClass("rightCol").appendTo($form);
  var $desc = $("<p />").addClass("editDescription").appendTo($rightCol);
  var $descriptionLabel = $('<span />').addClass("itemFormLabel").addClass("descriptionLabel").text("Description").appendTo($desc);
  var $descriptionInput = $('<textarea />').addClass("itemDescription").val(f.description).appendTo($desc);
  var $hiddenInput = $('<input />').addClass("itemId").attr("type", "hidden").val(f.id).appendTo($desc);
  var $submitP = $('<p />').addClass("submitInput").appendTo($rightCol);
  var $submit = $('<input />').addClass("submitItem").attr("type", "submit").val("Submit").appendTo($submitP);
  var $submitStatus = $('<span />').addClass("submitStatus").appendTo($submitP);
  $submit.click(function(e) {
    if ($(this).attr("disabled")) {
//      console.log($(this).attr("disabled"));
      return false;
    }
    var url = "/files/editFile/";
    var parent = $(this).parents('.itemForm');
    $('.submitStatus').text("Submitting...");
    $('.submitItem').attr("disabled", "disabled");
    var params = {
      'id': parent.find('.itemId').val(),
      'title': parent.find('.itemTitle').val(),
      'description': parent.find('.itemDescription').val()
    }
    $.post(url, params, function(response) {
      $('.submitStatus').text('Saved');
      $('.submitItem').removeAttr("disabled");
    }, "json");
  });
  if (!f.can_edit) {
    $submit.attr("disabled", "disabled");
  }
  return $form; 
}

function getListElement(f) {
//  console.log(f);
  var $item = $('<div />').addClass("fileItem").data("data", f);
  var $checkbox = $('<input />').attr("type", "checkbox").addClass("fileCheckbox").appendTo($item);
  var $icon = $('<img />').addClass("fileIcon").attr("src", f.thumb).appendTo($item);
  var study_txt = joinStudies(f.studies);
  var $study = $('<span />').addClass("fileStudy").text(study_txt + ": ").appendTo($item);
  var $title = $('<span />').addClass("fileTitle").text(f.title).appendTo($item);  
  return $item;
}

function joinStudies(studies) {
  var arr = [];
  for (var i=0; i<studies.length; i++) {
    arr.push(studies[i].name);
  }
  return arr.join(", ");
}

function getSelectedIds() {
  var ids = [];
  $('.fileItem').each(function() {
    var $this = $(this);
    var checked = $this.find(".fileCheckbox").is(":checked");
    if (checked) {
      var id = $this.data("data").id;
      ids.push(id);
    }
  });
  return ids;
}

function moveListDown() {
  var currentIndex = $('.selectedItem').index(".fileItem");
  if (currentIndex == $('.fileItem').length) {
    return;
  }
  $('.fileItem').eq(currentIndex + 1).click();  
}

function moveListUp() {
  var currentIndex = $('.selectedItem').index(".fileItem");
  if (currentIndex == 0) {
    return;
  }
  $('.fileItem').eq(currentIndex - 1).click();    
}
