// site.js
var ASD = {};

ASD.generateFormErrorTooltips = function()
{
    // slice and dice form error messages
    var elementsFormError = $$('.formError');
    if (elementsFormError)
    {
        elementsFormError.each(function(each)
        {
            var errorTrigger = $(each.id + ".trigger");
            try
            {
                errorTrigger.title = each.firstChild.nodeValue;
                new Tooltip(errorTrigger, {
                    appearDuration: .1,
                    backgroundColor: '#FFFFBB',
                    borderColor: '#FFCC66',
                    delay: 100,
                    hideDuration: .1,
                    maxWidth: 250,
                    mouseFollow: false,
                    opacity: .95,
                    textColor: '#000000'
                });

                Element.setStyle(errorTrigger, {visibility: 'visible'});
            }
            catch (err)
            {
                // We just let these go...
            }
        });
    }
};

ASD.Window = {
    open: function(inOptions)
    {
        this.options = {
            url: 'javascript:void(0)',
            width: 600,
            height: 500,
            name:"_blank",
            location:"no",
            menubar:"no",
            toolbar:"no",
            status:"yes",
            scrollbars:"yes",
            resizable:"yes",
            left:"",
            top:"",
            normal:false
        };
        Object.extend(this.options, inOptions || {});

        if (this.options.normal)
        {
            this.options.menubar = "yes";
            this.options.status = "yes";
            this.options.toolbar = "yes";
            this.options.location = "yes";
        }

        this.options.width = this.options.width < screen.availWidth ? this.options.width : screen.availWidth;
        this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;
        var openoptions = 'width=' + this.options.width + ',height=' + this.options.height + ',location=' + this.options.location + ',menubar=' + this.options.menubar + ',toolbar=' + this.options.toolbar + ',scrollbars=' + this.options.scrollbars + ',resizable=' + this.options.resizable + ',status=' + this.options.status;
        if (this.options.top !== "")
        {
            openoptions += ",top=" + this.options.top;
        }
        if (this.options.left !== "")
        {
            openoptions += ",left=" + this.options.left;
        }
        window.open(this.options.url, this.options.name, openoptions);
        return false;
    }
}; // end of ASD.Window


/**
 *    when using removeTextboxText, set the initial/default text of the input before calling
 */
ASD.removeTextboxText = function(elemId)
{
    if ($(elemId) && $(elemId).value === $(elemId).initText)
    {
        $(elemId).value = "";
    }
};

ASD.setTextboxText = function (elemId)
{
    if ($(elemId) && $(elemId).value === "")
    {
        $(elemId).value = $(elemId).initText;
    }
};

ASD.prepareTextFieldWithInfoTextToSubmit = function(textBoxId)
{
    if ($(textBoxId) && $(textBoxId).value == $(textBoxId).initText)
    {
        ASD.removeTextboxText(textBoxId);
    }
};

ASD.setupSearchForSchoolForm = function()
{
    var formButton = $('find-form-header-submit');
    Event.observe(formButton, 'click', function(event)
    {
        Event.stop(event);
        var value = $('stateProvince-header').getValue().escapeHTML();
        $('stateProvince-header').setValue(value);
        var form = $('find-form-header').submit();
    });

};

ASD.submitSubscribeWidget = function (subscribeSubmitButton, suffix)
{
    var page = $F('subscribe_source_page-' + suffix);
    var site = $F('subscribe_source_site-' + suffix);
    var email = $F('subscribe_email-' + suffix);
    var toURL = "/subscribe/" + escape(email) + "/" + escape(site) + "/" + escape(page);

    ASD.Window.open({
        url:toURL,
        width:520,
        height:350
    });
};

ASD.setZebraStripes = function()
{
    var evens = $$('.table-zebra tr:nth-child(odd)');
    if (evens)
    {
        evens.each(function(tr)
        {
            tr.addClassName('zebra-fill');
        });
    }
};

ASD.getControllerPath = function()
{
    var controllerPath = "";
    var currUrl = window.location.href;
    var segments = currUrl.split("/");
    if (segments.size() >= 3)
    {
        controllerPath = segments[3]; //http, blank, domain, controllerPath
    }
    return controllerPath;
};

ASD.getPathToHighlight = function(deg, spec)
{
    var urlPath = "";
    var urlPrefix = ASD.getControllerPath(); // substring first / after ://, to next / (context root)
    if (urlPrefix != "")
    {
        if (!deg.empty() && !spec.empty())
        {
            // both exist
            urlPath = "/" + urlPrefix + "/" + deg + "/" + spec;
        } else if (!spec.empty())
        {
            // only specialization
            urlPath = "/" + urlPrefix + "/all-degrees/" + spec;
        } else if (!deg.empty())
        {
            // only degree
            urlPath = "/" + urlPrefix + "/" + deg;
        }
    }
    return urlPath;
};

ASD.setHighlightLeftNav = function()
{
    // implemented in featured and faqs JavaScript files
};

ASD.setSpecializationDropdown = function()
{
    // implement in featured.js
};

