
Array.max = function( array ){
    return Math.max.apply( Math, array );
};

function siteInit()
{
    // while we're here, add the icon to lis containing a 3rd level ul
    $('#mainmenu ul ul').parent().addClass('hasSubmenu').parent().addClass('hasSubmenu');

    // and then adjust menu sizes
    $('#mainmenu > li, #mainmenu > li ul li').map(adjustMenuSizes_checkCurrentItem);

    // adjust the right side submenus from falling off the side of the page
    adjustRightSubmenus();

    // valign the sidebar buttons
    valignSidebarButtons();

    // make sure quickpop adjusts itself on window resize
    $(window).resize(quickPopup_resize);

    // add filler objects if needed
    //$(window).load(addFillers);

    // additional background objects
    createAdditionalBackgroundObjects();
}

function createAdditionalBackgroundObjects()
{
    for (var x=5; x >= 1; x--)
        $('<div id="addtl-bkg-'+x+'"></div>').prependTo('body');
}

function addFillers()
{
    $('<b class="vertical-filler-container"><b></b><b></b></b>').appendTo('.add-vertical-filler');
    adjustFillers();
}

function adjustFillers()
{
    var maxHeight = 0;
    $('.content, .sidebar').each(function(){

        var h = this.offsetHeight;
        if (maxHeight < h)
            maxHeight = h;

    });



    $('.vertical-filler-container').each(function (){

        var	container = $(this),
        currentHeight = this.offsetHeight,
        caps = container.find('b'),
        topOffset = caps[0].offsetHeight + this.offsetTop,
        bottomOffset = caps[1].offsetHeight,
        newHeight = (currentHeight - caps[0].offsetHeight - caps[1].offsetHeight) +
        (maxHeight - topOffset - bottomOffset - caps[0].offsetHeight - caps[1].offsetHeight) -
        Number($(caps[1]).css('bottom').replace(/[^0-9]/g,''));

        if (newHeight < 30)
            container.remove();
        else
            container.css('height', newHeight + 'px');
    // need to set position:absolute, add 46px (footer + spacing) to the height or padding-top or something, set top to container.offsetTop
    });
}

function valignSidebarButtons()
{
    var objs = $('a.sidebarBtn').contents().wrap('<span />').parent();

    objs.each(function(){

        var obj = $(this),
        parent = $(obj.closest('a')[0]);

        switch (parent.css('vertical-align'))
        {
            case 'middle':
            {
                obj.css('position','relative').css(
                    'top',
                    Math.floor((parent.height() - obj.height()) / 2) + 'px'
                    );
                return;
            }

            default:
                return;
        }

    });
}

function adjustMenuSizes_checkCurrentItem(idx, currentItem)
{
    // find the UL underneath this list item, the spans in that UL, and the widest item in the list
    var	submenu = $(currentItem).children('ul'),
    objs = submenu.children('li').children('a'),
    maxWidth = Array.max(
        objs.css('display', 'inline').map(function () {
            return this.offsetWidth
            }).toArray()
        );

    objs.css('display', 'block');


    // no submenu? exit
    if (submenu.length == 0)
        return;



    // find out what sort of padding we're dealing with by adding an empty entry, grabbing the width, and immediately removing it
    var tmpListItem = $('<li style="width:auto"><a style="display:inline"></a></li>');
    $(submenu).append(tmpListItem);
    var	paddingOffset = tmpListItem.children('a')[0].offsetWidth,
    minWidth = tmpListItem[0].offsetWidth - Number(tmpListItem.css('border-left-width').replace(/px/, '')) - Number(tmpListItem.css('border-right-width').replace(/px/, ''));
    tmpListItem.remove();

    // we found the min-width (if set, 0 otherwise). we subtracted the border widths (if they exist, 0 otherwise).
    // now, make sure the new width we'll be setting is at least minWidth.
    if (maxWidth < minWidth)
        maxWidth = minWidth;


    // move up from the a tags to the parent lis
    objs = objs.map(function () {
        return $(this).closest('li')[0]
        });

    //add extra space for ie wrapping cutting it too close (cody)
    maxWidth += 5;

    objs.each(function () {
        with($(this))
        {
            css('width', maxWidth + 'px');
            children('a').css('width', (maxWidth-paddingOffset) + 'px');
            children('ul').css('marginLeft', maxWidth + 'px');
            }
    });

    submenu.css('width', maxWidth + 'px');
}

