
// build class which can attach to all elements in a named div to a click event

var TessCal = {
    init: function (path) {
        TessCal._mainDiv = $('tessCal');
        if (TessCal._path == null)
            TessCal._path = path;
        TessCal.attachClickEvents();
    },

    attachClickEvents: function() {
        var anchors = $$('div a.ajaxlink');        
        anchors.invoke('observe', 'click', TessCal.handleClick);       
    },

    handleClick: function(e) {
        // figure out the href to use, swap the path the ~/svc/calendar.aspx, a use an XHttpRequest to 
        // call the page. 
        // swap out the div contents on the page with the results.
        var e = e || window.event;
        Event.stop(e);
        var link = Event.findElement(e, 'a'); 
        TessCal._mainDiv.innerHTML = "<fieldset class='loading_field'>Loading...</fieldset>";         
        TessCal.loadCalendar(link.search);              
    },
    
    loadCalendar: function(optionalArgs)
    {
        if (!optionalArgs)
        {
            optionalArgs = "";
        }
        
        new Ajax.Request(TessCal._path + optionalArgs,{
            method: 'get',
            onComplete: function(results) {
                if (results.readyState == 4)
                {
                    var cal = results.responseText;
                    var index1 = results.responseText.indexOf('<div id="tessCal">')+18;
                    var index2 = results.responseText.indexOf('</table></div>')+8;
                    if (index2 <= 9)
                    {
                        index2 = results.responseText.indexOf('</dl></fieldset>')+16;
                    }
                    if ( index1 == (18 + -1) || 
                         index2 < index1)
                    {
                        TessCal._mainDiv.innerHTML = "<div class='error'>There was a problem loading the calendar</div>";
                    } else
                    {
                        cal = cal.substring(index1,index2);
                        TessCal._mainDiv.innerHTML = cal;
                        TessCal.init();
                    }  
                    
                }                
            }
        });
    
    }
}

