var file_selected = false;

$(function(){
  // track characters on keyup
  if ($("#upload_form").length > 0) {
    $("#upload_description").keyup(function(event){
      left = 140 - $("#upload_description").attr("value").length;
      if (left == 0){left = "0";}
      if (left < 0) {$("#chars-left").addClass("negative");}
      else {$("#chars-left").removeClass("negative");}
      $("#chars-left").html(left);
    });

    // disabling non js form elements for file upload
    $("#upload_here").show();
    $("#submit").disable();
    $("#upload_image").hide();
    
    // send the form via ajax
    $("#upload_form").ajaxForm(
      {
       target: "#results",
       url: "/file-repository/ajax_upload",
       beforeSubmit: validate_form,
       success: success_and_reset
      }
    );

    // upload just the file via ajax
    var file_upload = new AjaxUpload('#upload_here', 
      {
        action: 'http://assets.mediarecover.com',
        name: 'file',
        autoSubmit: true,
        onSubmit: function(file, extension){
          // ajax call and return json object with new settings
        
          $("#upload_here").hide();
          $.ajax({
            url: "/file-repository/new_upload",
            data: {file: file},
            async: false,
            dataType: "json",
            success: function(data, textstatus) {
              file_upload._settings.data = {
                key: data['key'],
                AWSAccessKeyId: $("#AWSAccessKeyId").attr('value'),
                acl: "public-read",
                policy: data['policy'],
                signature: data['signature'],
                success_action_redirect: "http://www.mediarecover.com"
              }
             $("#file_id").attr('value', data['id']); 
             console.log(data['id']);


          $("#spinner").show();
          file_selected = true;
            }
          }
          )
          
        },
        onComplete: function(file,response){
          // enable the submit button
          // get rid of the spinner
          // hide the upload options
          // set the hidden form value to attach to the file
          // notify the user of completion
          // provide a delete link to start over
          console.log(response)
          if (response == "0")
          {
            alert("An error occured while trying to upload your file. Please refresh the page and try again.");
            $("#spinner").hide();
            $("#upload_here").show();
          }
          else 
          {
            $("#submit").enable();
            $("#spinner").hide();
            $("#upload_here").hide();
            $("#file_id").attr('value',response);
            $("#complete").show().html("File '" + file + "' <span class='highlight'>received</span>");
            $("#complete").append(" (<a href='#' onclick='clear_photo();return false;'>Delete file</a>)");
          }
        }
      }
    )
  }
})

function clear_photo(){
  // reset the upload form back to it's original state
  $("#complete").hide();
  $("#upload_here").show();
  $("#submit").disable();
  file_selected = false;
}

function success_and_reset()
{
  // update the main form and put the file in it's category

  $("#form_response").attr("class","success").html("File uploaded successfully").fadeIn().animate({opacity: 1.0}, 3000).fadeOut();
  $("#complete").hide();
  $("#submit").disable();
  $("#upload_here").show();
  category_column = "#category_" + $("#upload_category_id option:selected").attr("value") + " .file-listing";
  $("#upload_form").reset();
  // the file details are stored in #results, put this in the category column
  if ($(category_column)){
    $(category_column).prepend($("#results").html());
    $(category_column).effect("highlight", {}, 3000)
  } 
}

function validate_form(data, form, options)
{
  errors = 0;
  $(data).each(function(){
    if (this.name == "upload[name]")
    {
      if (this.value == ""){ errors += 1;}  
    }


  });

  if (errors > 0)
  { 
  $("#form_response").attr("class","error").show().html("<strong>Your name</strong> and a <strong>file</strong> a required");
  
  return false;}
  else { return true;}
}

