var templates = {};

$(function() {
  var not_uploaded = 0;
  var upload_forms = ['video_upload_form', 'photo_upload_form',
                      'audio_upload_form', 'logo_upload_form',
                      'featured_asset_upload_form',
                      'related_document_upload_form',
                      'press_release_document_upload_form'];

  $(upload_forms).each(function(index, id) {
    save_element   = $('#' + id.replace('_upload_form', '_form') + ' .trigger');
    upload_element = $('#' + id);

    if (id == 'featured_asset_upload_form') {
      save_element = $('#featured_media_embed_submit');
    }

    upload_element
      .find('input[type="file"]')
        .change(function() {
          var
          pending_uploads = save_element.data('pending-uploads');
          pending_uploads = (pending_uploads || 0) + 1;

          save_element.data('pending-uploads', pending_uploads);
        })
      .end()
      .parent()
        .next('button')
          .click(function() {
            var
            pending_uploads = save_element.data('pending-uploads');
            pending_uploads = pending_uploads > 0 ? pending_uploads - 1 : 0;

            save_element.data('pending-uploads', pending_uploads);
          });

    save_element
      .click(function(event) {
        var pending_uploads = save_element.data('pending-uploads') || 0;

        if (pending_uploads > 0) {
          if (!confirm('Some selected files have not been uploaded. Are you sure you want to continue?')) {
            event.stopImmediatePropagation();

            return false;
          }
        }
      });
  });

  $('#featured_media_embed_submit').click(function() {
    $('#featured_asset_form').submit();
    $('#featured_embed_form').submit();
  });

  $(".trigger").click(function() {
    var item = $(this).parents(".show")
    var box = $(this).parents(".box")
    if(box.length == 0) { var box = $(this).parents(".split-col") }

    if($(this).parents(".show").length == 0) {
      item = $(this).parents(".edit")
    }

    if($(this).parents(".show").length != 0) {
      item.siblings('.edit').show();
      box.addClass('editing');
    } else {
      item.siblings('.show').show();
      box.removeClass('editing');
    }

    item.hide();
  });

  // Used to dynamically insert form fields
  $(".add_nested_item").click(function(e) {
    var name = $(this).attr('rel')
    $('#display_edit_' + pluralize(name)).append(eval("templates."+name).replace(/NEW_RECORD/g, new Date().getTime()));
    return false;
  });
});

function addResizedEmbedCode(code, to_element) {
  if (code.replace(/ /g, "") == "")
    return false;

  code = resizeChildElementsRecursive($(unescape(code)), 360);

  if (!to_element.jquery)
    to = $("#" + to_element);
  else
    to = to_element;

  to.html(code);

  // This is so ugly hack! IE doesn't resize if it the embed code isn't loaded.
  if ($.browser.msie) {
    setTimeout(function() {
      resizeChildElementsRecursive(to, 360);
    }, 2000);
  }
}

function resizeChildElementsRecursive(element, width) {
  if (!element) return;

  // Change width if it is smaller than {width} or it is not specified.
  if ($(element).attr("width") && parseInt($(element).attr("width")) > width || !($(element).attr("width"))) {
    $(element).attr("width", width);
  }

  $.each($(element).children(), function(index, el) {
    resizeChildElementsRecursive(el, width);
  });

  return element;
}

function update_all_sections() {
  var data = release_info;

  update_media_contacts(data);
  update_headline(data);
  update_summary(data);
  update_related_links(data);
  update_quotes(data);
  update_statements(data);
  update_photos(data);
  update_videos(data);
  update_audios(data);
  update_press_release_document(data);
  update_related_documents(data);
  update_featured_asset(data);
  update_featured_embed(data);
  update_logo(data);
  update_footer(data);
  update_embeds(data);
  update_call_to_action(data);

}

SINGULAR_ASSETS = ["logo","press_release_document","featured_asset","featured_embed"];
function pluralize(which) {
  return (SINGULAR_ASSETS.indexOf(which) == -1) ? which + "s" : which;
}

function update_media_contacts(data) {
  update_section("media_contact",['name', 'company', 'email', 'phone', 'additional_info'],data);
}

function update_related_links(data) {
  update_section("related_link",['title', 'url', 'description'],data);
}

function update_quotes(data) {
  update_section("quote",['content', 'name'],data);
}

function update_statements(data) {
    update_section("statement",['content'],data);
}