$(siteInit);











function printPage()
{
    window.print();
    return false;
}

function promptForEmailInfo(companyName)
{
    var	theForm = $('<form id="emailSiteForm" method="post" action="'+location.href+'"><p>Please enter the following:</p><input type="hidden" name="sendPage" value="'+location.href+'"></form>'),
    fields = {
        'Recipient Email Address':'send_to',
        'Your Name':'send_from_name',
        'Your Email Address':'send_from_email'
    };

    for (label in fields)
        theForm.append('<label>'+label+'<input type="text" name="'+fields[label]+'" /></label>');

    theForm.append('<label>Comments<textarea name="comments" spellcheck="false">I found this page on the '+companyName+' website and thought you would be interested.</textarea></label>');

    theForm.append('<div class="buttonRow"><button type="button" onclick="submitPromptForEmailInfo()">Send</button><button type="button" onclick="closeQuickPopup()">Cancel</button></div>');

    quickPopup(theForm);

    return false;
}

function submitPromptForEmailInfo()
{
    $('#emailSiteForm p.error').remove();
    $('#emailSiteForm .error').removeClass('error');

    $(window).resize();

    var	theForm = $($('#emailSiteForm')[0]);

    $.post(
        theForm.action,
        theForm.serialize(),
        function (response) {
            if (response.success == 1)
            {
                quickPopup('<p>Your message has been sent!</p>').delay(3000).fadeOut(250, closeQuickPopup);
                return;
            }

            $('input[name=' + response.errorFields.join('], input[name=') + ']').addClass('error');
            $('#emailSiteForm > p').after('<p class="error">Please confirm that all fields have been entered and that you have included valid email addresses.</p>');

            $(window).resize();
        },
        'json'
        );
}

function emailUsBtn_click()
{
    var	theForm = $('<form id="emailSiteForm" method="post" action="'+location.href+'" class="email-us"><input type="hidden" name="emailUs" value="'+location.href+'"><p>Please enter the following:</p></form>'),
    fields = {
        'Name':'name',
        'Phone':'phone',
        'Email':'email'
    };

    for (label in fields)
        theForm.append('<label>'+label+'<input type="text" name="'+fields[label]+'" /></label>');

    theForm.append('<label>Comments<textarea name="comment" spellcheck="false"></textarea></label>');
    theForm.append('<div class="buttonRow"><button type="button" onclick="submitEmailUsBtnContactForm()">Send</button><button type="button" onclick="closeQuickPopup()">Cancel</button></div>');

    quickPopup(theForm);

    return false;
}

function submitEmailUsBtnContactForm()
{
    $('#emailSiteForm p.error').remove();
    $('#emailSiteForm .error').removeClass('error');

    $(window).resize();

    var	theForm = $($('#emailSiteForm')[0]);

    $.post(
        theForm.action,
        theForm.serialize(),
        function (response) {
            if (response.success == 1)
            {
                quickPopup('<p>Your message has been sent!</p>').delay(3000).fadeOut(250, closeQuickPopup);
                return;
            }

            theForm.find('[name=' + response.errorFields.join('], [name=') + ']').addClass('error');
            $('#emailSiteForm> p').after('<p class="error">Please confirm that all fields have been entered and that you have included valid email addresses.</p>');

            $(window).resize();
        },
        'json'
        );
}

function inlineMessage(element, type, contents, prependOrReplaceContents)
{
    if(prependOrReplaceContents == '')
    {
        prependOrReplaceContents = 'prepend';
    }


    //determine type of Message
    var typeClass = '';
    if(type == 'error')
        typeClass = 'inlineMessageError';
    else if(type == 'warning')
        typeClass = 'inlineMessageWarning';
    else if(type == 'notice')
        typeClass = 'inlineMessageNotice';
    else if(type == 'success')
        typeClass = 'inlineMessageSuccess';

    //remove existing message (should only be 1 on a page at this point)
    $('.inlineMessage').remove();

    var newContents = '<div class="inlineMessage ' + typeClass + '">' + contents + '</div>';

    if(prependOrReplaceContents == 'prepend')
    {

        $(element).prepend(newContents);
    }
    else if(prependOrReplaceContents == 'replace')
    {
        $(element).html(newContents);
    }

    //scroll user up to error
    $('html, body').animate({
        scrollTop: $(".inlineMessage").offset().top
    }, 1000);
}

