var VideoUploader =  {
  swf_upload_control: null,
  daFile: null,
  title: '',
  init: function() {
    var debug = false || !!window.location.search.match('debug');

    VideoUploader.swf_upload_control = new SWFUpload({

      flash_url : "/swfs/elements/swfupload.swf",
      // Backend settings
      upload_url: VideoUploader.upload_url + "?_cookie=" + encodeURIComponent(document.cookie),

      // Flash file settings
      file_size_limit: "102400",  // 100 MB
      file_types: "*.avi;*.mov;*.mpeg;*.mpg;*.mp4;*.3gp;*.wmv;*.flv;*.divx;*.m4v",
      file_types_description: "Video Files",
      file_upload_limit: "0", // Even though we only want 1 file, we want the user to be able to try again if an upload fails

      // Callbacks
      //file_dialog_complete_handler : dostuff, // force the upload to happen after first add
      file_queued_handler: VideoUploader.fileQueued,
      upload_complete_handler: VideoUploader.uploadComplete,          // after upload is complete we can call the next step
      upload_progress_handler: VideoUploader.uploadProgress,          // update the sidebar with the status of the upload
      upload_success_handler: VideoUploader.uploadSuccess,          // update the sidebar with the status of the upload

      // these are defaults, can be overwritten by caller
      button_placeholder_id : "choose_photos",
      button_image_url : "/images/buttons/upload_video_map.gif",
      button_width : 160,
      button_height : 32,
      //button_text_left_padding : 3,

      // Debug settings
      debug: debug
    });
  },
  validate: function() {
    var rval = "";
    var title = $('#video_title')[0].value;
    if (title.length < 4) {
      rval += "<li>Title must be at least 4 characters long</li>";
    }
    if ($('#video_dance_id').val() == '0') {
      rval += "<li>Please specify a dance</li>";
    }
    if (!VideoUploader.daFile) {
      rval += "<li>Please select a file</li>";
    }

    if (rval.length) return rval;
    return null;
  },
  editDetails: function() {
    // FIXME put the view modification inline withe view code
    $('li#youtube').hide();
    $('p#step_title').html("<h3>Please edit the details of your video</h3>");
    $('.titled_field.file_field').hide();
    $('#editMetaData').fadeIn(500);
    $('#video_title').focus();
    $('#SWFUpload_0').attr('width', '1');
    $('#SWFUpload_0').attr('height', '1');
    $('fieldset.video_upload br').hide();
  },
  doUpload: function() {
    //setConfirmUnload(true);
    var errors = VideoUploader.validate();
    if (errors) {
      $('#upload_messages').html('<ul id="errorExplanation" class="errorExplanation">' + errors + '</ul>');
      return false;
    }
    $('p#step_title').html("<h3>Uploading file </h3>");
    var post_params = {"_cookie": document.cookie};
    var fieldElems = jq('#new_video').serialize().split('&');
    for (var i=0; i < fieldElems.length; i++) {
      var key = unescape(fieldElems[i].split('=')[0]);
      var value = unescape(fieldElems[i].split('=')[1]);
      post_params[key] = value;
    }
    $('#editMetaData').hide();
    $('#upload_progress').fadeIn(400);
    VideoUploader.swf_upload_control.setPostParams(post_params);
    VideoUploader.swf_upload_control.startUpload();
  },
  fileQueued: function(fileObj) {
    try {
      var txtFileName = $("#video_file");
      txtFileName[0].value = fileObj.name;
      VideoUploader.daFile = fileObj;
      VideoUploader.editDetails();
    } catch (e) { }
  },
  uploadSuccess: function(fileObj, aResponse) {
    setConfirmUnload(false);
    //TODO: Consistent pattern for routing and strings in JS
    window.location = aResponse;
  },
  uploadComplete: function(fileObj) {
  },
  uploadProgress: function(fileObj, bytesLoaded) {
    jq('#progress .current').css('width', 100 * (bytesLoaded / fileObj.size) + '%');
    jq('#progress .current .message').html(parseInt((bytesLoaded / fileObj.size)*100) + '%');
  }
};

jq(function() {
  var options = {
    beforeSubmit: function() {
      $('span.youtube_status').removeClass('error');
      $('input.button').attr('disabled', true);
      $('span.youtube_status').text('Importing video YouTube please wait ...');
    },

    success: function(rsp) {
      rsp = eval(rsp)[0];
      if (rsp.status == 'ok') {
        $('span.youtube_status').text('Success! Please wait while you are redirected to edit the video details.');
        location.href = rsp.href;
       } else {
        $('span.youtube_status').addClass('error');
        $('span.youtube_status').text(rsp.message);
       }
       $('input.button').attr('disabled', false);
     },

     error: function(rsp) {
       $('span.youtube_status').addClass('error');
       $('span.youtube_status').text('There was an error importing video from YouTube.');
       $('input.button').attr('disabled', false);
     }
  }
  jq('#youtube_uploader').ajaxForm(options);
});

function trim(string) {
  return string.replace(/(^\s*|\s*$)/, "");
}

