    function flag_link_clicked(object_id)
    {
    	// is there a form? if so show_flag_form
    	if ($('flag_'+object_id) && $('flag_'+object_id).hasClassName('flag')) {
    		show_flag_form($('flag_'+object_id));
    	} 
    	// otherwise just submit it with confirm_flagged
    	else {
    		confirm_flagged($('flag_'+object_id), $('flag_'+object_id+'_link'));
    	}	
    }

	function confirm_flagged(flag_form, msg_area)
    {
		Overlaid.onConfirm = function(){
			submit_flagged(flag_form, msg_area);
		}.bind(Overlaid); Overlaid.confirm('Confirm', 'Are you sure you want to flag this item?', ' Flag ');  		
    }
    
   	function submit_flagged(flag_form, msg_area)
   	{
		new Ajax.Request(
        		flag_form.action,
                {   method:flag_form.method,
                    parameters:flag_form.serialize(),
                    onSuccess: function(transport, results){
                        if (results.flag)    
                        {
                        	flag_form.hide();
                        	msg_area.innerHTML=results.message;
                        	msg_area.removeClassName('flag');
                        	msg_area.addClassName('flagged');
                        	msg_area.stopObserving("click");
                        }
                        Overlaid.hide();
                    }
                });  
   	}
    	
    function show_flag_form(flag_form)
    {
        selbox = flag_form.down('.reason_select');
        context = selbox.title;
        
        if (selbox.options.length == 0)
	    {
        	new Ajax.Request(
                '/api/json/opinion/utils/flag_reasons/'+context, 
                {   method:'get',
                    onSuccess: function(transport, results) {
	        	        results.each(function(item) {
	        	        	selbox.options[selbox.options.length] = new Option(item.reason,item.id);
	        	        });
                    }
                });
        }
        flag_form.toggle();
    }
    
    function flags_setup() 
    { 
    	$$('.flaggable').each( function(flag_link) {
    		flag_link.stopObserving("click");
    		flag_link.observe("click", function() {
    			flag_link_clicked(flag_link.rel);
    		});
    	});
    }
    
    // setup after load
    document.observe("dom:loaded", function() {
    	flags_setup();
    });
    
    // re-setup after each XMLHTTPRequest
    Ajax.Responders.register({
    	onComplete: function() {
    		flags_setup();
    	}
    });
    