function quickPopup(contents)
{
    if ($('#siteCover').length == 0)
    {
        // IE6 needs the explicit height and width
        var	siteCover = $('<div id="siteCover" style="height:'+$(window).height() + 'px;width:'+$(window).width() + 'px;'+'"></div>'),
        quickPopup = $('<div id="quickPopup"></div>');

        // IE6 also can't handle SELECTs being hidden under anything. This will catch IE7 too (since ie7.js sets the same
        // class to the body regardless of version), but it shouldn't be a big deal.

        $('.ie7_body select').css('visibility', 'hidden');

        //window.quickPopupTimer = setInterval(quickPopup_resize, 250, quickPopup);

        $('body').prepend(siteCover);
        $('body').prepend(quickPopup.append(contents));

        siteCover.click(function () {
            $('#siteCover, #quickPopup').fadeOut(250, closeQuickPopup);
        });

        quickPopup_resize(quickPopup);
    }
    else
    {
        $('#quickPopup').html(contents);
    }

    quickPopup_resizeCover();

    return $('#siteCover, #quickPopup');
}

function closeQuickPopup()
{
    clearInterval(window.quickPopupTimer);
    $('.ie7_body select').css('visibility', 'visible');
    $('#siteCover, #quickPopup').remove();
}

function quickPopup_resize(obj)
{
    try {
        if (obj.length == undefined)
            obj = $('#quickPopup');
        else
            obj[0];
    }
    catch (err) {
        obj = $('#quickPopup');
    };

    // no popup found
    if (!obj.length)
        return;

    var	viewportHeight = $(window).height(),
    newHeight = obj.outerHeight(),
    newTop = Math.floor($(window).height()/2) - Math.floor( newHeight/ 2 );
    //newTop = $(window).scrollTop() + Math.floor($(window).height()/2) - Math.floor( newHeight/ 2 );

    if (viewportHeight <= newHeight)
    {
        obj.css({
            'top':0,
            'position':'absolute'
        });
        return;
    }

    if (newTop < 0)
        newTop = 0;

    obj.css({
        'top': newTop + 'px',
        'position':'fixed'
    });

    var IE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;
    if (IE6)
        $('html,body').animate({
            scrollTop: $('.content').offset().top
            }, 250);


    quickPopup_resizeCover();
}

function quickPopup_resizeCover()
{
    var heights = $('#siteWrapper, #footer, #footer-linkbar').map(function (){
        return $(this).height()
        }),
    docHeight = $(window).height(),
    popupHeight = $('#quickPopup').outerHeight(),
    maxHeight = Math.max(Math.max(heights[0] + heights[1] + heights[2], docHeight), popupHeight);

    $('#siteCover').css({
        'height': maxHeight + 'px',
        'width'	: $(window).width() + 'px'
    });
}

/**
 *
 * This function is run after the Validator library populates fields with errors
 *
 */
function showValidationErrors()
{
//    console.log($('form').find('.error').text());

//    $('form .error').each(function(){
//        //if($(this).val())
//        console.log(this.innerHTML);
//        console.log(this.innerText);
//        console.log($(this).attr('class'));
//        console.log($(this).text());
//        console.log($(this).html().length);
//    })
}

function submitContactForm()
{
    return websiteFormSubmit('contactform', 'Sending...', 'Your message has been sent!');
}

function submitVolunteerForm()
{
    return websiteFormSubmit('volunteerform', 'Sending...', 'Your message has been sent!');
}

function submitCareerForm()
{
    return websiteFormSubmit('careerform', 'Submitting application...', 'Your application has been submitted!');
}

function submitGreetingForm()
{
    return websiteFormSubmit('greetingcardform', 'Sending greeting...', 'Your greeting has been sent!');
}

function submitNewsletterForm()
{
    return websiteFormSubmit($('newsletterform'), 'Submitting...', 'You have been signed up for our newsletter!');
}