function update_photos(data) {
    update_section("photo",["name","title","thumbnail","large_thumbnail","description"],data);
}

function update_press_release_document(data) {
  update_section("press_release_document",["name","title","thumbnail","description","converted_status"],data);
}

function update_related_documents(data) {
  update_section("related_document",["name","title","thumbnail","description"],data);
}

function update_featured_asset(data) {
  update_section("featured_asset",["name","title","thumbnail","large_thumbnail","description","converted_status"],data);
}

function update_featured_embed(data) {
  update_section("featured_embed",["name","title","embed_code","description"],data);

  var element = $($(".featured_embed_template")[0]);

  if (element.length && element.html()) {
    addResizedEmbedCode(escape(element.html()), element);

    // This is so ugly hack! IE doesn't resize if it the embed code isn't loaded.
    if ($.browser.msie) {
      setTimeout(function() {
        resizeChildElementsRecursive(element, 360);
      }, 2000);
    }
  }
}

function update_embeds(data) {
  update_section("embed",["name","title","embed_code","description"],data);

  $.each($(".show .embed_wrapper"), function(index, ec) {
    if(ec && $(ec).html()) {
      addResizedEmbedCode(escape($(ec).html()), $(ec));

      // This is so ugly hack! IE doesn't resize if it the embed code isn't loaded.
      if ($.browser.msie) {
        setTimeout(function() {
          resizeChildElementsRecursive($(ec), 360);
        }, 2000);
      }
    }
  });
}

function update_videos(data) {
  update_section("video",["name","title","thumbnail","large_thumbnail","description"],data);
}

function update_audios(data) {
  update_section("audio",["name","title","thumbnail","description"],data);
}

function update_logo(data) {
  update_section("logo",["name","title","thumbnail","large_thumbnail","description","converted_status"],data);
}

function update_footer(data) {
  var show_contents = $('#footer .show .contents');
  var default_contents = $('#footer .show .default');

  var data = data['release']['release']['footer'];
  if(data != "") {
    default_contents.hide();
  } else {
    default_contents.show();
  }

  show_contents.empty();
  show_contents.append(data);
}

function update_headline(data) {
  var show_contents = $('#headline .show .contents');

  show_contents.empty();
  show_contents.append(data['release']['release']['headline']);
}

$(function() {
  $('#summaryForm').submit(function(event) {
    var html = CKEDITOR.instances.release_summary.getData();

    $(this)
      .find('textarea')
        .val(html.replace(/[\n\t\r]/g,''))
      .end()
      .ajaxSubmit(update_response);

    return false;
  });
});

function update_call_to_action(data) {
  var release = data.release.release;

  $('#call-to-action')
    .find('h4, a')
      .hide();

  if ($.trim(release.action_title) == '' ||
      $.trim(release.action_description) == '' ||
      $.trim(release.action_url) == '') {
    return;
  }

  $('#call-to-action')
    .find('h4')
      .text(release.action_title)
      .show()
    .end()
    .find('a')
      .text(release.action_description)
      .attr('href', release.action_url)
      .show();
}

function update_summary(data) {
  var show_contents = $('#summary .show .contents');
  var default_contents = $('#summary .show .default');

  var data = data['release']['release']['summary'];

  if(data != null && data != "") {
    default_contents.hide();
  } else {
    default_contents.show();
  }

  show_contents.empty();
  show_contents.append(data);
}

