/**
 * Global variabels
 */
memberArray  = new Array();
groupId      = null;
eventId      = null;
globalEvents = new Array();

/**
 * Checking if form was submitted with the right values
 */
function validateTimeFormat(str) {
    if ((str.match(/^(\d{1,2}).(\d{2})$/)) && (RegExp.$1<24 && RegExp.$2<60)) { return true; }
    return false;
}

function validateYearFormat(str) {
    if ((str.match(/^(\d{4})-(\d{2})-(\d{2})$/)) && (RegExp.$2<=12)) {
        if (leapYear(RegExp.$1)) { var days=29; } else { var days=28; }
        if (RegExp.$2==1 && RegExp.$3<=31) return true;
        else if (RegExp.$2==2 && RegExp.$3<=days) return true;
        else if (RegExp.$2==3 && RegExp.$3<=31) return true;
        else if (RegExp.$2==4 && RegExp.$3<=30) return true;
        else if (RegExp.$2==5 && RegExp.$3<=31) return true;
        else if (RegExp.$2==6 && RegExp.$3<=30) return true;
        else if (RegExp.$2==7 && RegExp.$3<=31) return true;
        else if (RegExp.$2==8 && RegExp.$3<=31) return true;
        else if (RegExp.$2==9 && RegExp.$3<=30) return true;
        else if (RegExp.$2==10 && RegExp.$3<=31) return true;
        else if (RegExp.$2==11 && RegExp.$3<=30) return true;
        else if (RegExp.$2==12 && RegExp.$3<=31) return true;
    }
    return false;
}

function leapYear(year) {
    if (year%400 == 0) return true;
    if (year%100 == 0) return false;
    if (year%4 == 0) return true;
    return false;
}

globalCalendarEvents = new Array();
globalRelativeWidth = true;

/**
 * Fetches a set of events through ajax and hands them of for displaying
 */
function loadCalendarEvents(calendarUrl, relativeWidth)
{
    globalRelativeWidth = (relativeWidth == null) ? true : relativeWidth;
    new Ajax.Request(calendarUrl, {
        parameters: '',
        onSuccess: displayEvents,
        onFailure: displayAjaxError
        });
}

function displayEvents(t)
{
    var serverData = eval('(' + t.responseText + ')');
    serverData.events.each(function(myEvent) {

        dayNode = $('calendarDay' + myEvent.date);
        if (typeof(dayNode) != 'object') {
            return;
        }
        eventNode = Builder.node('li', {
            className: 'horizontalEvent',
            style: 'background-color: #'+myEvent.color+'; color: #'+myEvent.font_color,
            id: 'event' + myEvent.id,
            onmouseover: 'popupEventDetails(this, ' + myEvent.id + ', \'' + escape(myEvent.title) + '\', \'' + myEvent.start_time + '\', \'' + myEvent.stop_time + '\', \'' + escape(myEvent.location) + '\', \'' + escape(typeof(myEvent.contents) == 'string' ? myEvent.contents : '') + '\');',
            onmouseout: 'hideEventDetails();',
            onclick: "window.location = '/group/" + groupId + "/eventId/" + myEvent.id + "';"
            });
        almanacPixelWidth = dayNode.offsetWidth;
        if ((myEvent.start_time != null) && (myEvent.start_time.length > 0) && (myEvent.stop_time != null) && (myEvent.stop_time.length > 0)) {
            if (globalRelativeWidth) {
                pixelOffset = time2PixelOffset(myEvent.start_time, almanacPixelWidth);
                eventNode.style.left = pixelOffset + 'px';
                eventNode.style.width = time2PixelOffset(myEvent.stop_time, almanacPixelWidth) - pixelOffset + 'px';
            } else {
                eventNode.innerHTML = myEvent.start_time + '-' + myEvent.stop_time;
            }
        } 

        if (compactEvents) {
            eventNode.innerHTML = eventNode.innerHTML + '<br />' + myEvent.title.substr(0, 10);
        } else {
            eventNode.innerHTML = eventNode.innerHTML + myEvent.title;
        }
        eventNode.style.display = 'none';

        dayNode.appendChild(eventNode);
        globalCalendarEvents[myEvent.calendar_id].push(eventNode);
        new Effect.Appear(eventNode, {duration: 0.5});
    });
}

function popupEventDetails(domObj, id, title, startTime, stopTime, location, contents)
{
    var popupDiv = $('popupDiv');
    var popupHtml;
    if (popupDiv.style.display != 'none') {
        popupDiv.style.display = 'none';
    }
    popupHtml = '<div style="font-weight: 800;">' + unescape(title) + '</div>';
    if (startTime != 'null') {
        popupHtml += '<p style="font-weight: 800">' +  startTime;
        if (stopTime != 'null') {
            popupHtml += ' &ndash; ' + stopTime;
        }
        popupHtml += '</p>';
    }
    popupHtml += '<p>' + unescape(contents) + '</p>';
    if (contents != 'false') { popupDiv.innerHTML = popupHtml; }
    popupDiv.style.top = (domObj.offsetTop + domObj.offsetHeight) + 'px';
    popupDiv.style.left = (domObj.offsetLeft) + 'px';
    popupDiv.style.width = '200px';
    popupDiv.style.display = 'block';
}

function hideEventDetails()
{
    $('popupDiv').style.display = 'none';
}

function hidePopup()
{
    new Effect.BlindUp('popupDiv', {duration: 0.5});
}

/**
 * Assumes a time format of HHxMM... and that the day starts att 06:00 and ends at 21:00 
 */
function time2PixelOffset(timeOfDay, width)
{
    hours = parseInt(timeOfDay.substr(0, 2), 10);
    minutes = parseInt(timeOfDay.substr(3, 2), 10);
    sumMinutes = hours * 60 + minutes;
    
    timeOffset = 60 * 8;
    minutesPerDay = 60 * (23 - 8); // end of day - start of day
    minutesPerPixel = minutesPerDay / width;

    pixels = Math.round((sumMinutes - timeOffset) / minutesPerPixel);
    if (pixels < 0) pixels = 0;
    if (pixels > width) pixels = width;
    return pixels;
}

function hideCalendar(id)
{
    globalCalendarEvents[id].each(function(eventNode) {
        new Effect.Fade(eventNode, {duration: 0.5});
        });
}

function showAllCalendars()
{
}

function showCalendar(id)
{
    var RegExp = /^[0-9]+$/;
    if (id == 'allCalendars') {
        for (i in globalCalendarEvents) {
            if (i.match(RegExp)) {
                globalCalendarEvents[i].each(function(eventNode) {
                    new Effect.Appear(eventNode, {duration: 0.5});
                    });
            }
        }
    } else {
        for (i in globalCalendarEvents) {
            if (i.match(RegExp) && i != id) {
                globalCalendarEvents[i].each(function(eventNode) {
                    new Effect.Fade(eventNode, {duration: 0.5});
                    });
            }
        }
        globalCalendarEvents[id].each(function(eventNode) {
            new Effect.Appear(eventNode, {duration: 0.5});
            });
    }
}

function editEvent(id)
{
    window.location = '/group/' + globalGroupId + '/event/' + id + '/edit';
}

