PERSONALCALENDAR = {
    'oscLoginCookieName':'oscLoginCookie',
    'scheduleditems':null,
    'eventsWithSelectedAbstractsOneShot':null,
    
    /*utilitymethod for updating the "add/remove" buttons beneath the specified
    root element. This is used to update all the events once the list of scheduled
    items is first loaded, and to update the list of abstracts when an abstractlist
    is added via ajax.
    */
    'updateAddAndRemoveButtons': function(rootelement) {
        var myscheduleCalenderContentHolder = $("#myscheduleCalenderContentHolder");
        if( myscheduleCalenderContentHolder.length !== 0 ) {
            // The "My schedule" tab has been selected. This means that we should 
            // always enable the "remove from schedule"-buttons.
            $(".removeFromScheduleButton",rootelement).show();
        } else {
            if(PERSONALCALENDAR.scheduleditems !== null) {
                var conferenceURL = $(".conferenceurllink").attr("href");
                $(".addToScheduleButton",rootelement).show();
                $(".removeFromScheduleButton",rootelement).hide();
                $(".onScheduleIcon",rootelement).remove();
                var scheduleditems = PERSONALCALENDAR.scheduleditems;
                if( PERSONALCALENDAR.eventsWithSelectedAbstractsOneShot !== null ) {
                    scheduleditems = scheduleditems.concat(PERSONALCALENDAR.eventsWithSelectedAbstractsOneShot);
                    // Clear the oneshot list. It is only used at the initial loading of the page
                    PERSONALCALENDAR.eventsWithSelectedAbstractsOneShot = null;
                }
                
                // Note that when we search for items that are selected, we must 
                // search from the rootelement's parent, in order to enable
                // the rootelement itself, if needed.
                rootelementParent = rootelement.parent();
                for (var i = 0; i < scheduleditems.length; i++){ 
                    var topicserial = scheduleditems[i];
                    topicserial = topicserial.replace(/(:|\.)/g,'\\$1');
                    var selectedItem = $("."+topicserial,rootelementParent);
                    if(selectedItem.length > 0 ){
                        $(".addToScheduleButton",selectedItem).hide();
                        $(".removeFromScheduleButton",selectedItem).show();
                        var titleElements = [];
                        var titleelement = $(".event-time-and-code",selectedItem);
                        if( titleelement.length === 0 ) {
                            titleelement = $(".abstract-link",selectedItem);
                            // This is an abstract, so we must add the icon to the parent event, too
                            var eventElement = selectedItem.parents("li.event");
                            if(eventElement.length > 0 ) {
                                var eventTitleElement = $(".event-time-and-code",eventElement);
                                titleElements.push(eventTitleElement);
                            }
                        }
                        titleElements.push(titleelement);                        
                        var j;                    
                        for(j=0;j<titleElements.length;j++) {
                            titleelement = titleElements[j];
                            var existingIcon = titleelement.siblings(".onScheduleIcon");
                            if( existingIcon.length === 0 )  {
                                titleelement.before('<img class="onScheduleIcon" src="' + conferenceURL + '/OSC_images/onScheduleIcon.png" />');
                            }
                        }
                        
                    }
                }
            }
        }
    },
    'onAbstractLightBoxComplete' : function(currentArray, currentIndex, currentOpts) {
        var lightbox = $("#abstract-lightbox");
        PERSONALCALENDAR.updateAddAndRemoveButtons(lightbox.parent());
    },

    'getTopicSerialFromParents' : function(element) {
        var serialRE = /\d+\.\d+/;
        var parents = element.parents();
        var i;
        for(i=0;i<parents.length;i++) {
            var parent = parents[i];
            parent = $(parent);
            var classes = parent.attr("class");
            
            var match = serialRE.exec(classes);
            if( match ) {
                return match[0];
            }
        }

        return null;    
    },

    // This function is called when the user wants to add an event or an abstract
    // to his/her personal calendar.
    'onAddToScheduleButtonClicked' : function(event) {
        event.preventDefault();
        event.stopPropagation();
        var conferenceURL = $(".conferenceurllink").attr("href");
        
        var eventtarget = $(event.target);
        var topicserial = PERSONALCALENDAR.getTopicSerialFromParents(eventtarget);
            
        
        PROGRAMME.blockUI();
        var postURL = conferenceURL + "/personalcalendar/add";
        //alert("onAddToScheduleButtonClicked() running for topicserial " + topicserial);
        
        
        var topicserialClass = topicserial.replace(/(:|\.)/g,'\\$1');
        var elementsToUpdate = $("."+topicserialClass);
        // Add any "event" parent elements (only applies to abstracts)
        elementsToUpdate = elementsToUpdate.add(elementsToUpdate.parents(".event"));
        
        
        $.ajax({'url':postURL,
                'type': "POST",
                'timeout':3600000,
                'dataType':'json',
                'data': {'topicserial' : topicserial},
                'cache':false,
                'success':function(response){
                    if( response == "notloggedin" ) {
                        // The user isn't logged in, so redirect to the loginpage
                        window.location = conferenceURL + "/personalcalendar/myschedule?topictoadd=" + topicserial;
                        return;
                    }
                    
                    if( $.inArray(topicserial,PERSONALCALENDAR.scheduleditems) == -1 ) {
                        PERSONALCALENDAR.scheduleditems.push(topicserial);
                    }
                    PERSONALCALENDAR.updateAddAndRemoveButtons(elementsToUpdate );
                    PROGRAMME.unblockUI();
                },
                'error':function(request, error) {
                    humanMsg.displayMsg("Failed to add the topic " + topicserial + " to your personal schedule: " + error);
                    PROGRAMME.unblockUI();
                }
                });


        return false;
    },
    
    
    // This function is called when the user wants to remove an event or an abstract
    // from his/her personal calendar.
    'onRemoveFromScheduleButtonClicked' : function(event) {
        event.preventDefault();
        event.stopPropagation();
        
        PROGRAMME.blockUI();
        var eventtarget = $(event.target);
        var topicserial = PERSONALCALENDAR.getTopicSerialFromParents(eventtarget);
        var conferenceURL = $(".conferenceurllink").attr("href");
        var postURL = conferenceURL + "/personalcalendar/remove";

        var topicserialClass = topicserial.replace(/(:|\.)/g,'\\$1');
        var elementsToUpdate = $("."+topicserialClass);
        // Add any "event" parent elements (only applies to abstracts)
        elementsToUpdate = elementsToUpdate.add(elementsToUpdate.parents(".event"));


        $.ajax({'url':postURL,
                'type': "POST",
                'timeout':3600000,
                'dataType':'json',
                'data': {'topicserial' : topicserial},
                'cache':false,
                'success':function(response){
                    if( response == "notloggedin" ) {
                        // The user isn't logged in, so redirect to the loginpage
                        window.location = conferenceURL + "/personalcalendar/myschedule";
                        return;
                    }

                    var myscheduleCalenderContentHolder = $("#myscheduleCalenderContentHolder");
                    if(myscheduleCalenderContentHolder.length == 1 ) {
                        // The "My schedule" tab has been selected. This means that we should just remove the
                        // item from the page.
                        PROGRAMME.unblockUI();
                        $.fancybox.close();
                        var elementsToRemove = $("li." + topicserialClass);
                        elementsToRemove.slideUp(500,function(){$(this).remove();});
                        
                    } else {
                        // One of the normal "day"-pages has been selected, so we must remove the "has been selected"-icon
                        // from the removed item.
                        PERSONALCALENDAR.scheduleditems = $.grep(PERSONALCALENDAR.scheduleditems, function(val) { return val != topicserial; });
                        PERSONALCALENDAR.updateAddAndRemoveButtons(elementsToUpdate);
                        PROGRAMME.unblockUI();
                    }
                    
                },
                'error':function(request, error) {
                    humanMsg.displayMsg("Failed to remove the topic " + topicserial + " from your personal schedule: " + error);
                    PROGRAMME.unblockUI();
                }
                });

        return false;
    },



    
    'initializeMySchedulePageIfNeeded' : function() {
        var myscheduleCalenderContentHolder = $("#myscheduleCalenderContentHolder");
        var loadingImg = $(".loadingimg",myscheduleCalenderContentHolder);
        if(myscheduleCalenderContentHolder.length == 1 ) {
            // the "My schedule" tab has been selected
            // 
            var conferenceURL = $(".conferenceurllink").attr("href");
            var myscheduleURL = conferenceURL + "/personalcalendar/osc_myschedule_contents";
            $.ajax({ url:myscheduleURL,
                    timeout:3600000,
                    cache:false, // we cannot cache this, since we need a fresh value. TODO: maybe add the
                                 // email and a "lastmodifiedtime" parameter (that can be stored in the cookie)
                                 // to the url? In that way we could enable caching.
                    success:function(calendarContent) {
                        if( calendarContent == "notloggedin") {
                            // The user hasn't been logged in, so hide the loading image and enable the login-form.
                            loadingImg.hide();
                            $("#osc_sendemailformHolder").show();
                        } else {
                            if( calendarContent == "" ) {
                                calendarContent = '<p class="errormsg">Failed to load the personal calendar</p>';
                            }
                            loadingImg.replaceWith(calendarContent);

                            $(".abstract-link",myscheduleCalenderContentHolder).fancybox({
                                'hideOnContentClick': false,
                                'autoDimensions': false,
                                'width': 600,
                                'height': 400,
                                'onComplete' : PERSONALCALENDAR.onAbstractLightBoxComplete
                            });
                            
                            

                        }
                    },
                    dataType:"html",
                    error:function(request, error) {
                        loadingImg.replaceWith('<p class="errormsg">Failed to load the personal calendar: " + error + "</p>');
                    }
            });
        }
    }
    

};