function websiteFormSubmit(formID, sendingMsg, completedMsg)
{
    if (document.error_disp_handler && document.error_disp_handler.all_msgs.length > 0)
        return false;

    try
    {
        if (formID.outerHeight)
            var theForm = formID;
    }
    catch (e) {};

    if (!theForm)
        var theForm = $('#' + formID)[0];

    $.post(
        theForm.action,
        $(theForm).serialize(),
        function (response) {
            if (response.success == 1)
            {
                //quickPopup('<p>'+completedMsg+'</p><button class="closeBtn" onclick="closeQuickPopup()">Close</button>').delay(3000).fadeOut(250, closeQuickPopup);
                inlineMessage('.formStyle1', 'success', completedMsg, 'replace');
                theForm.reset();
                //return;
            }
            else if (response.errMsg)
            {
                //quickPopup('<p>'+response.errMsg+'</p><button class="closeBtn" onclick="closeQuickPopup()">Close</button>').delay(3000).fadeOut(250, closeQuickPopup);
                inlineMessage('.formStyle1',  'error', response.errMsg, 'prepend');
            }
        },
        'json'
        );

    //$('#form_container').remove();
    //quickPopup('<p>'+sendingMsg+'</p>');

    return false;
}

function getDirectionsBtn_click()
{
    // disable directions in a popup for the time being
    location.href='/_plugin_/6';
    return false;



    // on the directions page? just scroll to the content section.
    // our code doesn't support multiple gmaps yet.
    if ($('#getDirectionsForm').length != 0)
    {
        $('html,body').animate({
            scrollTop: $('.content').offset().top
            }, 500);
        return false;
    }

    quickPopup('Loading...');
    $.post(
        location.href,
        'getDirections=1',
        quickPopup
        );
    return false;
}

/* maps */
function enterGMapsFromAddrTextbox()
{
    var textBox = $( $('#getDirectionsForm #textfield')[0] ).removeClass('usability');

    if (textBox.val() == textBox[0].directionsUsabilityText)
        textBox.val('');
}

function exitGMapsFromAddrTextbox()
{
    var textBox = $( $('#getDirectionsForm #textfield')[0] );
    if (textBox.val() == '')
        textBox.val(textBox[0].directionsUsabilityText).addClass('usability');
}
function setDirections(fromAddress, toAddress, locale) {
    gdir.load("from: " + fromAddress + " to: " + toAddress,
    {
        "locale": locale
    });
}

function handleMapErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");

}

function submitDirectionsForm()
{
    var	fields = $('#getDirectionsForm input#textfield, #getDirectionsForm select#from'),
    usabilityText = fields[0].directionsUsabilityText,
    values = fields.map(function() {
        return this.value
        }),
    fromAddr = false;

    for (var x=0; x < 2; x++)
    {
        if (values[x] != '' && values[x] != usabilityText)
        {
            fromAddr = values[x];
            break;
        }
    }

    if (fromAddr == false)
        alert('Please enter an address or select a location from the list.');
    else
        setDirections(fromAddr, document.getElementById('toAddress').value, document.getElementById('locale').value);

    /*

	var theform = document.getElementById('getDirectionsForm');
	var fromAddr = document.getElementById('from').value;
	if (fromAddr == '')
	{
		fromAddr = document.getElementById('textfield').value;
	}

	if (fromAddr == '' || fromAddr == directionsUsabilityText)
	{
		alert('Please select a "From" location.');
		return;
	}
	*/

    return false;
}


/* main menu - submenus */
function adjustRightSubmenus()
{
        var	content = $('#contentContainer')[0];
        var siteMaxRight = Number(content.offsetWidth + $(content).offset().left);

        // need to show the submenus since some browsers won't properly calc
        // the offsetWidth if the item hasn't been visible first
        var submenus = $('#mainmenu > li ul').css('left', 'auto');
        var items = submenus.children();

        items.each(function() {

            var right = Number(this.offsetWidth) + Number($(this).offset().left) + Number($(this).css('borderRightWidth').replace(/px/,''));
            if (right > siteMaxRight)
                $(this).css('left', Math.ceil(siteMaxRight - right)+'px').css('position', 'relative');

        });

        submenus.css('left', ''); // rehide the items
}