function update_section(which,populate_fields,data) {
  var which_pl = pluralize(which);

  var show_contents = $('#' + which_pl + ' .show:first .contents:first');
  var edit_contents = $('#' + which_pl + ' .edit #display_edit_' + which_pl + '');
  var default_contents = $('#' + which_pl + ' .show:first .default:first');

  if (which == 'featured_embed') {
    show_contents = $('#featured_embed_show .contents:first');
    default_contents = $("#featured_embed_show .default:first");
  }

  if (default_contents)
    show_contents.empty();

  edit_contents.empty();

  var section = data[which_pl];
  if( section == null || section.length == 0 ) {
    default_contents.show();

    if (which == 'featured_embed') {
      $('#display_edit_featured_embed').empty();
      $('.featured_embed_template:gt(0)').remove();

      add_edit_entry(which, {name: " ", title: " ", embed_code: " ", description: " ", _destroy: "0"}, null,
        ["name", "title", "embed_code", "description", "_destroy"]);
    }
    return;
  } else {
    default_contents.hide();
  }

  $(section).each(function(i, the_object) {
    var main_object = the_object[which];

  // type specific defaults
  if( !main_object.thumbnail ) {
    switch(which) {
      case "photo":
        main_object.thumbnail = "/images/default_photo_thumbnail.gif";
        break;
      case "video":
        main_object.thumbnail = "/images/default_video_thumbnail.gif";
        break;
      case "related_document":
      case "press_release_document":
        main_object.thumbnail = "/images/default_document_thumbnail.gif";
        break;
      case "logo":
        main_object.thumbnail = "/images/default_logo_thumbnail.gif";
        break;
      case "featured_asset":
        main_object.thumbnail = "/images/default_featured_asset_thumbnail.gif";
        break;
      case "audio":
        main_object.thumbnail = "/images/default_audio_thumbnail.gif";
        break;
    }
  }
  if( !main_object.large_thumbnail )
    main_object.large_thumbnail = main_object.thumbnail;

  // show templates
    var template_name = '.'+which+'_template'

    if (which == 'featured_embed') {
      $(template_name + ":gt(0)").remove();
    }

    $(template_name + ":first").render(main_object, {
        preserve_template: true,
        clone: true,
        afterUpdate: function(new_node) {
      // IE HACK manually set src of img's
      if( new_node.find('img.large_thumbnail').length > 0 )
      new_node.find('img.large_thumbnail')[0].src = main_object.large_thumbnail
      else if( new_node.find('img.thumbnail').length > 0 )
      new_node.find('img.thumbnail')[0].src = main_object.thumbnail

      new_node.show();
          show_contents.append(new_node);
        }
    });

    // edit templates
    if (which == 'featured_embed') {
      if ($('#display_edit_featured_embed').children().length == 1) {
        $('#display_edit_featured_embed').empty();
      }
    }

    add_edit_entry(which,main_object,main_object.id,populate_fields);
  })

  PLC.refresh();

}

function add_edit_entry(which,object,id,populate_fields) {
  var which_pl = pluralize(which);

  var edit_contents = $('#display_edit_'+which_pl);

  var timestamp = new Date().getTime();

  var id_template = null;
  if( id ) {
    id_template = '<input type="hidden" value="' + id + '" name="release['+which_pl+'_attributes]';
    if ( SINGULAR_ASSETS.indexOf(which) == -1 )
      id_template += '[' + timestamp + ']';
    id_template += '[id]" id="release_'+which_pl+'_attributes_' + timestamp + '_id"/>';
  }

  var html = eval("templates."+which).replace(/NEW_RECORD/g, timestamp)
    if( object.name )
      html = html.replace(/ASSET_NAME/g, object.name);

  var the_template = $(html).prepend(id_template);
  if( id_template )
    the_template = the_template.prepend(id_template);

  $(populate_fields).each(function(i, field){
    the_template.find('.' + field).val(eval('object.' + field));

    // asset specific setting of thumbnail
    if( field == "thumbnail" ) {
      the_template.find("img")[0].src = object.thumbnail
    }
  });

  edit_contents.append(the_template);
}

// callback from the dropioApiClient
function photo_uploaded(response,success) {
  $("#photo_upload_spinner").hide();
  if( !validate_media_uploaded("photo",response, success) ) return;
  save_media_on_upload("photo",response);
}

// callback from the dropioApiClient
function video_uploaded(response,success) {
  $("#video_upload_spinner").hide();
  if( !validate_media_uploaded("video",response, success) ) return;
  save_media_on_upload("video",response);
}

// callback from the dropioApiClient
function related_document_uploaded(response,success) {
  $("#related_document_upload_spinner").hide();
  if( !validate_media_uploaded("related_document",response, success) ) return;
  save_media_on_upload("related_document",response);
}

// callback from the dropioApiClient
function logo_uploaded(response,success) {
  $("#logo_upload_spinner").hide();
  if( !validate_media_uploaded("logo",response, success) ) return;
  save_media_on_upload("logo",response);
}

// callback from the dropioApiClient
function featured_asset_uploaded(response,success) {
  $("#featured_asset_upload_spinner").hide();
  if( !validate_media_uploaded("featured_asset",response, success) ) return;
  save_media_on_upload("featured_asset",response);
}

// callback from the dropioApiClient
function press_release_document_uploaded(response,success) {
  $("#press_release_document_upload_spinner").hide();
  if( !validate_media_uploaded("press_release_document",response, success) ) return;
  save_media_on_upload("press_release_document",response);
}

