if (typeof PeopleInsite === 'undefined') {
    var PeopleInsite = {};
}

PeopleInsite.login = function() {

    var LOGIN_ACTION = "/app/login";

    var SSL_PORT = {
        "" : "",
        "8080" : "8443",
        "80"   : "443",
        "8443" : "8443",
        "443"  : "443"
    };

    var _errorMessage;
    var _interval;

    var _baseURI;

    var LAST_USERNAME_COOKIE = "lastUsername";
    var AUTH_COOKIE = "persistentSession";
    var AUTH_URI = "/secure/session/auth.json";
    var HOME_URI = "/secure/home";

    function uri(path) {
        return _baseURI + path;
    }

    function redirect(absolutePath) {
        window.location = uri(absolutePath);
    }

    var authenticationCallback = {
        success: function(o) {
            var loginPanel = YAHOO.util.Dom.get("loginPanel");
            if (loginPanel) {
                loginPanel.innerHTML = "<p class='loginAutoMsg'>Logging in... (<a href='/secure/logout'>Logout</a>)</p>";
            }

            // the user is pre-authenticated - redirect to account home
            setTimeout(function() {
                redirect(HOME_URI);
            }, 2000);
        },
        failure: function(o) {
            // the cookie is invalid
            YAHOO.util.Cookie.remove(AUTH_COOKIE);
        }
    };

    function authenticate() {
        YAHOO.util.Connect.resetFormState();
        YAHOO.util.Connect.asyncRequest("POST", AUTH_URI, authenticationCallback);
    }

    /**
     * If the auth cookie exists, make an HTTP request to see if the user is logged in.
     * If logged in, redirect to their home page
     */
    function initAutoAuthentication() {
        var authCookieValue = YAHOO.util.Cookie.get(AUTH_COOKIE);
        if (authCookieValue) {
            authenticate();
        }
    }

    /**
     * Read the cotent of the meta tab "hub" if defined
     */
    function evaluateHub() {
        try {
            var headEl = YAHOO.util.Dom.getElementBy(function() { return true; }, "head");
            if (headEl) {
                var meta = YAHOO.util.Dom.getElementBy(function(el) {
                    return (YAHOO.util.Dom.getAttribute(el, "name") === "hub");
                }, "meta", headEl);
                if (meta) {
                    return YAHOO.util.Dom.getAttribute(meta, "content");
                }
            }
        } catch (e) {
            // ignored
        }

        return null;
    }

    function evaluateBaseURI(loginFormEl, domain, sslPort, port) {
        var target;

        if ((domain.indexOf("stage") === 0) || (domain.indexOf("snow") === 0) || (domain.indexOf("fcb") > 0) || (domain.indexOf("-dev") > 0)) {
            target = "http://" + domain + (port ? ":" + port : "");
        } else {
            target = "https://" + domain + (sslPort ? ":" + sslPort : "");
        }

        return target;
    }

    function evaluateTarget(loginFormEl, domain, sslPort, port) {
        var target = evaluateBaseURI(loginFormEl, domain, sslPort, port)+LOGIN_ACTION;

        // set the hub parameter if not already defined
        if (loginFormEl) {
            if (!loginFormEl["hub"] || loginFormEl["hub"].value.length === 0) {
                var hub = evaluateHub();
                if (hub) {
                    target = target+"?hub="+hub;
                }
            }
        }

        return target;
    }

    function setupBaseURI() {
        var target;
        var sslPort;
        var domain = document.domain;
        var uri = document.URL;
        var startPos = uri.indexOf(domain) + domain.length + 1;
        var endPos = uri.indexOf("/", startPos - 1);
        var port;
        if (endPos > startPos) {
            port = uri.substring(startPos, endPos);
        }

        if (port) {
            sslPort = SSL_PORT[port];
        } else {
            sslPort = null;
        }

        var loginFormEl = document.getElementById("loginForm");

        _baseURI = evaluateBaseURI(loginFormEl, domain, sslPort, port);
    }

     var initUsername = function() {
        var usernameEl = YAHOO.util.Dom.get("username");
        if (usernameEl) {

            var lastUsernameCookieValue = YAHOO.util.Cookie.get(LAST_USERNAME_COOKIE);
            if (lastUsernameCookieValue) {
                if (usernameEl.value.length === 0) {
                    usernameEl.value = lastUsernameCookieValue;
                    usernameEl.focus();
                }
            } else {
                // focus if not used
                usernameEl.focus();
            }
        }
    };

    YAHOO.util.Event.onDOMReady(initUsername);

    return {
        init : function() {
            setupBaseURI();
            initAutoAuthentication();
            var usernameEl = document.getElementById("username");
            if (usernameEl) {
                // focus if not used
                if (usernameEl.value.length === 0) {
                    usernameEl.focus();
                }
            }
        },
        submit : function(loginForm) {
            var target;
            var sslPort;
            var domain = document.domain;
            var uri = document.URL;
            var startPos = uri.indexOf(domain) + domain.length + 1;
            var endPos = uri.indexOf("/", startPos - 1);
            var port;
            if (endPos > startPos) {
                port = uri.substring(startPos, endPos);
            }

            if (port) {
                sslPort = SSL_PORT[port];
            } else {
                sslPort = null;
            }

            target = evaluateTarget(loginForm, domain, sslPort, port);

            loginForm.action = target;
            loginForm.method = 'POST';

            if (loginForm.username) {
                YAHOO.util.Cookie.set(LAST_USERNAME_COOKIE, loginForm.username.value);
            }

            // all allow the default event to proceed
            return true;
        }
    };
}();

