/**
 * @author Neon 'Thi' Zero  thi@websitebuilder.co.nz
 */
/**
 * Calendar Function for WebWidgets to display any efents thats been added to the events list.
 * if no events appear, a reminder of Add Event will appear on Today...
 * The Calendar will display from the first events starting month (in the future) till the last events ending month with a maximum span of 13 months.
 * if an event starts befire the current month, and ends in the future, the calendar will start from the current month.
 *
 */
var monthArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
monthArrayShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
dayArray = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
daysInMonthArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
dayNumberArray = [7, 1, 2, 3, 4, 5, 6]; // sunday, monday, tuesday, wednesday, thursday, friday, saturday... Date.getDay returns a number 0-6 (week starting from sunday). but the calendar week starts on monday.
var elementId = 0;
var calendar = new Array();
dayArraySystem = ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

if (typeof(window['events']) == "undefined") {
    document.write('Sorry, but there are no events to list currently...');
	
}else if(events.length == 0){
	document.write('Sorry, but there are no events to list currently...');
	
}else {
    calendarMain();
}
function calendarMain(){
	
    /**
     Checks if any events exist, if not, do nothing. if do, then creates the calendar...
     **/
    day = new Date();
    thisMonth = new Date(day.getFullYear(), day.getMonth(), 1);
    startMonth = new Date(getStartMonth(events, thisMonth));
    
    
    endMonth = new Date(getEndMonth(events, startMonth, thisMonth));
    calendar = createCalendar(startMonth, endMonth);
    generateEvents(events, startMonth, endMonth);
    data = drawCalendar(startMonth);
     
	 
	 /**
    
     This is where the write to file(content area) come in... the data object just need to be written in....
    
     **/
    
    document.write(data);
    
    // var dummy = document.createTextNode(data);
    // document.body.appendChild(dummy);

	
}

function drawCalendar(startMonth){
    /**
     * Draws the calendar array(incl all html formatting) into the data object later to be written into the document.
     */
    workingTime = new Date(startMonth.getTime());
    data = '<div class=calendar >';
    
    for (workingMonth = 0; workingMonth < calendar.length; workingMonth++) {//for every month
        workingTime.setDate(1);
    
        data +=  '<div class=calendarMonth><h3 class=calendarMonthHeading>' + monthArray[workingTime.getMonth()] + ' ' + workingTime.getFullYear() + '</h3>';
        data += '<Table class=calendarMonthTable border=1 WIDTH=100% cellspacing=0>';
        data +=  '<tr class=daysOfTheWeek><td width=14%>Monday</td><td width=14%>Tuesday</td><td width=14%>Wednesday</td><td width=14%>Thursday</td><td width=14%>Friday</td><td width=15%>Saturday</td><td width=15%>Sunday</td></tr>';
        
		dummyDate = new Date(workingTime.getTime());
        
        if (dummyDate.getDay() != 1) {//filling the empty boxes at the begining of the month....
            data +=  '<tr>';
    
            for (j = 1; j < (dayNumberArray[dummyDate.getDay()]); j++) {
                data +=  '<td>&nbsp;</td>';
            }
        }
        
        for (workingDay = 0; workingDay < calendar[workingMonth].length; workingDay++) {//for every day
            dummyDate.setDate(workingDay + 1);
            if (dummyDate.getDay() == 1) {//Start a new row on mondays
                data +=  '<tr>';                
            }
            if (calendar[workingMonth][workingDay].length == 0) {//if no events exist on this date...
                data +=  '<td class=calendarDayEmpty valign=top><B class=calendarDayB>' + (workingDay + 1) + '</B>';
                
                
            }
            
            else {//if theres any events on this date
            
                data +=  '<td class=calendarDayFilled valign=top><B class=calendarDayB>' + (workingDay + 1) + '</B>';
                
                for (workingEventI = 0; workingEventI < calendar[workingMonth][workingDay].length; workingEventI++) {//for every event
                    workingEvent = calendar[workingMonth][workingDay][workingEventI];
                    data += '<br><a class=calendarEvent href="' + eventUrlPrefix + workingEvent[0] + '"' + ' title="'+ getDescription(workingEvent) + '" >' + workingEvent[3] + '</a>'; // link and event
                }
            }
            data +=  '</td>';
            if (dummyDate.getDay() == 0) {//ends the row on sundays
                data +=  '</tr>';
            }
        }
        if (dummyDate.getDay() != 0) {//last day of the month is NOT sunday
            for (m = 0; m < (7 - dummyDate.getDay()); m++) {
                data +=  '<td>&nbsp;</td>';
            }
            data +=  '</tr>';
        }
        data += '</table></div>';
        workingTime.setMonth(workingTime.getMonth() + 1);
    }
	data += "</div>";
    return data;
}
function addEventToCalendar(event, startDate, endDate){
	/**
	 * for any given event (single event), this method will iterate through the days of the event and adds it to 
	 * the calendar array...
	 * 
	 */
    var eventCurrent = new Date(event[1].getFullYear(), event[1].getMonth(), event[1].getDate());
    var eventEnd = new Date(event[2].getFullYear(), event[2].getMonth(), event[2].getDate());
    while (eventCurrent <= eventEnd) {//for every day of the chosen event
        if (eventCurrent >= startDate && eventCurrent < endDate) {//if the day is between the starting and end dates of the calendar
		var restrictToDay = event[7];
		var currentDOW = dayArraySystem[eventCurrent.getDay()];
		if (!restrictToDay || restrictToDay==currentDOW) {
	            arrayMonth = ((eventCurrent.getFullYear() - startDate.getFullYear()) * 12) + eventCurrent.getMonth() - startDate.getMonth();
     		      dayArray = calendar[arrayMonth][eventCurrent.getDate() - 1];
     	      	dayArray[dayArray.length] = event;
		}
        }
        eventCurrent.setDate(eventCurrent.getDate() + 1);
    }
}
function generateEvents(events, startYear, endYear){
	/**
	 * Loops through all events and any event thats within the start and end dates (of the calendar), will be sent to the addEventToCalendar() method...
	 */
    for (counter = 0; counter < events.length; counter++) {//for every event
		eventStart = events[counter][1];
		eventEnd = events[counter][2];
        if (eventStart <= endYear && eventEnd >= startYear) {
            addEventToCalendar(events[counter], startYear, endYear);
	   }
    }
}