// callback from the dropioApiClient
function audio_uploaded(response,success) {
  $("#audio_upload_spinner").hide();
  if( !validate_media_uploaded("audio",response, success) ) return;
  save_media_on_upload("audio",response);
}



function validate_media_uploaded(which,response,success) {
  if( !success ) {
    alert("There was a problem uploading your " + which + ". Please try again.");
    return false;
  }

  var valid_types = {"photo":"image",
             "video":"movie",
             "related_document":"document",
             "press_release_document":"document",
             "logo":"image",
             "featured_asset":"image or movie",
             "audio":"audio"};

  if( valid_types[which].indexOf(response.type) == -1 ) {
    alert("That file was not a " + valid_types[which] + ". Please be sure to upload a valid "+valid_types[which]+" file.");
    dropioApi.deleteAsset({drop_name:DROP,admin_token:DROP_ADMIN_TOKEN,asset_name:response.name},function(response,success) {}); // clean up
    return false;
  }

  return true;
}

// do an initial save of the edit form with media that is just uploaded so the user doesnt have to click save
// and just in case the pingback url comes quickly
function save_media_on_upload(which,response) {
  add_edit_entry(which,{name:response.name,title:response.name,converted_status:"pending"},null,["name","title","converted_status"]);

  // clear file chooser
  $('#'+which+'_upload_form input[type=file]').val("");

  $('#'+which+'_form').ajaxSubmit(update_response);
}

function update_asset(stream_data) {
  if( stream_data && thumbnails_are_converted(stream_data) ) {
	var id = id_for_asset_with_name(stream_data.name)
	if( id == -1 ) return;
    var url = MANUALLY_CHECK_ASSET_STATUS_URL.replace("%7Bid%7D",id);
    $.post(url,{},function(data) {
      data = eval("("+data+")");
      if( data && data.success && data.converted ) {
        if( data.thumbnail ) {
          if( (pti = $('.photo_template.asset-'+data.name+' img') ).length > 0 ) {
            pti[0].src = data.thumbnail;
          }
          if( (vt = $('.video_template.asset-'+data.name+' img') ).length > 0 ) {
            vt[0].src = data.thumbnail;
          }
          if( (eh = $('.entry.asset-'+data.name+' .thumbnail') ).length > 0 ) {
            eh[0].value = data.thumbnail;
          }
          if( (ei = $('.entry.asset-'+data.name+' img') ).length > 0 ) {
            ei[0].src = data.thumbnail;
          }
        }
        if( data.large_thumbnail ) {
          if( (pti = $('.logo_template.asset-'+data.name+' img') ).length > 0 ) {
            pti[0].src = data.large_thumbnail;
          }
          if( (fati = $('.featured_asset_template.asset-'+data.name+' img') ).length > 0 ) {
            fati[0].src = data.large_thumbnail;
          }
          if( (eh = $('.entry.asset-'+data.name+' .large_thumbnail') ).length > 0 ) {
            eh[0].value = data.large_thumbnail;
          }
        }
      }
    });
  }
}

function id_for_asset_with_name(name) {
  if( name && $(".asset-"+name).length > 0 )
    return $(".asset-"+name).attr("asset_id");
  else
    return -1;
}


function thumbnails_are_converted(stream_data) {
	var res = stream_data.roles && stream_data.roles.role;
	res = res && stream_data.roles.role.name == "large_thumbnail";
	res = res && stream_data.roles.role.locations && stream_data.roles.role.locations.location;
	res = res && stream_data.roles.role.locations.location.status == "complete"
	return res;
}

function update_response(status, result, form) {
  if( result == "success" && eval("(" + status + ")").success != false)
    eval(form.attr('rel') + "(" + status + ")");
  else
    alert("There was an error saving this section. Please try again.");
  return false;
}

