
// called by ooyala's js after it includes and initializes itself
function onOoyalaUploaderReady() {
  ooyalaUploader.addEventListener('fileSelected','onFileSelectedOoyala');
  ooyalaUploader.addEventListener('progress','onProgressOoyala');
  ooyalaUploader.addEventListener('complete','onCompleteOoyala');
  ooyalaUploader.addEventListener('error','onUploadErrorOoyala');
  ooyalaUploader.addEventListener('embedCodeReady','onEmbedCodeReadyOoyala');

  // ooyala js code must initialize before the upload button can fire,
  // attach onclick here
  $('upload_button').observe('click', startUploadOoyala);
  return true;
}

// entry function to start uploading video files to ooyala
function startUploadOoyala() {
  if (!validateUploadForm()) {
    return false;
  }

  // immediately disable the upload button so users cannot submit duplicates
  $('upload_button').stopObserving('click', startUploadOoyala);
  // clunky way to find the selected option, thanks IE
  f     = $('upload_form');
  input = f['video_category_id']; 
  var category = null;
  $A(input.options).each(function(c) {
      if (c.selected) category = c.innerHTML;
  });

  // add ooyala params first, since the server must sign them
  params = {category: "/category/"+category };

  if (current_login) { // var set in upload template
    params['user'] = "/user/"+current_login;
  }

  ooyalaSign(params, commitOoyalaUpload);
}

function validateUploadForm() {
  var req_txt_fields = ["video_title", "video_description", "video_filename"];
  var invalids = $A([]);
  var txt, clean_form_name, error_text, error_div_id, error_div;
  req_txt_fields.each(function(f) {
    txt             = $(f).value;
    clean_form_name = f.gsub(/_/, ' ');
    error_text      = 'Please include a valid '+clean_form_name;
    error_div_id    = 'invalid_form_'+f;
    error_div       = $(error_div_id);

    if (txt.empty()) {
      error_div.innerHTML = error_text;
      invalids.push(error_div);
      if (!error_div.visible()) new Effect.Appear(error_div);
    } else {
      $(f).value = txt.strip();
      if (error_div.visible()) new Effect.Fade(error_div);
    }
  });
  return invalids.size() > 0 ? false : true; // false means some form inputs were invalid
}

function ooyalaSign(params, callback) { // callback will be 'commitOoyalaUpload()'
  new Ajax.Request('/videos/upsign', {
    method: 'get',
    parameters: params,
    onComplete: function(r) {
      callback(r.responseText);
    }
  });
}

function commitOoyalaUpload(signature) {
  ooyalaUploader.setParameters(signature);
  ooyalaUploader.setTitle($('video_title').value);
  ooyalaUploader.setDescription($('video_description').value);

  if (validOoyalaUpload()) {
    // perform the actual upload
    var result = ooyalaUploader.upload();
    if (result) {
      lightBoxStart();
    }
    // TODO: if ooyalas uploader fails, show some message
  }
  // make sure the upload button is reactivated so users can click it
  $('upload_button').observe('click', startUploadOoyala);
}

function validOoyalaUpload() {
  var error_text = ooyalaUploader.validate();
  var is_valid = false;

  if ($('error_message')) {
    new Effect.Fade($('ooyala_error'));
    $('error_message').remove();
  }

  if (error_text == null) {
    is_valid = true;
  } else {
    is_valid = false;
    // gotcha: div must wrap an inner div for scriptaculous effects to work
    var inner_div_txt = "File Upload Error: "+error_text;
    var inner_div = Builder.node('div', {'id': "ooyala_error", 'class':'invalid_form_input'}, inner_div_txt);
    error_div = Builder.node('div', {id:'error_message'}, inner_div);
    $('upload').insert({top:error_div});
    $('ooyala_error').hide();
    new Effect.Appear($('ooyala_error'));
  }
  return is_valid;
}

// callback functions ooyala js requires
function onFileSelectedOoyala(file) {
  $('video_filename').value = file.name;
}