$(document).ready(function () {
    /* 
    This tests checks if the "My schedule" tab is present. The tabs are generated by the
    OSCConference.programinfo.ProgramInfo.getDayList() method. If the "My schedule" tab isn't
    present, the javascript shouldn't enable the personal calendar functionality.
    */
    var myscheduleTab = $(".calendarTabs li.myschedule");
    var enablePersonalCalendar = myscheduleTab.length > 0;
    if( !enablePersonalCalendar ) {
        return;
    }


    /* Try to download the personal schedule. If the user isn't logged on, this will return "notloggedin" */
    var scheduleditemsLink = $("a.scheduleditemsLink");
    var myscheduleCalenderContentHolder = $("#myscheduleCalenderContentHolder");
    if(    (myscheduleCalenderContentHolder.length == 0) // don't load the scheduleditems list on the myschedule page
        && (scheduleditemsLink.length > 0 )  // only load the schedule if the "scheduleditemsLink" placeholder is present
        ){
        var scheduleditemsURL = scheduleditemsLink.attr("href");
        var scheduleditemsLinkParent = scheduleditemsLink.parent();
        var conferenceURL = $(".conferenceurllink").attr("href");
        var loadingimg = $(".loadingimg").first();
        loadingimg.show();
        
        
        $.ajax({'url':scheduleditemsURL,
                'timeout':3600000,
                'dataType':'json',
                'cache':false,
                'success':function(result){
                    var rootelement = $("body");
                    if( result == "notloggedin") {
                        PERSONALCALENDAR['scheduleditems'] = null;
                        /* The user is not logged in, but we want to display the "Add to your schedule" buttons
                        anyway, in order to make it easy for novice users to discover the personal calendar
                        functionality. (The user will be asked to log in when he clicks an "Add"-button.) */
                        PERSONALCALENDAR['scheduleditems'] = [];                        
                        PERSONALCALENDAR.updateAddAndRemoveButtons(rootelement);
                        
                    } else {
                        var selectedCalendarItemSerials = result.selectedCalendarItemSerials;
                        var eventsWithSelectedAbstracts = result.eventsWithSelectedAbstracts;
                        PERSONALCALENDAR['scheduleditems'] = selectedCalendarItemSerials;
                        PERSONALCALENDAR['eventsWithSelectedAbstractsOneShot'] = eventsWithSelectedAbstracts;
                        /* Add the "is in personal calendar" icon to all selected 
                           events and abstracts */
                        PERSONALCALENDAR.updateAddAndRemoveButtons(rootelement);
                    }
                    loadingimg.hide();
                    
                },
                'error':function(request, error) {
                    humanMsg.displayMsg("Failed to load the personal calendar: " + error);
                    loadingimg.hide();
                }
                });
    }

    $(".addToScheduleButton").click(PERSONALCALENDAR.onAddToScheduleButtonClicked);
    $(".removeFromScheduleButton").click(PERSONALCALENDAR.onRemoveFromScheduleButtonClicked);
    /* use the "live" eventbinding method to add the eventhandlers to future buttons as well.*/
    $(".addToScheduleButton").live('click',PERSONALCALENDAR.onAddToScheduleButtonClicked);
    $(".removeFromScheduleButton").live('click',PERSONALCALENDAR.onRemoveFromScheduleButtonClicked);
    
    PERSONALCALENDAR.initializeMySchedulePageIfNeeded();
    
});


