document.observe("dom:loaded", function() {


  // Cookie jar for storing which announcements have been viewed
  CookieJar.prototype.appendString = '';
  expire = 3600 * 24 * 14;
  jar = new CookieJar({expires: expire, path: '/'});




  // Set up sharing with groups on create for photos, videos and blog posts
  if(group_selects = $$('.group_select')){
    $A(group_selects).each(function(group_select){
      
      $(group_select.id + '_add_button').onclick = function(){

        selected_option = group_select.options[group_select.selectedIndex];
        group_id = selected_option.value;
        group_name = selected_option.text;
        
        group_list_item_id = group_select.id + '_item_' + group_id;

        // Check that this group isn't already in the list
        if($(group_list_item_id)){
          alert('Group already selected');
        }
        else {
          // Add a list item with link to remove group and hidden field to store the id
          $(group_select.id + '_list').appendChild( 
            Builder.node('li', {id: group_list_item_id}, [
              Builder.node('a', {href: '#'}, '[x]'),
              ' ' + group_name,
              Builder.node('input', {type:'hidden', name: group_select.id + '_fields[]', value: group_id})
            ])
          );
          setup_group_sharing_remove_links();
        }

      }
      

    });

    setup_group_sharing_remove_links();
    
  }

  
});




function setup_group_sharing_remove_links()
{
  // Link within list item for group removes it from the list
  $$('.shared_with_groups_list li a').each(function(link){
    link.onclick = function(){
      link.parentNode.remove();
      return false;
    }
  });
}


// observing all starboxes
document.observe('starbox:rated', function(e){
  // need to extract type and id or ratable item from a dom id like 'wiki_page_12_rating' or 'video_4_rating'
  identity_parts = e.memo.identity.split('_');
  identity_parts.pop(); // remove _rating from the end
  ratable_id = identity_parts.pop();
  ratable_type = identity_parts.join('_');
  new Ajax.Request(window['rating_url'], {
    parameters: {
      ratable_type: ratable_type, 
      ratable_id: ratable_id, 
      rating: e.memo.rated
      },
    onComplete: function() {}
  });
});



function dismiss_announcement(id){
  // A list of announcement that the user has dismissed is stored as a comma-separated list of ids in a cookie
  if(jar.get('announcementsSeen')) {
    announcements = jar.get('announcementsSeen').split(',');
  }
  else {
    announcements = [];
  }
  if(! announcements.include(id)){
    announcements.push(id);
  }
  jar.put('announcementsSeen', announcements.join(','));
  Effect.Fade('announcement_'+id);
}


function checkAll(formId){ checkAllOrNone(formId, true) }
function checkNone(formId){ checkAllOrNone(formId, false) }
function checkAllOrNone(formId, checked){
  $$("#" + formId + ' input[type="checkbox"]').each(function(checkbox){
    checkbox.checked = checked;
  });
}