function check_asset_status(id) {
  var url = MANUALLY_CHECK_ASSET_STATUS_URL.replace("%7Bid%7D",id);
  $('#asset_action_link_'+id).hide();
  $('#asset_action_spinner_'+id).show();
  $.post(url,{},function(data) {
    $('#asset_action_spinner_'+id).hide();
    if( data ) {
      if( !data.success ) {
        alert("Sorry, there was an error checking on this file's status. Please try again in a few moments.");
        $('#asset_action_link_'+id).show();
        return;
      }
      if( data.converted == false ) {
        alert("Sorry, that file is still not ready. You may want to consider going back to Step 2, deleting this file, then re-uploading it or uploading another file.");
        $('#asset_action_link_'+id).show();
        return;
      } else {
        $("#pending-count")[0].innerHTML = parseInt($("#pending-count")[0].innerHTML) - 1;
        $("#converted-count")[0].innerHTML = parseInt($("#converted-count")[0].innerHTML) + 1;
        if( $('#asset_'+id) ) {
          $('#asset_status_'+id)[0].innerHTML = "<img src='/images/converted.png'/> ready!"
          $('#asset_action_'+id)[0].innerHTML = "";
          setTimeout(function() {
            $('#asset_'+id).remove();
            if( $('.pending-assets-table').children().children().length == 1 )
              $('.pending-assets-table').remove();
          }, 3000);
        }

      }
    }
  },"json");
}

function begin_media_upload(which) {
  $("#"+which+"_upload_spinner").show();
  DropioApiClient.submitUploadForm(which+"_upload_form");
}

// Flash Animation
$(window).load(function(){
  hidden_css = (-1*$('#flashNotice').outerHeight()) + 'px'
  $('#flashNotice').show().animate({top:hidden_css}, 0).animate({top:'0px'}, 1000).animate({opacity:1.0}, 5500).animate({top:hidden_css}, 500);
  $('#flashNotice .hideFlash').click(function(){
    $('#flashNotice').stop().animate({top:hidden_css}, 500);
    return false;
  });
});

// Form Helpers

$(function(){
  $('input.copyField').click(function(){
    this.select();
  });
});

$(function(){
  $('.postAndRedirect').click(function(){
    redirect_url = $(this).attr('redirect_to')
    redirect_param = document.createElement('input')
    $(redirect_param).attr({type:'hidden',name:'redirect_to',value:redirect_url})

    $('#' + $(this).attr('target_form')).append(redirect_param).submit()
    return false;
  });
});

function addFieldHelper(args) {
  $('#' + args['trigger']).click(function(){
    $('#' + args['collection']).append(args['objectHtml']);
    $('#' + args['collection'] + ' .remove-field').unbind('click', removeFieldHelper);
    $('#' + args['collection'] + ' .remove-field').click(removeFieldHelper);
    return false;
  });

  $('#' + args['collection'] + ' .remove-field').click(removeFieldHelper);
}

function removeFieldHelper() {
  $(this).parent().fadeOut("normal", function(){$(this).remove();});
  return false;
}

function urlSafeString(old_string, without_dashes) {
  var no_spaces = without_dashes ? old_string.replace(/\s/g,"") :
                                   old_string.replace(/\s/g,"-")
  var proper_string = no_spaces.replace(/[^a-zA-Z0-9\-]/g, "");

  return proper_string;
}

function ismaxlength(obj){
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
  if (obj.getAttribute && obj.value.length>mlength)
  obj.value=obj.value.substring(0,mlength)
}


function updateBgColorPreview(hsb, hex, rgb) {
  updateColorBox("bg",hex);
  $(".press #content").css("background","#"+hex);
}

function updateLinkColorPreview(hsb, hex, rgb) {
  updateColorBox("link",hex);
  $(".press #content .container a").css("color","#"+hex);
}

function updateColorBox(which,hex) {
  $("#"+which+"ColorBox").css("background","#"+hex);
  $("#"+which+"ColorLabel")[0].innerHTML = (which == "bg" ? "background" : "link") + ": #" + hex;
  $("#"+which+"ColorField").val(hex);
}

function saveColors() {
  $("#colorForm").ajaxSubmit(function(status, result, form) {
    if( !(result == "success" && eval("(" + status + ")").success != false) )
      alert("There was an error saving your colors. Please try again.");
  });
}

function resetColors() {
  updateBgColorPreview(null,"FDFEFE",null);
  $(".press #content").css("background","#FDFEFE url(/images/bg-content.gif) repeat-x scroll 0 0");
  updateLinkColorPreview(null,"790000",null);
  $("#bgColorField").val("");
  $("#linkColorField").val("");
  saveColors();
}

function updateDatepicker() {
  var inst = $.datepicker._curInst;
  inst.input.val($.datepicker._formatDate(inst));
  $.timepicker.update($.datepicker._formatDate(inst));
}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).before(content.replace(regexp, new_id));
}

function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}
