function get_section_name(name) {
	if (['new_post_comment','new_image_comment','new_buzzer_comment'].indexOf(name) > -1) {
		sect_name = 'new_comment';
	} else {
		sect_name = name;
	}	
	return sect_name;
}
 
function mark_item_read(name, id) {
	if (name == 'new_message') {
		new Ajax.Request('/users/close_message/'+id, {asynchronous:true, evalScripts:true});
	} else if (name == 'new_post_comment') {
		new Ajax.Request('/post/mark_comment_as_read/'+id, {asynchronous:true, evalScripts:true});
	} else if (name == 'new_image_comment') {
		new Ajax.Request('/gallery/mark_comment_as_read/'+id, {asynchronous:true, evalScripts:true});
	} else if (name == 'logged_in') {
		new Ajax.Request('/activity/mark_logged_in_as_read?user_id='+id, {asynchronous:true, evalScripts:true});
	} else if (name == 'buzzer_event') {
		new Ajax.Request('/activity/mark_buzzer_as_read?event_id='+id, {asynchronous:true, evalScripts:true});
	} else if (name == 'new_buzzer_comment') {
		new Ajax.Request('/activity/mark_buzzer_comment_as_read?comment_id='+id, {asynchronous:true, evalScripts:true});
	} else {
		new Ajax.Request('/activity/mark_invitation_as_read?inv_id='+id+'&part='+name.split('_')[1], {asynchronous:true, evalScripts:true});
	}
}

function view_n_link(name) {
	//pri nazhatii na view(n) otkrivajem jego item-i
	Element.show(name); 
	Element.show('view_all_'+name); 
	Element.hide('view_n_'+name);
	close_current_section(Activity.cur_section, Activity.cur_item);
	hide_one_invitation();
	switch_msg_form('', '');
	Activity.cur_section = name;
	Activity.cur_item = '';
}

function hide_one_invitation() {
	if (Activity.cur_inv != '') {
		Element.show(Activity.cur_inv+'_closed');
		Element.hide('invitation_'+Activity.cur_inv.split('_')[1]);
		Element.hide(Activity.cur_inv);
		Activity.cur_inv = '';
	}
}

function close_current_section(sect_name, item_name) {
	if (sect_name != '') {
		Element.hide(sect_name);
	}

	if (item_name != '') {
		//jesli v razdele jest otkritoje sobitie, zakrivajem jego
		info = get_name_id(item_name);
		close_item_fully(info['name'], info['id'], sect_name);
		switch_msg_form_link('', '');
	}
	

	if (sect_name != '') {
		//alert(sect_name);
		if ($('view_n_'+sect_name)) {
			Element.hide('view_all_'+sect_name);
			if (Activity.sections[sect_name].length == 1) {
				//jesli v razdele ostalosj tolko odno sobitie, nado jego otobrazitj sprava ot nazvanija razdela bez view (1)
				if (sect_name == 'new_comment' || sect_name == 'new_message') {
					last_item = Activity.sections[sect_name].first();
					if ($(last_item+'_closed_time')) {	
						Element.show(last_item+'_closed_time');
					}
					Element.hide(last_item+'_closed_text');
					last_item_html = $(last_item).innerHTML;
					Element.remove(last_item);
					new Insertion.Before('view_n_'+sect_name, '<span class="item_closed" id="'+last_item+'">'+last_item_html+'</span>');
				} else if (sect_name == 'logged_in') {
					Element.show(sect_name);
					Element.removeClassName(sect_name, 'friends_bordered');
				} else if (Activity.get_inv_size() == 1) {
					last_item = Activity.sections[sect_name].first();
					Element.show(last_item+'_closed');
				} else {
					Element.show('view_n_'+sect_name);
				}
			} else {
				Element.show('view_n_'+sect_name);
			}
		}

		Activity.cur_section = '';
	} 	
}