function onProgressOoyala(progress) {
  if (progress.total > (500*1024*1024)) {
    if ($('progress_msg')) {
      $('progress_msg').innerHTML = "REELcomp Error: Come on, try to keep it under 500MB and upload it again!";
    }
    var reload = function () {
      lightBoxStop();
    };
    setTimeout(reload, 5000);
    return true;
  }

  // must check for existence of elem, ooyalas <object> calls this one final time after the lightbox
  // has been faded/removed
  if ($('progress_percent')) {
    $('progress_percent').innerHTML = Number(progress.uploaded/1024/1024).toPrecision(3)+" MB ( "+ (parseInt(progress.ratio * 10000) / 100) + '% )';  
  }

  if (progress.total == progress.uploaded) {
    if ($('progress_msg')) {
      $('progress_msg').innerHTML = "UPLOAD COMPLETED 100%! Thanks for uploading, we'll hit you up by email when it's approved and available on the site.";
      $('close_light_box').show();
    }
  }
}

// this call back doesn't yet appear to work with ooyala
//function onUploadErrorOoyala(err) { }

function onEmbedCodeReadyOoyala(embedCode) {
  $('video_embed_code').value = embedCode;
  params = $('upload_form').serialize(true)
  params.filename = null; // this input is only used by ooyala's js, dont submit it
  new Ajax.Request('/videos/create', {
    method: 'post',
    parameters: params
    // TODO? if this request somehow fails, do some kind of error checking, upload
    // should not continue
  });
}

function lightBoxStart() {
  setupLightBox();
  new Effect.Appear($('upload_lightbox_overlay'), { duration: 0.5, from: 0.0, to: 0.8 });
  new Effect.Appear($('upload_lightbox_modal'), { duration: 0.6, from: 0.0, to: 1.0 });
}

function setupLightBox() {
  offsets  = document.viewport.getScrollOffsets();
  viewport = document.viewport.getDimensions();
  body     = $$('body').first();
  bodyvp   = body.getDimensions();
  // cover the body with the transparent overlay. gotcha: must be recreated each time,
  // display breaks if the overlay is defined in the template
  overlay = Builder.node('div', {'id':'upload_lightbox_overlay'});
  body.insert({'top':overlay});
  var overlay_style = {'width': bodyvp.width+"px", 'height': bodyvp.height+"px"};
  $('upload_lightbox_overlay').setStyle(overlay_style);
  overlay.hide();

  // center the modal box
  modal_width  = Math.floor( 0.45 * viewport.width);
  modal_height = Math.floor( 0.45 * viewport.height);
  modal_top    = Math.floor( offsets.top + (viewport.height - modal_height) / 2 );
  modal_left   = Math.floor( offsets.left + (viewport.width - modal_width) / 2 );

  // must dynamically generate these to prevent display position errors when the html
  // is defined in the template
  var modal = Builder.node('div', {'id': "upload_lightbox_modal"}, [
                Builder.node('a', {'href': "#", 'onClick': "lightBoxStop();"}, 
                  Builder.node('img', {'src': "/images/exitButton.png"})), 
                Builder.node('div', {'style': "clear:both"}), 
                Builder.node('div', {'id': "upload_lightbox_title"},
                  Builder.node('h1', "Uploading Video File: ", $('video_filename').value,
                    Builder.node('span', {'id': "upload_lightbox_filename"}))),
                Builder.node('h2', {'id': "progress_percent"}, "0%"),
                Builder.node('h2', {'id': "progress_msg"}, "DON'T LEAVE THIS PAGE!! Please wait until you see 100% on the progress bar. You will also see a new message confirming the upload! Thanks for uploading your video to REELcomp, we're pumped to see it!"),
                Builder.node('div', {'id':'close_light_box', 'style':'text-align:center;display:none'}, 
                  Builder.node('button', {'onClick':"lightBoxStop()", 'style':'border 1px solid black;text-align:center'}, "Close"))
              ]);

  body.insert({'top': modal});
  $('upload_lightbox_modal').setStyle({
    'top':    modal_top+"px",
    'left':   modal_left+"px",
    'width':  modal_width+"px",
    'height': modal_height+"px"
  });
  $('upload_lightbox_modal').hide();
}

function lightBoxStop() {
  var lightbox_hide = function() {
      if ($('upload_lightbox_overlay')) $('upload_lightbox_overlay').remove();
      if ($('upload_lightbox_modal')) $('upload_lightbox_modal').remove();
      return true;
  };
  setTimeout(lightbox_hide, 3000);
  $('upload_form').reset();
  new Effect.Fade($('upload_lightbox_modal'), { duration: 0.2, from: 1.0, to: 0.0 });
  new Effect.Fade($('upload_lightbox_overlay'), { duration: 0.25, from: 8.0, to: 0.0 });
}