/* setup slideshows */
function plugin_slideshow_setup()
{
    $(".plugin_slideshow").cycle({
        timeout:10000,
        speed:2500
    });

    //$('.plugin_slideshow img').bind('load', plugin_slideshow_imgLoaded);

    // not triggering load if img is in cache, need to force it
    $('.plugin_slideshow img').one("load",plugin_slideshow_imgLoaded).each(function(){
        if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
            $(this).trigger("load");
    });
}

function plugin_slideshow_imgLoaded(e)
{
    var slideshow = $($('.plugin_slideshow')[0]);

    var slideshowWidth = slideshow.width();
    var slideshowHeight = slideshow.height();

    var imgHeight = $(this).height();
    var imgWidth = $(this).width();

    if (slideshowHeight < imgHeight)
        slideshow.css('height', imgHeight + 'px');

    if (slideshowWidth < imgWidth)
        slideshow.css('width', imgWidth + 'px');

}

function IE6_fixmenu()
{
    $('#mainmenu > li > ul').each(function(){

        var	obj = $(this),
        parent = obj.parent(),
        offsetTop = parent.offset().top,
        width = parent.width(),
        height = parent.height(),
        newTop = (height+offsetTop)+'px',
        newMarginLeft = (-1 * width)+'px';

        obj.css('top', newTop).css('margin-left', newMarginLeft);

    });
}

function showCalendarEvents(day)
{
    $('.calendar-right').addClass('hide');

    if ( $('#calendar-right-' + day).removeClass('hide').length == 0)
    {
        $('#calendar-right-none').removeClass('hide').find('h2 span').html(
            (day == 0) ? '' : ' ' + day
            );
    }

    return false;
}
function showAllCalendarEvents()
{
    if (  $('.calendar-right').not('#calendar-right-none').removeClass('hide').length == 0  )
        showCalendarEvents(0);

    return false;
}

function showEmailUsPopup()
{
    quickPopup('TODO: This popup');
    return false;
}
function showGetDirectionsPopup()
{
    quickPopup('TODO: This popup');
    return false;
}

function RoundedCorners(selectors)
{
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7)
        return IE6RoundedCorners(selectors);

    var	corners = $(
        '<b class="roundedcorners-topleft"></b>' +
        '<b class="roundedcorners-topright"></b>' +
        '<b class="roundedcorners-bottomleft"></b>' +
        '<b class="roundedcorners-bottomright"></b>'),

    func = function () {
        $(selectors).css('position', 'relative').append(corners);
    };

    $(func);
}

function IE6RoundedCorners(selectors)
{
    $(document).ready(function () {

        var	objs = $(selectors),
        resizeFunc = function () {

            var	self = $(this),

            parentPos = self.data('parentObject').offset(),

            parentHeight = self.data('parentObject').outerHeight(),
            parentWidth  = self.data('parentObject').outerWidth(),

            bodyHeight = $(window).height(),
            bodyWidth = $(window).width(),

            classPosition = self[0].className.replace(/^.*-([a-z]+)$/, '$1'),
            isTop = (classPosition.indexOf('bottom') < 0),
            isLeft = (classPosition.indexOf('right') < 0),

            css = {
                'position':'absolute',
                'display':'block',
                'zIndex': '10'
            };


            if (isLeft)
                css.left = parentPos.left + 'px';
            else
                css.right = (bodyWidth - parentPos.left - parentWidth) + 'px';


            if (isTop)
                css.top = parentPos.top + 'px';
            else
                css.bottom = (bodyHeight - parentPos.top - parentHeight) + 'px';


            self.css(css);
        };

        objs.each(function () {

            var parentObject = $(this);

            $(
                '<b class="ie6-roundedcorners-topleft"></b>' +
                '<b class="ie6-roundedcorners-topright"></b>' +
                '<b class="ie6-roundedcorners-bottomleft"></b>' +
                '<b class="ie6-roundedcorners-bottomright"></b>').appendTo($('body')).each(function ()
                {

                var self = $(this);

                self.data('parentObject', parentObject);
                self.resizeFunc = resizeFunc;

                $(window).resize(function () {
                    self.resizeFunc()
                    });
            }
            );

        });

        $(window).resize();
        setInterval('$(window).resize()', 1000);

    });
}
