var Story = {
  initCustomizableAddress: function(){
    $('.customizable_address input').character_counter(128, $('.customizable_address .counter'));

    $('.customizable_address a').click(function(){
      $('.customizable_address .current').hide();
      $('.customizable_address .editable').show()
      $('.customizable_address input').select();
      return false;
    })
  },
  initMissingImageHover: function(){
    $('.inset.gallery .missing_image').hover(function(){
      $(this).find('img').animate({opacity:1},200);
    }, function() {
      $(this).find('img').animate({opacity:0.33},200);
    });
  },
  add_see_more: function( id, label ) {
    $(id).first().before('<p style="text-align: center;"><a href="#" onclick="$(\'' + id + '\').toggle(); return false">' + label + '</a></p>');
    $(id).hide();
  },
  expand_see_more: function( id, label, compact_height ) {
    el = $(id).first();
    el.after('<p style="text-align: center;"><a href="'+id+'" class="index" onclick="Story.toggle_expand_see_more(\'' + id + '\', \'' + compact_height + '\')">' + label + '</a></p>');
    el.css('position', 'relative');
    el.css('overflow', 'hidden' );
    el.css('height', compact_height );
  },
  toggle_expand_see_more: function( id, compact_height ) {
    el = $(id).first();
    if( el.css('height') == compact_height  ) {
      el.css('height', 'auto' );
      el.next().children(":first").text( el.next().children(":first").text().replace( /more/, "less" ) );
    } else {
      el.css('height', compact_height );
      el.next().children(":first").text( el.next().children(":first").text().replace( /less/, "more" ) );
    }
  },
  initProgressHash: function(){
    if ((window.location.hash !== '') && (window.location.hash !== '#edit_address')) {
      $('.chapter').hide();
      var destination = $(window.location.hash).closest('.chapter');
      // hide any toggle links
      destination.find('.heading .toggler').hide();
      $(window.location.hash).closest('.chapter').show();
      window.location = window.location.hash;
    }
  },
  initProgressLinkClick: function(){
    $('ol.progress_links li a').click(function(){
      if($(this).attr('href').match(window.location.pathname)){
        $('.main .inset').show();
      }
    });
  },
  initIphoneAppClick: function(){
    if (window.location.hash === '#iphone') {
      Story.showGetIphoneApp();
    }
    $('a.iphone').click(function(){
      Story.showGetIphoneApp();
      return false;
    });
  },
  initGetIphoneAppNotification: function(){
    if( $.cookie('do_not_bug_about_iphone_app') !== 'true' ) {
      Story.showGetIphoneApp();
    }
    $('#iPhoneAppNoThanks').change( Story.doNotBugGetIphoneApp );
  },
  showGetIphoneApp: function(){
    $('#modalOverlay').show();
    $('#getIphoneApp').show();
  },
  hideGetIphoneApp: function(){
    $('#modalOverlay').hide();
    $('#getIphoneApp').hide();
    if( $.cookie('do_not_bug_about_iphone_app') === 'true' ) {
      var li = $('a.iphone').closest('li');
      var list = li.parent();
      // remove from list, hide entire list if nothing left to do
      li.remove();
      if( list.children().length == 0)
      {
        list.closest('.checklist').hide();
      }
    }
  },
  doNotBugGetIphoneApp: function() {
    $.cookie('do_not_bug_about_iphone_app', $("#iPhoneAppStopBugging").attr('checked') ? 'true' : 'false', { expires: 365 } );
  }
};

