// Javascript for an event submission
// Heavily based on the commenting functionality from wcmComments.js

var wcmEvent = {
    sanitize: function(argText)
    {
		// Allowed tags: <p>, <b>, <u>, <i>, <blockquote>, <br />
        // Formats:
        // <p>tlsdkhsdg</p>
        // sldkghsdg<br />
        // sdlgkhsdgl<br>
        // TODO This looks like very broken regexp
		// (This is a copy of the strategy from wcmComments.js)
		newText = argText.stripScripts().replace(/(<([^\b(p|lockquot|u|i|b)\b^>]+)>)/igm,"");
		
        // If has put in thir own paragraph tags, then add br's to the text if required.
        // Otherwise (and this is the expected case), paragraphise it:
		// (This is a modification of the strategy from wcmComments.js)
        if (newText.indexOf(/\<p\>/i) != -1)
        	newText = newText.replace(/\n/,'<br />');
        else
        {
        	newText = '<p>' + newText.replace(/\n/g, '</p><p>') + '</p>';
        	newText = newText.replace(/\<p\>\<\/p\>/g, '');
        }
        
        return newText;
    },
	
	save: function(argParentId)
    {
        var url = wcmSiteURL + 'ajax/controller.php';
        var params = $('event-'+argParentId+'-replyFormEl').serialize(true);
        
        var callbackAction = '';
        if ($('event-'+argParentId+'-replyFormEl').callbackAction)
        	callbackAction = $('event-'+argParentId+'-replyFormEl').callbackAction.value;
        
        params.evdescription = wcmEvent.sanitize(params.evdescription);
        
        new Ajax.Request(url, {
            parameters: params,
            onSuccess: function(argTransport)
            {
        		// The response will either start with "ERROR:" or will be the HTML message to display.
        		if (argTransport.responseText.substr(0,6) == 'ERROR:') {
        			alert('Event not saved: ' + argTransport.responseText.substr(6));
        		} else {
        			saved = new Element('div');
                    saved.addClassName('savedMsg');
                    saved.innerHTML = argTransport.responseText;
                    saved.hide();
                    
                    $('event-' + argParentId + '-previewEventButtons').update().appendChild(saved);
                    saved.appear();
                    
                    if (callbackAction.length > 0)
                    	eval(callbackAction);
        		}
            }
        });
    }
}