function close_item(name, id, sect_name, suffix) {
	//zakritie ljubogo sobitija, ne vazhno kakim sposobom vsegda cherez etu funkciju
	//Activity.counters[sect_name] -= 1;
	Element.hide(name+'_'+id+suffix);
	Activity.remove(sect_name, name+'_'+id);	
	if (Activity.sections[sect_name].length == 0) {
		Element.hide(sect_name);
		if ($('view_all_'+sect_name)) {
			Element.hide('view_all_'+sect_name);
		}
		if (Activity.cur_section == sect_name) {
			Activity.cur_section = '';
		}

		if (sect_name.split('_')[0] == 'invitation' && Activity.get_inv_size()==1) {
			inv_sections = ["new", "accepted", "declined"]
			for(i=0;i<inv_sections.length;i++) {
				//alert(inv_sections[i]);
				if (Activity.sections["invitation_"+inv_sections[i]].length == 1) {
					Element.hide('view_n_invitation_'+inv_sections[i]);
					Element.show(Activity.sections["invitation_"+inv_sections[i]].first()+'_closed')					
				}
			}
		}
	} 
	var cnt_viewed = update_viewed_n(sect_name, +1);	
  //console.log( Activity.sections[sect_name].length);
  //console.log( Activity.counts[sect_name]-cnt_viewed);
	if (Activity.sections[sect_name].length > 4 || (Activity.counts[sect_name]-cnt_viewed > 0)) {
	  $A($R(0,4)).reverse().each(function(i) {
	    if ($(Activity.sections[sect_name][i])) {
	      Element.show(Activity.sections[sect_name][i]);
	    }
	    //console.log(Activity.sections[sect_name][i]);
	  });		 
	  
	} else {
		if ($('view_all_'+sect_name)) {
			$('view_all_'+sect_name).innerHTML = '';
		}	
	}
	
	update_view_n_link(sect_name, -1);
	if (Activity.cur_item == name+'_'+id) {
		Activity.cur_item = '';
	}
	
	if (Activity.cur_inv == name+'_'+id) {
		Activity.cur_inv = '';
	}	
	
	mark_item_read(name, id);
	
	if (Activity.counts[sect_name] > 20 && Activity.sections[sect_name].length == 10) {
	  new Ajax.Request('/activity/preload/', {parameters:Activity.params_for_preload(sect_name)});
	}
	
	//console.log(name+' '+id);
	if (Activity.get_size() == 0) {
		//$('recent_activity_title').innerHTML = '';
		$('recent_activity_wrap').hide();
		//Element.classNames('recent_activity_title').set('activity_title_inactive');
		update_activity();
	}
}

function get_name_id(the_item) {
	//poluchitj iz vida logged_in_222 section_name = logged_in i id=222
	info = [];
	info['name'] = the_item.split('_');
	info['id'] = info['name'].pop();
	info['name'] = info['name'].join('_');
	return info;
}


function close_opened_item(name, sect_name) {
	//zakritie polnostju razvernutogo sobitija
	info = get_name_id(name);
	close_item(info['name'], info['id'], sect_name, '_opened');
}

function close_opened_item_link(name, id) {
	//to zhe samoje, no s drugimi parametrami
	sect_name = get_section_name(name);
	close_item(name, id, sect_name, '_opened');
}

function close_item_link(name, id) {
	//zakritije ne razvernutogo item-a
	sect_name = get_section_name(name);
	close_item(name, id, sect_name, '');
}

function close_invitation_closed(name, id) {
	//zakritije invitation-a, kogda ono odno i otobrazheno sprava ot New Invitations
	sect_name = get_section_name(name);
	close_item(name, id, sect_name, '_closed');
}


function update_view_n_link(x_name, value) {
	//for view (n)
	cnt = $('view_n_'+x_name+'_size');
	if (cnt) {
		old_cnt = parseInt(cnt.innerHTML.slice(1,-1));			
		new_cnt = old_cnt+value;
		if (new_cnt>0) {
			cnt.innerHTML = '('+new_cnt+')';
		} else {
			if ($('view_n_'+x_name)) {
				$('view_n_'+x_name).innerHTML = '';
			}
		}
	}
}

