var DEBUG;
(window.location.host == 'plone-dev:8001') ? DEBUG = true : DEBUG = false;
DEBUG ? console.log('running in debug mode') : null;

var Feedback = {
    init: function() {
        jq('body').prepend('<div class="header"> </div>');
        jq('body').append('<div class="footer"> </div>');
    }
}

var Cookies = {
    /*
     * PRE: Existing cookies
     * POST: Stores existing cookies in key->value
     */
    init: function () {
        var allCookies = document.cookie.split('; ');
        for (var i=0;i<allCookies.length;i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },
    /*
     * PRE: Key, value, TTL in hours
     * POST: Stores cookie 
     */
    create: function (name,value,hours) {
        if (hours) {
            var date = new Date();
            date.setTime(date.getTime()+(hours*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
        this[name] = value;
    },
    /*
     * PRE: Name of cookie
     * POST: Erases cookie
     */
    erase: function (name) {
        this.create(name,'',-1);
        this[name] = undefined;
    }
};
Cookies.init();

/* start videoconference studio reservation */
var Videoconference = {
    /* 
     * PRE: URL
     * POST: Selects video conference based on previously viewed page
     */
    selectByReferrer: 
        function () {
            console.log('in selectbyreferrer');
            var ref;
            if (document.referrer != "") {
                ref = document.referrer.replace('.html','').split('/');
            } 
            else {
                return
            }
            var studioName = ref[ref.length-2];
            var studio;
            switch (studioName) {
                case 'ougl_videoconference_studio':
                    studio = 1;
                break;
                case 'hs_videoconference_lecture_hall':
                    studio = 2;
                break;
                case 'hs_videoconference_studio':
                    studio = 3;
                break;
                default:
                    studio = 0;
                break;
            }
            var facilitySelect = document.getElementById('facilityName');
            facilitySelect.options[studio].selected = true;
        },
    /*
     * when a user submits the form, it stores the facility selected so if an error is encountered the 
     * form sets itself 
     */
    selectByCookie:
        function() {
            var vcs = { 
                        'Odegaard Videoconference Studio': 1, 
                        'Health Sciences Videoconference Lecture Hall': 2, 
                        'Health Sciences Videoconference Studio': 3 
                        };
            var studio = vcs[Cookies['facility']];
            if (studio == undefined) {
                return null;
            }
            var facilitySelect = document.getElementById('facilityName');
            facilitySelect.options[studio].selected = true;
        },
    /* 
     * to enable non-javascript functionality of the forms, all are displayed by default
     * this hides those other elements when the user has javascript for a nice interface
     * PRE: 
     * POST: Hides videoconference studio details
     */ 
    hideDetails: 
        function() {
            DEBUG ? console.log('hiding details') : null;
            var elems = ['odegaard-studio', 'hs-lecture-hall',
                            'hs-studio','odegaard-studio-title',
                            'hs-lecture-hall-title','hs-studio-title'];
            for (var ii=0; ii<elems.length; ii++) {
                jq('#'+elems[ii]).hide();
            }
        },
    /*
     * PRE: Grabs the facility selected value
     * POST: Displays selected facility's details
     */
    showDetails:
        function() {
            DEBUG ? console.log('showing details') : null;
            this.hideDetails();
            switch (jq('#facilityName').val()) {
                case "Odegaard":
                    jq('#odegaard-studio').show();
                break;
                case "Health Sciences Lecture Hall":
                    jq('#hs-lecture-hall').show()
                break;
                case "Health Sciences Studio":
                    jq('#hs-studio').show()
                break;
            }
        },
    /*
     * PRE: ID of field to display error in
     *      Message to display
     * POST: Displays message in field
     */
    displayError: 
        function(field, message) {
            DEBUG ? console.log('displaying error') : null;
            var elm = jq('#'+field);
            elm.css("color", "#FF0000");
            elm.text(message);
        },   
    /*
     * PRE: Email address
     * POST: Dispalys error if invalid
     */
     checkEmail:
        function(elm, errorfield) {
            DEBUG ? console.log('checking email') : null;
            var elm = jq('#'+elm);
            var email = elm.val();
            DEBUG ? console.log(email) : null;
            if (email.length > 0) {
                var regExp = /^\S+@+\w/;
                if (regExp.test(email)) {
                    return true;
                }
                else {
                    elm.css("background","#FF3366");
                    this.displayError(errorfield, "Invalid email");
                    return false;
                }
            }
            else {
                elm.css("backgroundcolor","#FFFFFF");
            }
        },
    /*
     * PRE: Takes ID of input and error fields
     * POST: Resets fields
     * TODO: Make more generic
     */
    resetFields:
        function (input, error) { 
            jq('#'+input).css("backgroundColor","#FFFFFF");
            error = jq('#'+error); 
            error.text("(required)");
            error.css("color","#FFFFFF");
        },
    /*
    * PRE: Takes an int x for a month such that 1 <= x <= 12
    *       Takes a year in full four digit form i.e. 2009
    * POST: Returns the number of days in that month 1 <= y <= 31
    */
    _daysInMonth:
        function (month,year) {
            return new Date(year, month, 0).getDate();
        },
    /*
    * PRE: Takes the select object
    * POST: Clears all options from the select
    */
    _clearSelect:
        function(sel) {
            while (sel.firstChild) {
                sel.removeChild(sel.firstChild);
            }
        },
    /*
    * PRE: Takes the IDs of a month, day, and year select
    * POST: Replaces the select with a generated select that calculates the
    *       number of days in the month and sets the current date as selected
    * TODO: Use jQuery, make clean!
    */
    createSelect:
        function (months, days, years) {
            var now = new Date();
            var curMonth = (Cookies['month'] == undefined) ? now.getMonth() : Cookies['month'];
            var curDay = (Cookies['day'] == undefined) ? now.getDate() : Cookies['day'];
            var curYear = (Cookies['year'] == undefined) ? now.getFullYear() : Cookies['year'];
            var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
                                'August', 'September', 'October', 'November', 'December'];

            var daySelect = document.getElementById(days);
            var monthSelect = document.getElementById(months);
            var yearSelect = document.getElementById(years);

            for (var m = 0; m < 12; m++) {
                monthSelect.options[m] = new Option(monthList[m], m);
            }
            // select the current month by default
            monthSelect.options[curMonth] = new Option(monthList[curMonth], curMonth, true, true)

            // clear out all days
            this._clearSelect(daySelect);
            var numDaysMonth = this._daysInMonth(parseInt(curMonth)+1, curYear);
            for (i = 0; i < numDaysMonth; i++) {
                daySelect.options[i] = new Option(i+1, i+1,i+1==curDay?true:false,i+1==curDay?true:false)
            }

            for (y = 0; y < 2; y++) {
                yearSelect.options[y] = new Option(curYear+y, curYear+y)
            }
            yearSelect.options[0] = new Option(curYear, curYear, true, true)
        },
    /*
     * PRE: Takes ID of element
     * POST: Clears value of content and resets color
     */
    clearDefault:
        function(elm) {
            elm = jq('#'+elm);
            elm.val("");
            elm.css("color", "#000000");
        },
    /*
    * POST: Sets three cookies called month, day, year based on the selected options
    *       on the associated HTML selects
    */
    setDateCookie:
        function() {
            var elms = { 'month' : document.getElementById('reservation_month'),
                                'day'   : document.getElementById('reservation_day'),
                                'year'  : document.getElementById('reservation_year')
                            };
            // set cookies for each field in the date
            Cookies.create('month', elms['month'].options[elms['month'].selectedIndex].value, 1);
            Cookies.create('day', elms['day'].options[elms['day'].selectedIndex].value, 1);
            Cookies.create('year', elms['year'].options[elms['year'].selectedIndex].value, 1);
        },
    /* 
     * POST: 
     *
     */
    setFacilityCookie:
        function() {
            Cookies.create('facility',jq('#facilityName').val()); 
        },
    /*
    * POST: Creates the dates selects, hides all the facilities, sets up event handlers
    */
    init:
        function() {
            this.hideDetails();

            this.createSelect('reservation_month', 
                        'reservation_day', 
                        'reservation_year');

            // clear far end name when clicked
            jq('#far_end_name').focus(function() { 
                                            Videoconference.clearDefault(this.id); 

                                            // if users want to edit a name, we don't 
                                            // want to delete it if they've already entered something
                                            jq('#far_end_name').unbind('focus');
                                    });
            jq('#far_end_name').css('color','#999999');

            // check email inputs
            var email_fields = [['handler_email_from','validinfo'],
                                ['far_end_email','validinfo2'],
                                ['it_email','validinfo3']];
            jq.each(email_fields, function(ii, val) {
                jq('#'+val[0]).blur(function() { Videoconference.checkEmail(val[0], val[1]) } );
                jq('#'+val[0]).focus(function() { Videoconference.resetFields(val[0], val[1]) } );
            });

            // gray out far end contact
            // contains description of what users should enter
            //jq('#[!Far_End_Info]far_end_name').css("color","#999999");

            //document.getElementById('[!Far_End_Info]far_end_name').style.color = "#999999";
            //document.getElementById('[!Far_End_Info]far_end_name').onFocus = function() { 
             //                               Videoconference.clearDefault('[!Far_End_Info]far_end_name'); };

            Videoconference.selectByReferrer();
            Videoconference.selectByCookie();

            // when a facility if selected based on the referrer
            // we want to show the details of it
            var facility = jq('#facilityName');
            if (facility.val() != "None Selected") { Videoconference.showDetails(); }

            // show details when facility selection changes
            facility.change(function() {  
                            DEBUG ? console.log('changed facility') : null;
                            Videoconference.showDetails(); });

            // cookies will get set when the form is submitted
            jq('#videoconfform').submit(function() { 
                        Videoconference.setFacilityCookie(); 
                        Videoconference.setDateCookie(); 
                        });
        }
}

var LibVideoconference = {
    init:
        function() {
            this.hideOtherField();

            this.showingOther = false;

            this.toggleOtherByCookie();

            // check email inputs
            var email_fields = [['handler_email_from','validinfo'],
                                ['far_end_email','validinfo2']];
            jq.each(email_fields, function(ii, val) {
                jq('#'+val[0]).blur(function() { LibVideoconference.checkEmail(val[0], val[1]) } );
                jq('#'+val[0]).focus(function() { LibVideoconference.resetFields(val[0], val[1]) } );
            });


            jq('#other').click(function() { 
                if(jq('#other').is(':checked')) { 
                    LibVideoconference.showOtherField();
                }
                else {
                    LibVideoconference.hideOtherField();
                }
            });

            jq('#far_end_name').focus(function() {
                jq('#far_end_name').select();
            });

            jq('#videoconfform').submit(function() { LibVideoconference.setOtherCookie(); });
        },
    /*
     * PRE: Takes ID of element
     * POST: Clears value of content and resets color
     */
    clearDefault:
        function(elm) {
            elm = jq('#'+elm);
            elm.val("");
            elm.css("color", "#000000");
        },
    /*
     * PRE: Email address
     * POST: Dispalys error if invalid
     */
     checkEmail:
        function(elm, errorfield) {
            DEBUG ? console.log('checking email') : null;
            var elm = jq('#'+elm);
            var email = elm.val();
            DEBUG ? console.log(email) : null;
            if (email.length > 0) {
                var regExp = /^\S+@+\w/;
                if (regExp.test(email)) {
                    return true;
                }
                else {
                    elm.css("background","#FF3366");
                    this.displayError(errorfield, "Invalid email");
                    return false;
                }
            }
            else {
                elm.css("backgroundcolor","#FFFFFF");
            }
        },
    /*
     * PRE: Takes ID of input and error fields
     * POST: Resets fields
     * TODO: Make more generic
     */
    resetFields:
        function (input, error) { 
            jq('#'+input).css("backgroundColor","#FFFFFF");
            error = jq('#'+error); 
            error.text("(required)");
            error.css("color","#FFFFFF");
        },
    /*
     * PRE: ID of field to display error in
     *      Message to display
     * POST: Displays message in field
     */
    displayError: 
        function(field, message) {
            DEBUG ? console.log('displaying error') : null;
            var elm = jq('#'+field);
            elm.css("color", "#FF0000");
            elm.text(message);
        },   
    hideOtherField:
        function() {
            jq('#conferencing_with').hide()
            //jq('#far_end_name').val('')

            this.showingOther = false;
        },

    showOtherField:
        function(replaceFarEnd) {
            jq('#conferencing_with').show()

            this.showingOther = true;
        },

    setOtherCookie:
        function() {
            if (this.showingOther) {
                Cookies.create('showingOther', true);
            }
            else {
                Cookies.erase('showingOther');
            }
        },

    toggleOtherByCookie:
        function() {
            if (Cookies['showingOther']) {
                this.showOtherField(false);
                this.showingOther = true;
            }
        }
    }

// setup the form
jq(document).ready(function() { DEBUG ? console.log('document loaded') : null; });
