google.load("gdata","1.s");

// function init()
// {
//     google.gdata.client.init(handleGDError);
//     loadDeveloperCalendar();
// }

/**
 * Loads the Google Developers Event Calendar
 */
// function loadDeveloperCalendar()
// {
//     loadCalendarByAddress('developer-calendar@google.com');
// }

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */
// function loadCalendarByAddress(calendarAddress)
// {
//     var calendarUrl='http://www.google.com/calendar/feeds/'+ calendarAddress + '/public/full';
//     loadCalendar(calendarUrl);
// }

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */
function loadCalendar(calendarUrl)
{
    var service = new google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
    var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
    query.setOrderBy('starttime');
    query.setSortOrder('ascending');
    query.setFutureEvents(true);
    query.setSingleEvents(true);
    query.setMaxResults(10);
    service.getEventsFeed(query,listEvents,handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e)
{
    document.getElementById('jsSourceFinal').setAttribute(
        'style',
        'display:none'
    );
    
    if (e instanceof Error)
    {
        /* alert with the error line number, file and message */
        alert(
            'Error at line '+ e.lineNumber +
            ' in '+ e.fileName +'\n'+
            'Message: '+ e.message
        );
        /* if available, output HTTP error code and status text */
        if(e.cause)
        {
            var status=e.cause.status;
            var statusText=e.cause.statusText;
            alert(
                'Root cause: HTTP error '+ status +' with status text of: '+
                statusText
            );
        }
    }
    else
    {
        alert(e.toString());
    }
}

function getClockTime(now)
{
    var hour   = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var ap = "AM";
    if (hour   > 11) { ap = "PM";             }
    if (hour   > 12) { hour = hour - 12;      }
    if (hour   == 0) { hour = 12;             }
    if (hour   < 10) { hour   =  hour;        }
    if (minute < 10) { minute = "0" + minute; }
    if (second < 10) { second = "0" + second; }
    var timeString = hour + ':' + minute + "" + ap;
    return timeString;
}




/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */
function listEvents(feedRoot)
{
    var entries = feedRoot.feed.getEntries();
    
    // var SelfLink = feedRoot.feed.getFeedLink(); 
    // console.log(SelfLink.getHref());

    var hookID = "";
    
    switch(feedRoot.feed.getFeedLink().getHref())
    {
        case "http://www.google.com/calendar/feeds/oir%40odu.edu/public/full":
            hookID = "upcoming";
            break;
        case "http://www.google.com/calendar/feeds/c69vvalkm02jqvrd4j3s00qj5o%40group.calendar.google.com/public/full":
            hookID = "interhol";
            break;
        case "http://www.google.com/calendar/feeds/4vco5pc137li9qtqq5tukv63qg%40group.calendar.google.com/public/full":
            hookID = "campusev";
            break;
        case "http://www.google.com/calendar/feeds/66u82jvhsv9qbi454hf9qqnctk%40group.calendar.google.com/public/full":
            hookID = "localev";
            break;    
        default:
            throw new Error("Unresolved feedRoot while transforming to hookID");
            break;
    }
    
    
    var eventDiv = document.getElementById(hookID);
    
    /* loop through each event in the feed */
    var len=entries.length;
    for (var i=0; i < len; i++)
    {
        var entry = entries[i];
        var title = entry.getTitle().getText();
        var startDateTime = null;
        var startJSDate = null;
        var endDateTime = null;
        var endJSDate = null;
        
        var times = entry.getTimes();
        
        if(times.length > 0)
        {
            startDateTime = times[0].getStartTime();
            startJSDate = startDateTime.getDate();
            
            endDateTime = times[0].getEndTime();
            endJSDate = endDateTime.getDate();
        }
        
        
        
        var entryLinkHref = null;
        
        if (entry.getLink('related') != null)
        {
            entryLinkHref = entry.getLink('related').getHref();
        }
        
        
        
        var timeString = "";
        
        if(!startDateTime.isDateOnly())
        {
            timeString += " "   + getClockTime(startJSDate) 
                       +  " - " + getClockTime(endJSDate);
        }

                
        
        var entryLocationString = null;
        
        if (entry.getLocations()[0].getValueString()) 
        {
            entryLocationString = entry.getLocations()[0].getValueString();
        };
        
        
        
        var entryBodyString =  null;
        
        if (entry.getContent().getText()) 
        {
            entryBodyString = entry.getContent().getText();
        };
        
        
        
        var divi = document.createElement('div');

        // Work on the title element
        var strongTitle = document.createElement('strong');
        
        if (entryLinkHref != null)
        {
            // if we have a link to the event, create an 'a' element
            entryLink = document.createElement('a');
            entryLink.setAttribute('href',entryLinkHref);
            entryLink.appendChild(document.createTextNode(title));
            strongTitle.appendChild(entryLink);
        }
        else
        {
            // Otherwise, just a flat <strong> element
            strongTitle.appendChild(document.createTextNode(title));
        }
        
        var strongTime = document.createElement('strong');
        var strongLocation = document.createElement('strong');
        
        strongTime.appendChild(document.createTextNode('Time: '));
        strongLocation.appendChild(document.createTextNode('Location: '));

        divi.appendChild(strongTitle);
        divi.appendChild(document.createElement('br'));
        
        if (startJSDate.toDateString() != endJSDate.toDateString()) 
        {
            oneDayEarlier = new Date(endJSDate.getTime() - 86400000);
            
            if(startJSDate.toDateString() != oneDayEarlier.toDateString())
            {
                divi.appendChild(document.createTextNode(
                    startJSDate.toDateString() + " - " + oneDayEarlier.toDateString()
                ));
            } 
            else
            {
                divi.appendChild(document.createTextNode(
                    startJSDate.toDateString()
                ));
            }
        }
        else
        {
            divi.appendChild(document.createTextNode(startJSDate.toDateString()));
        };
        
        divi.appendChild(document.createElement('br'));
        
        if (timeString != "") 
        {
            divi.appendChild(strongTime);
            divi.appendChild(document.createTextNode(timeString));
            divi.appendChild(document.createElement('br'));
        };
        
        if (entryLocationString != null) 
        {
            divi.appendChild(strongLocation);
            divi.appendChild(document.createTextNode(entryLocationString));
            divi.appendChild(document.createElement('br'));
        };
        
        if (entryBodyString != null)
        {
            divi.appendChild(document.createTextNode(entryBodyString));
            divi.appendChild(document.createElement('br'));
        };
        
        divi.appendChild(document.createElement('br'));        
    
        /* append the div item onto the eventDiv  */
        eventDiv.appendChild(divi);
    } 
}


function loadGoogleCalendars()
{
    loadCalendar('http://www.google.com/calendar/feeds/oir@odu.edu/public/full');
    loadCalendar('http://www.google.com/calendar/feeds/c69vvalkm02jqvrd4j3s00qj5o@group.calendar.google.com/public/full');
    loadCalendar('http://www.google.com/calendar/feeds/4vco5pc137li9qtqq5tukv63qg@group.calendar.google.com/public/full');
    loadCalendar('http://www.google.com/calendar/feeds/66u82jvhsv9qbi454hf9qqnctk@group.calendar.google.com/public/full');
}