function update_viewed_n(x_name, value) {
	//for viewed n out of all
	cnt = $('view_all_'+x_name+'_size');
	old_cnt = 0;
	if (cnt) {
		old_cnt = parseInt(cnt.innerHTML);			
		cnt.innerHTML = old_cnt+value;
	}
	return old_cnt+value;
}

function close_all_for_current(sect_name) {
	if (Activity.cur_msg != '') {
		switch_msg_form_link('', '');
	} else if (Activity.cur_section == sect_name) {
		if (Activity.cur_item != '') {
			//jesli jestj otkritoje sobitije v etom razdele, zakrivajem jego
			info = get_name_id(Activity.cur_item);
			close_item_fully(info['name'], info['id'], sect_name);
		}	
	} else {
		close_current_section(Activity.cur_section, Activity.cur_item);
	}
}

function open_item_link(name, id) {
	//razvernutj sobitije
	sect_name = get_section_name(name);
	close_all_for_current(sect_name);
	hide_one_invitation();
	
	//pravilnoje otobrazhenije dotted border-ov sverhu i snizu sobitij
	sect_name = get_section_name(name);
	if (!Activity.is_last(sect_name, name+'_'+id)) {
		Element.addClassName(name+'_'+id+'_opened', 'item_border_bottom');
	} else {
		if (Element.hasClassName(name+'_'+id+'_opened', 'item_border_bottom')) {
			Element.removeClassName(name+'_'+id+'_opened', 'item_border_bottom');
		}
	}	

	if (!Activity.is_first(sect_name, name+'_'+id)) {
		Element.addClassName(name+'_'+id+'_opened', 'item_border_top');
	} else {
		if (Element.hasClassName(name+'_'+id+'_opened', 'item_border_top')) {
			Element.removeClassName(name+'_'+id+'_opened', 'item_border_top');
		}
	}
	
	//sobstvenno otkritije sobitija i zapisj v Activity, cto ono - aktivnoje
	Element.show(sect_name); 
	Element.hide(name+'_'+id); 
	Element.show(name+'_'+id+'_opened');
	Activity.cur_item = name+'_'+id;
	Activity.cur_section = sect_name;

}

function close_item_fully(name, id, sect_name) {
	close_item(name, id, sect_name, '');	
	if ($(name+'_'+id+'_opened')) {
		Element.hide(name+'_'+id+'_opened');
	}
	if ($(name+'_'+id+'_closed')) {
		Element.hide(name+'_'+id+'_closed');
	}	
}

function hide_item_after_send_msg(name, id) {
	sect_name = get_section_name(name);
	//alert(sect_name+'; '+name+'_'+id);
	//alert(Activity.cur_section+'; '+Activity.cur_item);
	if (Activity.cur_section==sect_name && Activity.cur_item==name+'_'+id){
		close_item_fully(name, id, sect_name);
	} 
} 

function hide_message_sent_msg(name, id) {
	$(name+"_"+id+"_msg_sent").innerHTML = '';
	if($('send_msg_inv_new_'+id)) {
		//Element.hide('send_msg_inv_new_'+id);
		$(name+'_'+id+'_send_msg').innerHTML = '';
		Element.show(name+"_"+id+"_send_msg_links");		
	}
}