/**
 * Webinar request form
 */
(function() {

    PeopleInsite.webinar = {};

    PeopleInsite.webinar.DETAILS = {
        "28/10/2010 10am" : { meetingNumber: "864 066 422", startDate: "", startTime: "", link: "" },
        "28/10/2010 3pm" : "",
        "4/11/2010 10am" : "",
        "4/11/2010 3pm" : "",
        "9/11/2010 2pm" : "",
        "11/11/2010 10am" : "",
        "11/11/2010 3pm" : "",
        "16/11/2010 2pm" : "",
        "18/11/2010 10am" : "",
        "18/11/2010 3pm" : "",
        "23/11/2010 2pm" : "",
        "25/11/2010 10am" : "",
        "25/11/2010 3pm" : "",
        "30/11/2010 2pm" : ""
    };

    var webinarValidationSettings = {
        formName : "webinarForm",
        validators : [
            {
                name : "enqName",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqNameErrorContainer",
                        message: "Please provide the name of the person attending the webinar"
                    }
                ]
            },
            {
                name : "enqCompany",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqCompanyErrorContainer",
                        message: "Please provide the name of company or organisation"
                    }
                ]
            },
            {
                name : "enqSate",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqSateErrorContainer",
                        message: "Please provide the organisation's state"
                    }
                ]
            },
            {
                name : "enqPhone",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqPhoneErrorContainer",
                        message: "Please provide a contact phone number"
                    }
                ]
            },
            {
                name : "enqEmail",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqEmailErrorContainer",
                        message: "Please provide an email address"
                    }
                ]
            },
            {
                name : "enqBusType",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqBusTypeErrorContainer",
                        message: "Please select the business type"
                    }
                ]
            },
            {
                name : "enqBusIndustry",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqBusIndustryErrorContainer",
                        message: "Please select the business industry"
                    }
                ]
            },
            {
                name : "enqNoOfEmp",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqNoOfEmpErrorContainer",
                        message: "Please specify the number of employees within your business"
                    }
                ]
            },
            {
                name : "enqProduct",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqProductErrorContainer",
                        message: "Please select the product you're interested in"
                    }
                ]
            },
            {
                name : "enqAbout",
                validators: [
                    {
                        validator : PeopleInsite.validation.requiredString,
                        containerId: "enqAboutErrorContainer",
                        message: "Please indicate how you heard about PeopleInsite"
                    }
                ]
            }
        ]
    };

    var formSubmitListener = function(e) {
        YAHOO.util.Event.preventDefault(e);

//        var calendar = this.calendar;
        var value = "";
        var first = true;
        // concatenate the selected date values
//        if (calendar) {
//            var selectedDates = calendar.getSelectedDates();
//            for (var i = 0; i < selectedDates.length; ++i) {
//                var date = selectedDates[i];
//                if (!first) {
//                    value += ",";
//                } else {
//                    first = false;
//                }
//                value += PeopleInsite.calendar.formatSystemJSDate(date);
//            }
//        }

//        YAHOO.util.Dom.get("webinarDate").value = value;

        if (PeopleInsite.validation.validate(webinarValidationSettings)) {
            // submit the form
            this.form.submit();
        }
    };

    PeopleInsite.webinar.init = function() {
        // any date
        var calendarDiv = YAHOO.util.Dom.get("webinarDateCal");
        if (calendarDiv) {
            var cal1 = new YAHOO.widget.Calendar(calendarDiv);
            cal1.render();
            var formEl = PeopleInsite.dom.getFormById("webinarForm");
            YAHOO.util.Event.addListener(formEl, "submit", formSubmitListener, { form: formEl, calendar: cal1 }, true);
        } else {
            // preset dates
            var calendarSelect = YAHOO.util.Dom.get("webinarDate");
            if (calendarSelect) {

                var targetDay = YAHOO.util.Dom.getAttribute(calendarSelect, "data-dayOfWeek");
                if ((targetDay >= 0 && targetDay <= 6)) {
                    // nothing to do actually
                } else {
                    targetDay = 1;  // monday
                }
                var now = new Date();
                var today = now.getDay();
                // calculate the number of days until the next monday
                var dayOffset = targetDay - today;
                if (dayOffset <= 0) {
                    dayOffset += 7;
                }
                var nextWebinarDate = new Date();
                nextWebinarDate.setTime(now.getTime()+dayOffset * (24*60*60*1000));

                var dateOptions = [];
                var current = nextWebinarDate;
                var oneWeek = 7 * 24 * 60 * 60 * 1000;
                for (var i = 0; i < 4; i++) {
                    dateOptions[i] = new Option(PeopleInsite.calendar.formatJSDisplayDayDate(current)+", 10:00 AM EST", PeopleInsite.calendar.formatSystemJSDate(current), false, false);
                    current.setTime(current.getTime() + oneWeek);
                }
                PeopleInsite.dom.select.setOptions("webinarDate", dateOptions);

                var formEl = PeopleInsite.dom.getFormById("webinarForm");
                YAHOO.util.Event.addListener(formEl, "submit", formSubmitListener, { form: formEl }, true);
            }
        }
    };

    var init = function() {
        PeopleInsite.webinar.init();
    };

    YAHOO.util.Event.onDOMReady(init);
})();