function createCalendar(startMonth, endMonth){
    /**
     * Creates the empty calendar array from the starting date to the end date...
     * Calendar[Month][Date][?]
     * month is a number from 0-x (0 = the very 1st month(starting month); x = the number of months between the start date and end date, it should be 11 or less by defauly start/end date calculation)
     * date starts from 0 and ends at <Days of the Month - 1>
     * ? = if any events exist, it would/should be added here... at the very end if ? = 0 for any date, then theer exists no events for that day. if ? = 2, meaning 3 events exist...
     */
    workingMonth = new Date(startMonth);
    
    lastDate = new Date(workingMonth);
    _calendar = new Array();
    
    
    i = 0;
    while (workingMonth < endMonth) {
    
        if (workingMonth.getDate() == 1) {//start of the month, add a new month to the array
            _calendar[_calendar.length] = new Array();
        }
        
        _calendar[_calendar.length - 1][workingMonth.getDate() - 1] = new Array();// add a day..
        workingMonth.setDate(workingMonth.getDate() + 1);
    }
    
    return _calendar;
    
    
}
function dateToString(mydate) {
	return mydate.getDate() + '/' + (mydate.getMonth()+1) + '/' +mydate.getFullYear();
}
function getDescription(_event){
	/**
	 * creates the event description text...
	 */
	title = _event[3] + '\n' + _event[4] ;
	if (_event[2] > _event[1]) 
		title += '\nFrom ' + dateToString(_event[1]) + ' Till ' + dateToString(_event[2]);
	else
		title += '\nDate ' + dateToString(_event[1]) ;
	return title;
}

function getStartMonth(_events, thisMonth){
    /**
     Generates the First month that is to be displayed on the calendar
     **/
    today = new Date();
    //startDate = new Date(thisMonth);
    
    for (i = 0; i < _events.length; i++) {//for all events
        if (_events[i][1] <= thisMonth && _events[i][2] >= thisMonth) {//event starts in the past and ends in the future
            startDate = new Date(thisMonth);
            //dont need to do anything since this month is set to start month by default
        }
        else 
            if (_events[i][1] >= thisMonth && typeof(window['startDate']) == "undefined") {//if the event starts in the future and start date not set
                startDate = new Date(_events[i][1]);
            }
            else 
                if (_events[i][1] >= thisMonth && _events[i][1] <= startDate) {//if the event starts in the future and is before current start date
                    startDate = new Date(_events[i][1]);
                }
    }
    
    startDate.setDate(1);
    finalStartDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    return finalStartDate;
}
function getEndMonth(_events, _startMonth, thisMonth){
    /**
     Generates the Last month that is to be displayed on the calendar
     **/
    nextYear = new Date(_startMonth.getFullYear() + 1, _startMonth.getMonth(), startMonth.getDate() ); //-1
    endMonth = new Date(_startMonth);
    
    for (y = 0; y < _events.length; y++) {//for all events
        if (_events[y][2] >= endMonth && _events[y][2] >= _startMonth) {
            endMonth = new Date(_events[y][2]);
            
        }
    }
	if (endMonth >= nextYear){
		endMonth = nextYear;
	}
    
    endMonth.setMonth(endMonth.getMonth() + 1);
    endMonth.setDate(1);
    finalEndMonth = new Date(endMonth.getFullYear(), endMonth.getMonth(), endMonth.getDate());
    
    
    
    return finalEndMonth;
}