function after_send_msg(name, id) {
	sect_name = get_section_name(name);
	//console.log(name, id);
	if (sect_name == 'new_comment') {
	  if ($("new_buzzer_comment_"+id)) {
    	$(name+"_"+id+"_msg_sent").innerHTML='comment sent';
  	} else {
		$(name+"_"+id+"_msg_sent").innerHTML='reply sent';
		}
	} else if (sect_name == 'buzzer_event') {
	  if ($("buzz_question_"+name+"_"+id)) {
	    $(name+"_"+id+"_msg_sent").innerHTML='answer sent';
	  } else {
		  $(name+"_"+id+"_msg_sent").innerHTML='comment sent';
		}
	} else{
		//alert(name+"_"+id+"_msg_sent");
		//console.log(name+"_"+id+"_msg_sent");
		$(name+"_"+id+"_msg_sent").innerHTML='message sent';
		if ($(name+"_"+id+"_msg_sent_closed")) {
			$(name+"_"+id+"_msg_sent_closed").innerHTML='message sent';
		}
	}
	if (sect_name == 'invitation_new' && $('send_msg_inv_new_'+id)) {
		Element.hide(name+"_"+id+"_send_msg_links");
		Element.hide(name+"_"+id+"_send_msg_link");
		Element.show(name+"_"+id+"_create_msg_link");
		$("if_inv_sent_"+id).innerHTML='1'
	}
	if ($(name+"_"+id+"_create_msg_link_closed")) {
		Element.hide(name+"_"+id+"_create_msg_link_closed");
	}


	switch_msg_form(name, id);
	if ($(name+'_'+id+'_opened')) {
		Element.hide(name+'_'+id+'_opened');
		Element.show(name+'_'+id);
	}

	if (!$('view_n_'+sect_name) && sect_name != 'logged_in') {
		Element.hide(sect_name);
	}

	if (Activity.get_inv_size() == 1 && Activity.sections[sect_name].length == 1){
		if (sect_name != 'invitation_new' || (Element.visible(name+'_'+id+'_accepted') || Element.visible(name+'_'+id+'_declined'))) {
		  if ($(name+'_'+id+'_closed')) {
  			Element.hide(name+'_'+id);
  			Element.show(name+'_'+id+'_closed');
  			Element.hide(name); 
  		}
		} else {
			Element.show(name+'_'+id);
			Element.show(name);
		}
	}		


	
	if (sect_name == 'invitation_new') {
		if (Element.visible(name+'_'+id+'_accepted') || Element.visible(name+'_'+id+'_declined')) {
			Activity.cur_section = sect_name;
			Activity.cur_item = name+"_"+id;
			setTimeout("hide_item_after_send_msg('"+name+"', "+id+")", 2000);
		} else {
			setTimeout("hide_message_sent_msg('"+name+"', "+id+")", 2000);
		}
	} else {
		Activity.cur_section = sect_name;
		Activity.cur_item = name+"_"+id;
		setTimeout("hide_item_after_send_msg('"+name+"', "+id+")", 2000);
	}
}

function toggle_hidden_comment(name, id) {
	Element.toggle(name+'_'+id+'_show'); 
	Element.toggle(name+'_'+id+'_hide'); 
	Element.toggle('hidden_pic_'+name+'_'+id);
}

function approve_comment(name, id) {
	Element.hide(name+'_'+id+'_approve'); 
	Element.show(name+'_'+id+'_approved'); 
}

function check_typed_length(parent, textarea, size) {
  if (!size) {
    size = 1000;
  }
	$(parent+'_send_msg_counter').value = size-textarea.value.length;
	if (textarea.value.length>0) {
		$(parent+'_send_msg_submit').disabled='';
	} else {
		$(parent+'_send_msg_submit').disabled='disabled';
	}
	if (textarea.value.length > size) {
		textarea.value = textarea.value.substring(0, size-1);
	}
}

function choose_reply_button(parent, textarea) {
  //console.log(parent, textarea);
  //console.log("choose_reply_button function");
	$(parent+'_send_msg_submit').src=(textarea.value.length == 0 ? '/images/design/submitcomment_bw.gif' : '/images/design/submitcomment.gif'); 
}

function check_submit_length(parent) {
	if($(parent+'_send_msg_counter').value<0) {
		return confirm('Message text too long, it will be truncated to 1000 symbols,do you wish to send anyway?');
	}	else {
		return true;
	}
}