ASD.expandLeftNavForShortBody = function()
{
    // left-hand nav: expand body to height of left-hand nav
    var mainBody = $$('.asd-main')[0];
    var leftNav = $('left-nav-id');
    if (mainBody && leftNav)
    {
        var mainHeight = mainBody.getHeight();
        var leftNavHeight = leftNav.getHeight();
        if (leftNavHeight > mainHeight)
        {
            mainBody.style.height = leftNavHeight + "px";
        }
    } // end if main body
};

ASD.setAnchorToExternalToPopNewWindow = function()
{
    // markup validation-compliant solution for target <a> attribute
    // handle multiple campus Request Information content toggle
    var elements = Element.select($(document), "a.external");
    var element;//, id, toggler;
    elements.each(function(item)
    {
        Event.observe(item, 'click', function(event)
        {
            ASD.Window.open({
                url: item.href,
                width:700
            });
            Event.stop(event);
        });
    });
};

/**
 * Sets up the fancy make-blank-on-click for textboxes. It captures the original
 * text so we can replace it if they leave it blank.
 */
ASD.setupTextBoxForClickReplacement = function(textElementID, submitElementID, defaultText)
{
    var textbox = $(textElementID);
    if (textbox)
    {
        textbox.initText = defaultText;

        textbox.observe('focus', function(event)
        {
            ASD.removeTextboxText(textbox);
        });

        textbox.observe('blur', function(event)
        {
            ASD.setTextboxText(textbox);
        });

        if ($(submitElementID))
        {
            $(submitElementID).observe('click', function(event)
            {
                ASD.prepareTextFieldWithInfoTextToSubmit(textbox);
            });
        }
    }
};

ASD.setupHoverButtons = function()
{
    var hoverLinks = $$('.hover-button');
    if (hoverLinks)
    {
        hoverLinks.each(function(each)
        {
            Event.observe(each, 'mouseover', function(event)
            {
                var image = each.down();
                if (!image)
                    image = each;
                image.src = image.src.replace("-btn", "-btn-on");
            });
            Event.observe(each, 'mouseout', function(event)
            {
                var image = each.down();
                if (!image)
                    image = each;
                image.src = image.src.replace("-btn-on", "-btn");
            });
        });
    }
};

ASD.setupHoverSubmitButton = function()
{
    var hoverLinks = $$('.submit');
    if (hoverLinks)
    {
        hoverLinks.each(function(each)
        {
            Event.observe(each, 'mouseover', function(event)
            {
                each.addClassName('over');
            });
            Event.observe(each, 'mouseout', function(event)
            {
                each.removeClassName('over');
            });
        });
    }
};

document.observe("dom:loaded", function()
{
    // highlight left nav for any implementing page
    ASD.setHighlightLeftNav();
    ASD.setSpecializationDropdown();
    // set zebra stripes on tables
    ASD.setZebraStripes();

    ASD.setupTextBoxForClickReplacement('stateProvince-header', 'find-form-header-submit', 'Enter a zip or state');
    ASD.setupTextBoxForClickReplacement('zipfilterLocation', 'zipfilterSubmit', 'State / ZIP');
    // setup button catcher for onclick
    ASD.setupSearchForSchoolForm();

    // Subscribe Footer Submit button
    ASD.setupHoverButtons();
    // setup hovers for submit buttons
    ASD.setupHoverSubmitButton();
    /*
     Impl:  Each field has a suffix added to the end becasue ID's can be duplicated
     subscribe_email-<suffix> (for all elements)
     */
    ['subscribe_submit-footer','subscribe_submit-widget'].each(function(id)
    {
        if ($(id))
        {
            var fields = id.split('-');
            if (!fields)
            {
                return;
            }
            var emailField = 'subscribe_email-' + fields[1];
            $(id).observe('click', function(event)
            {
                ASD.prepareTextFieldWithInfoTextToSubmit(emailField);
                ASD.submitSubscribeWidget(id, fields[1]);
            });

            $(emailField).initText = $F(emailField);
            $(emailField).observe('focus', function(event)
            {
                ASD.removeTextboxText(emailField);
            });
            $(emailField).observe('blur', function(event)
            {
                ASD.setTextboxText(emailField);
            });
        }
    });
    // left nav expansion if body is shorter
    ASD.expandLeftNavForShortBody();
    ASD.setAnchorToExternalToPopNewWindow();
    // OpenCMS Slot
    var footer = $('ft');
    if (footer)
    {
        var footerOffset = $('ft').positionedOffset();
        if (footerOffset && footerOffset.top < 600)
        {
            $$(".cms-content-slot-placeholder").each(
                function(slot)
                {
                    var slotOffset = $(slot).positionedOffset();
                    if (slotOffset.top <= footerOffset.top)
                    {
                        slot.style.height = (footerOffset.top - 100) + "px";
                    }
                }
                );
        }
    } // end if footer

    // page: exception
    var displayErrors = $('displayErrors');
    if (displayErrors)
    {
        Event.observe(displayErrors, 'click', function()
        {
            var exception = $('exception');
            if (exception)
            {
                exception.toggle();
            }
            var exceptionContent = $('exception-content');
            if (exceptionContent)
            {
                exceptionContent.toggle();
            }
        });
    }
});