/**
 * Find and enable the tool tips
 */
(function() {

    var init = function() {
        YAHOO.util.Dom.getElementsByClassName("tip", "a", "bd", function(el) {
            var id = YAHOO.util.Dom.generateId(el);
            var ttl = new YAHOO.widget.Tooltip("tip" + id, {
                context: id,
                width: "400px"
            });
        });
    };

    YAHOO.util.Event.onDOMReady(init);

})();
/*
(function() {
    var Dom = YAHOO.util.Dom;
    var e1 = null, e2 = null;

    function reinviteListener(e) {
        var formEl = Dom.getAncestorByTagName("reinviteBtn", "form");
        if (formEl) {
            if ((e1 >= 0) && (e2 >= 0)) {
                formEl.action = "/registration/reinvite?e1="+e1+"&e2="+e2;
            }
        }
    }
    function init() {
        var btn = YAHOO.util.Dom.get("reinviteBtn");
        if (btn != null) {
            YAHOO.util.Event.addListener(btn, "click", reinviteListener);

            var e1El = Dom.get("e1");
            var e2El = Dom.get("e2");
            if (e1El && e2El) {
                e1 = Math.floor(Math.random()*11);
                e2 = Math.floor(Math.random()*11);
                e1El.innerHTML = e1;
                e2El.innerHTML = e2;
            }
        }
    }
    YAHOO.util.Event.onDOMReady(init);
})();  */