function switch_msg_form(name, id) {
	if (Activity.cur_msg != '') {
		Element.hide(Activity.cur_msg+'_send_msg');
	}
	if (name == '' || Activity.cur_msg == name+'_'+id) {
		Activity.cur_msg = '';
	} else {
		Activity.cur_msg = name+'_'+id;
		Element.show(name+'_'+id+'_send_msg');
		if (Element.hasClassName(name+'_'+id+'_send_msg', 'can_border')) {
			if (!Activity.is_last(name, name+'_'+id) || (name == 'logged_in' && !Element.hasClassName(name, 'friends_bordered'))) {
				Element.addClassName(name+'_'+id+'_send_msg', 'msg_bordered');
			} else {
				Element.removeClassName(name+'_'+id+'_send_msg', 'msg_bordered');
			}
		}
	}
}

function switch_msg_form_link(name, id) {
	sect_name = get_section_name(name);
	if (Activity.cur_section != sect_name) {
		close_current_section(Activity.cur_section, Activity.cur_item);
	} else if (Activity.cur_item != '' && Activity.cur_item != name+'_'+id) {
		old_name = Activity.cur_item.split('_');
		old_id = old_name.pop();
		old_name = old_name.join('_');
		old_sect_name = get_section_name(old_name);
		close_item_fully(old_name, old_id, old_sect_name);
	}
	switch_msg_form(name, id);
}

function open_one_invitation(name, id) {
		close_all_for_current(name);
		Element.hide(name+'_'+id+'_closed');
		Element.show(name);
		Element.show(name+'_'+id);
		Activity.cur_inv = name+'_'+id;
}

function create_msg_form(link, name, id) {
	if ($(name+'_'+id+'_closed')) {
		open_one_invitation(name, id);
	} else {
		Element.hide(link); 
		Element.show(name+'_'+id+'_send_msg_link'); 
	}
	switch_msg_form_link(name, id);
}

function invitation_new_done(name, id, accepted) {
	if ($("if_inv_sent_"+id).innerHTML=='1') {
		close_item(name, id, name, '');
	}
	if (accepted) {
		if (Element.visible(name+'_'+id+'_declined')) {
			Element.hide(name+'_'+id+'_declined');
			Element.show(name+'_'+id+'_decline');
		}
		Element.hide(name+'_'+id+'_accept');
		Element.show(name+'_'+id+'_accepted');		
	} else {
		if (Element.visible(name+'_'+id+'_accepted')) {
			Element.hide(name+'_'+id+'_accepted');
			Element.show(name+'_'+id+'_accept');
		}
		Element.hide(name+'_'+id+'_decline');
		Element.show(name+'_'+id+'_declined');
	}
	mark_item_read(name, id);
}

function buzzer_invitation_done(name, id, accepted) {
  setTimeout("hide_item_after_send_msg('"+name+"', "+id+")", 1000);
	if (accepted) {
		Element.hide(name+'_'+id+'_accept');
		Element.show(name+'_'+id+'_accepted');		
	} else {
		Element.hide(name+'_'+id+'_decline');
		Element.show(name+'_'+id+'_declined');
	}
	//mark_item_read(name, id);
}

function buzzer_invitation_action(id, accepted, group_id) {
  new Ajax.Request('/buzzers/acc_group?buzzer_group_id='+group_id, {
    asynchronous:true, evalScripts:true, onComplete:function(request){
      buzzer_invitation_done('buzzer_event', id, accepted);}
  }); 
  
	return false;
}

//name+'_'+id+'_accept').innerHTML=='Accepted!'

function update_activity() {
	if ((Activity.cur_section=='' || Activity.cur_section=='logged_in') && Activity.cur_item=='' && Activity.cur_msg=='' && Activity.cur_inv==''){
		new Ajax.Updater('recent_activity', '/activity/activity_update', {asynchronous:true, evalScripts:true})
	}
}

