Ext.namespace('utc.calendar');

var dialog;
var canModify;
var currMonth;
var currYear;

/**
 * This should maybe be in event.js? Either way, this function is called to display an event.
 *
 * @param user The current user, or NULL if the person is not logged in (read-only mode).
 * @param date The date of the event to display!
 * @param day  An integer representing the day of the month. This is kind of a weird variable to pass,
 * 			   but it's used so that this will all work with Kevin's original generateCalendar.php code.
 * @param action A String representing the action to be taken. 'add' 'update' 'modify' 'delete'
 */
function displayEvent (user, date, day, action) {
    // This function is called on a successful AJAX request. It calls the function that will
    // construct the popup window.
    var successHandler = function (response) {
        utc.calendar.displayResponse(user, date, day, response.responseText, action);
    }
    var con = new Ext.data.Connection();

    // This is an ajax call to eventForm.php. The response of the call is passed to the
    // successHandler.
    con.request({url:'eventForm.php',
                method: 'POST',
                success: successHandler,
                params: {
                     date: date,
                     action: action}
                });
}

/**
 * This...logs the user out. Probably self explanatory.
 */
function logout() {
    var successHandler = function () {
        canModify = null;
        utc.calendar.reloadCalendar();
    }
    var con = new Ext.data.Connection();
    // Make an ajax call to the logout.php file which will remove login session variables.
    con.request({url:'logout.php',
                method: 'POST',
                success: successHandler
                });
}

/**
 * Pops up a handy little help screen for the user. More specifically, this loads help.html and
 * then passes the actual pop-up responsibilities to the displayResponse() function. Hooray for
 * reusing code!
 */
function viewHelp() {
    var successHandler = function (response) {
        utc.calendar.displayResponse(null, null, null, response.responseText);
    }
    var con = new Ext.data.Connection();
    con.request({url:'help.html',
                success: successHandler});
}

/**
 * This function is responsible for those neat pop-up windows that pop up (ha) all around
 * the calendar.
 *
 * @param user The current user, or NULL if the person is not logged in (read-only mode).
 * @param date The date of the event to display!
 * @param day  An integer representing the day of the month. This is kind of a weird variable to pass,
 * 			   but it's used so that this will all work with Kevin's original generateCalendar.php code.
 * @param action A String representing the action to be taken. 'add' 'update' 'modify' 'delete'
 *
 * @param responseText A big blob of text/html that will be the body of the pop-up window.
 */
utc.calendar.displayResponse = function(user, date, day, responseText, action) {
    // First, let's figure out which buttons we'll need.
    var buttonArray = new Array();

    if (user) { // We need to be logged in to see this.
    if (action == 'new') { // if the screen is for a new event
        buttonArray[0] = new Ext.Button({
                                text: 'Add Event',
                                handler: function(){ // handler=what-happens-when-the-button-is-clicked
                                    utc.calendar.event.submitForm('add');
                                }});
        } else if (action == 'modify') { // if we're modifying an existing event
            buttonArray[0] = new Ext.Button({
                                text: 'Save Changes',
                                handler: function(){
                                    utc.calendar.event.submitForm('update');
                                }});
        } else { // otherwise, we're viewing an existing event
            buttonArray[0] = new Ext.Button({
                                text: 'Edit',
                                handler: function(){
                                    displayEvent(user, date, day, 'modify');
                                }});

            buttonArray[1] = new Ext.Button({
                                text: 'Delete',
                                handler: function(){
                                    utc.calendar.event.deleteEvent(user, date);
                                    dialog.hide();
                                }});
        }
    }

    // No matter what, add a close button.
    buttonArray[buttonArray.length] = new Ext.Button({text: 'Close',
                                        handler: function(){
                                            dialog.hide();
                                        }});

    if (dialog) { // If the dialog box exists already, close it.
        dialog.destroy();
    }

    dialog = new Ext.Window({
                        animateTarget: 'cell' + day, // the HTML id for the dialog to 'grow' out of
                        width:550,
                        minWidth:340,
                        minHeight:550, // arbitrary numbers.
                        plain: true,
                        buttons: buttonArray,
                        keys: [{
                            key: 27,  // hide on Esc pressed
                            fn: function(){
                                dialog.hide();
                            }
                        }],
                        html: responseText,
                        title: 'Event Details'
                });

    dialog.show();
    if (action == 'new' || action == 'modify') {
        utc.calendar.event.initialize(user, date, day, action);
    }
}

/**
 * Just reloads the page. This is called whenever the calendar is modified.
 */
utc.calendar.reloadCalendar = function() {
    loadCalendar(canModify, currMonth, currYear);
}

/**
 * Displays the calendar for a given {@param month} and {@param year}. Will either be
 * editable or read-only, depending if {@param hasModifyPriv} is true.
 */
function loadCalendar (hasModifyPriv, month, year) {
    canModify = hasModifyPriv;
    currMonth = month;
    currYear = year;

    // Some validations.
    if (month > 12) {
        month -= 12;
        year += 1;
    } else if (month < 1) {
        month += 12;
        year -= 1;
    } else if (month == null) {
        var today = new Date();
        month = today.getMonth() + 1;
        year = today.getFullYear();
    }
    var successHandler = function (response) {
        var calendarDiv = Ext.get('calendarDiv');
        // Set the HTML of the page to be what was generated by generateCalendar.php
        calendarDiv.dom.innerHTML = response.responseText;

        // If the user has modify privilege, show the filter panel (even though it doesn't
        // work yet...)
        if (hasModifyPriv) {
            var datePanel = new Ext.Panel({
                    title:'View Filters',
                    collapsible:true,
                    renderTo: 'calFilterDiv',
                    html: 'This doesn\'t work yet',
                    collapsed: true,
                    bodyStyle: 'background-color: #111111;'
                });
        }
    }
    var con = new Ext.data.Connection();
    // ajax call to generateCalendar.php to build the display
    con.request({url:'generateCalendar.php',
                method: 'GET',
                success: successHandler,
                params: {
                     month: month,
                     year: year,
                     canModify: canModify}
                });
}

(function() {
    // Called when the HTML of the page has finished loading.
    Ext.onReady(function() {
        var p = new Ext.Panel({
                collapsible:true,
                renderTo: 'calendarDiv'
            });
    });

})();