var StoryAdmin = {
  init_form: function() {
    StoryAdmin._init_calendar();
    StoryAdmin._init_radio_helpers();
    // StoryAdmin._init_countdowns();
  },

  removeExternalLink: function(elem) {
    $(elem).parent().parent().remove();
  },
  addExternalLink: function() {
    $('#externalLinks').append("<tr>" +
      "<td class=\"link_name\"><input type=\"text\" size=\"10\" name=\"external_link_name[" + base_externalLinkNextIdx + "]\" class=\"name\" value=\"\"/> </td> " +
      "<td class=\"link_url\"><input type=\"text\" size=\"10\" name=\"external_link_url[" + base_externalLinkNextIdx + "]\" class=\"url\" value=\"\"/> </td> " +
      "<td class=\"link_sort\"><input type=\"text\" size=\"10\" name=\"external_link_sort[" + base_externalLinkNextIdx + "]\" class=\"sort\" value=\"\"/></td> " +
      "<td><a href=\"#\" onclick=\"StoryAdmin.removeExternalLink(this); return false\"><img alt=\"Remove\" src=\"/images/brands/default/unified_card/remove.png\" /></a></td> " +
    "</tr> ");
    base_externalLinkNextIdx++;
  },

  removeDonationOption: function(elem) {
    $(elem).parent().remove();
  },
  addDonationOption: function() {
    $('.levels').append(
      "<div class='level'>" +
      "  <span style='font-size: 18px; vertical-align: middle;'>$</span>" +
      "  <input type='text' value='' class='amt' name='story[donation_suggestion_levels][" + base_suggestLevelNextIdx + "]' style='width: 40px;'>" +
      "  <input type='text' value='' class='description' name='story[donation_suggestion_descriptions][" + base_suggestLevelNextIdx + "]' style='width: 258px;'>" +
      "  <a onclick='StoryAdmin.removeDonationOption(this); return false' href='#'><img src='/images/unified_card/remove.png?1283539187' alt='Remove'></a>" +
      "</div>"
    );
    base_suggestLevelNextIdx++;
  },

  _init_calendar: function() {
    // load up calendar
    $('#story_end_date').datepicker({ dateFormat: 'MM d, yy' });
  },

  _init_radio_helpers: function() {

    $(".imagePicker input[type='text'], .imagePicker input[type='file']").focus(function(){
      $(this).closest('li').children("input[type='radio']").attr('checked', 'checked');
    });

    // // radio button helpers for video
    // $('.videoDiv .checkBoxBuddy').click(function() {
    //   $('#videoBox').attr('checked', 'checked');
    // });
    // $('#youtubeField').focus(function() {
    //   $('#videoBox').attr('checked', 'checked');
    // });
    // 
    // // radio button helpers for image
    // $('.imageDiv .checkBoxBuddy').click(function() {
    //   $('#imageBox').attr('checked', 'checked');
    // });
    // $('#imageChooser').click(function() {
    //   $('#imageBox').attr('checked', 'checked');
    // });
  },

  _init_countdowns: function() {

    // load up countdowns
    var default_countables = {
      safeClass: 'countdown_safe',
      overClass: 'countdown_over',
      onOverCount: function(count, countable, counter) { counter.text(-count + ' characters over limit'); },
      onSafeCount: function(count, countable, counter) { counter.text(count + " characters left");  if (count > 30) { counter.hide(); } else { counter.show(); } }
    };

    $('#story_blurb').simplyCountable($.extend(default_countables, { counter: '#storyEditSummaryCountdown', maxCount: 140 }));
    $('#story_story').simplyCountable($.extend(default_countables, { counter: '#storyEditStoryCountdown',   maxCount: 5000 }));

    if ($('#story_designation').length !== 0) {
      $('#story_designation').simplyCountable($.extend(default_countables, { counter: '#storyEditDesignationCountdown', maxCount: 75 }));
    }
    if ($('#story_title').length !== 0) {
      $('#story_title'      ).simplyCountable($.extend(default_countables, { counter: '#storyEditTitleCountdown',       maxCount: 75 }));
    }
  }
};

/* Designations */
StoryDesignations = {
  bindEvents: function() {
    $('select#story_designation').change(StoryDesignations.toggleDesignationEntry);
  },

  toggleDesignationEntry: function() {
    if ( $('select#story_designation').val() === 'Other...' ) {
      $('#story_designation_entry').show();
    } else {
      $('#story_designation_entry').hide();
    }
  },

  updateDesignationList:function(){
    $.getJSON('/story/' + $('#story_org_id').val()+'/project_designations', function(data) {
      var options = '';
      for (var i=0; i<data.length; i++) {
        options += '<option>' + data[i] + '</option>';
      }
      options += '<option>Other...</option>';
      $('select#story_designation').html(options);
      $('#story_designation_entry').hide();
    })
  }
};

$(function(){
  StoryAdmin.init_form();
  StoryDesignations.bindEvents();
  StoryDesignations.toggleDesignationEntry();
});