var Activity = {
  sections: [],
  counts: [],
  cur_item: '',
  cur_section: '',
  cur_msg: '',
  cur_inv: '',
  sect_names: ['logged_in', 'new_message', 'new_comment', 'invitation_new', 'invitation_accepted', 'invitation_declined'], //, 'buzzer_event'],


	init: function() {
		for(name in this.sect_names) {
			this.sections[name] = [];
		}
		this.cur_item = '';
		this.cur_section = '';
		this.cur_msg = '';
		this.cur_inv = '';
	},


	clear: function() {
		for(i=0;i<this.sect_names.length;i++) {
			name = this.sect_names[i];
			//alert(name);
			//console.log(name);
			if ($('view_n_'+name)) {
				Element.hide('view_all_'+name); 
				Element.hide('view_n_'+name);
			}
			Element.hide(name);
			if (this.sections[name].length == 1) {
				the_item = this.sections[name].first();
				//alert(this.sections[name].first());
				if ($(the_item)) {
					Element.hide(the_item);
				}
				if ($(the_item+'_opened')) {
					Element.hide(the_item+'_opened');
				}
				if ($(the_item+'_closed')) {
					Element.hide(the_item+'_closed');
				}
			}
			this.sections[name] = [];
		}
		this.cur_item = '';
		this.cur_section = '';
		this.cur_msg = '';
		this.cur_inv = '';
		$('recent_activity_wrap').hide();
	},
	
	close: function() {
	  $('recent_activity_wrap').hide();
	},

  get_size: function() {
	var all_size = 0;
	for(i=0;i<this.sect_names.length;i++) {
		name = this.sect_names[i];
		//alert(this.counters[name]);
		all_size += this.sections[name].length;
		//all_size += this.counters[name];
	}
	return all_size;
  },
  
  show_five_items: function(sect_name){
	  $A($R(0,4)).reverse().each(function(i) {
	    if ($(Activity.sections[sect_name][i])) {
	      Element.show(Activity.sections[sect_name][i]);
	    }
	    //console.log(Activity.sections[sect_name][i]);
	  });	
  },
  
  get_inv_size: function() {
		return this.sections['invitation_new'].length+this.sections['invitation_accepted'].length+this.sections['invitation_declined'].length
  },  
	
  add: function(section, item) {
 		this.sections[section].push(item);
  },
  
  remove: function(section, item) {
 		this.sections[section] = this.sections[section].without(item);
  },  
  
  set_section: function(section, items, count) {
  	this.sections[section] = items;
  	this.counts[section] = count;
  },
  
  is_first: function(section, item) {
  	if (this.sections[section].first() == item) {
  		return true;
  	} else {
  		return false;
  	}
  },
  
  is_last: function(section, item) {
  	if (this.sections[section].last() == item) {
  		return true;
  	} else {
  		return false;
  	}
  },
  
  params_for_preload: function(section) {
    if (section != 'new_comment') {
      var params = {
        name: section,
        ids: Activity.sections[section].map(function(i) {
          return i.split('_').last();
        }).join(',')
      };
    } else {
      var params = {
        name: section, 
        post_ids: [],
        image_ids: [], 
        buzzer_ids: []
      };
      Activity.sections[section].each(function(i) {
        i = i.split('_'); 
        params[i[1]+'_ids'].push(i.last());
      });
      params.post_ids =  params.post_ids.join(',');
      params.image_ids =  params.image_ids.join(',');
      params.buzzer_ids =  params.buzzer_ids.join(',');
    }
    return params;
  },
  
  update_event_time: function(name, id, time) {
    setTimeout(function(){
      $(name+'_'+id+'_opened').down('div.msg_contents td').innerHTML = time;
    }, 1000);
  },
  
  update_message_time: function(name, id, time) {
    setTimeout(function(){
      $(name+'_'+id+'_opened').down('div.msg_contents div').innerHTML = time;
    }, 1000);
  }
  
};
