/*jslint browser: true */
/*global $, resourcePath, swfobject, addthis_open, addthis_close, addthisUrl, addthisTitle, addthis_sendto, window: true, self: true */
var addthis_options;
function removeError(el)
{
    el.parent('li').removeClass('error').find('> label.error').remove();
}
function enableEl(el, enabled)
{
    if (enabled)
    {
        el.removeAttr('disabled').removeClass('disabled').parent('span.primary').removeClass('disabled');
    }
    else
    {
        el.attr('disabled', true).addClass('disabled').parent('span.primary').addClass('disabled');
    }
}
function sizeButtons(parentEl)
{
    var button, width, outerWidth, height, copy, copyButton, minWidth;
    parentEl.find('span.primary').each(function () {
        button = $(this).find('a, input');
        if ($(this).is(':visible'))
        {
            width = button.width();
            outerWidth = button.outerWidth();
            height = button.outerHeight();
        }
        else
        {
            copy = $(this).clone().appendTo($(this).parent());
            copyButton = copy.find('a, input');
            width = copyButton.parent().css('position', 'absolute').css('top', '-10000px').show().end().innerWidth();
            outerWidth = copyButton.outerWidth();
            height = copyButton.outerHeight();
            copy.remove();
        }
        if ($.browser.msie && button.is('input'))
        {
            minWidth = parseInt(button.css('min-width'), 10);
            if ($.browser.version === '6.0')
            {
                outerWidth = outerWidth < minWidth ? minWidth : outerWidth;
                $(this).css('position', 'relative').height(height + 'px');
                button.css('position', 'absolute').css('top', '0').css('left', '0');
            }
            else if ($.browser.version === '7.0')
            {
                button.width(width + 'px');
                outerWidth = width < minWidth ? minWidth : width;
            }
        }
        $(this).width(outerWidth + 'px');
    });
}
function showModal(el)
{
    var left;
    if ($('body #modalBackground').length === 0)
    {   // add a modal background
        $('body').prepend('<div id="modalBackground" style="width:' + $(document).width() + 'px;height:' + $(document).height() + 'px;"></div>');
    }
    if (!el.is(':visible'))
    {
        left = (($('#content').width() - el.width()) / 2) + $('#promo').width();
        el.show().css('left', left + 'px').css('top', '50px').insertAfter($('body #modalBackground'));
        sizeButtons(el);
    }
}
function closeModal(el)
{
    $('#modalBackground').remove();
    el.hide();
}
function playerStatusChange(oldState, newState)
{
    if (newState === 'COMPLETE')
    {
        $('#playerPromo').show();
    }
    else
    {
        $('#playerPromo').hide();
    }
}
function characterLimit(el, max)
{
    if (el.length > 0)
    {
        el.find('~ p').eq(0).html('(<span class="limit">' + (max - el.val().length) + '</span> characters available)').end().end()
            .bind('keypress', function (e) {
                if (el.val().length >= max)
                {
                    if (e.which !== 0 && e.which !== 8)
                    {
                        return false;
                    }
                }
            }).bind('keyup change', function () {
                var cleaned, newlineCount;
                newlineCount = (el.val().match(/\n/gi) === null) ? 0 : el.val().match(/\n/gi).length;
                if (el.val().length >= (max - newlineCount))
                {
                    cleaned = el.val().replace(/\t/, '   ').replace(/\r/, '').replace(/\n$/, '');
                    newlineCount = (cleaned.match(/\n/gi) === null) ? 0 : cleaned.match(/\n/gi).length;
                    el.val(cleaned.substring(0, (max - newlineCount)));
                }
                removeError(el);
                newlineCount = (el.val().match(/\n/gi) === null) ? 0 : el.val().match(/\n/gi).length;
                el.parent().find('span.limit').text(max - newlineCount - el.val().length);
            });
    }
}
$(function () {
    /* jQuery bug fix */
    $.browser.version = $.browser.msie && /msie 7\.0/i.test(navigator.userAgent) ? "7.0" : $.browser.version;

    var path, imgLoading;
    path = location.pathname.substring(1) ? location.pathname.substring(1) : '/';
    if (path)
    {
        $('a[href$="' + path + '"]').addClass('disabled').parent('li').addClass('disabled').end().click(function () {
            return false;
        });
    }

    if ($('form.patient').length > 0)
    {
        imgLoading = new Image();
        imgLoading.src = resourcePath + '/images/uploading.gif';

        $('form.patient :submit').click(function () {
            var message, overlay;
            message = ($('#patientMessage').length > 0 && $('#patientMessage').val().length > 0) ? $('#patientMessage').val() : 'It may take several minutes for your information to upload.';
            overlay = '<div id="submitOverlay" style="width:' + $(document).width() + 'px;height:' + $(document).height() + 'px;"></div><div id="submitMessage"><p><strong>Please be patient</strong> ' + message + '</p></div>';
            $('body').prepend(overlay);
            $('#submitMessage').append($(imgLoading));
        });
    }

    $('a.external').click(function () {
        window.open(this.href);
        return false;
    });
    // fix for submit buttons not having a wrapper
    $('.buttons > a, .buttons > input').wrap('<span class="primary"></span>');
    $('.buttons span, li, a').hover(
        function () {
            $(this).addClass("hover");
        },
        function () {
            $(this).removeClass("hover");
        }
    );
    $('a.close').click(function () {
        window.close();
    });
    $('body.popupWindow a.popback').click(function () {
        if (window.opener !== null)
        {
            if (window.opener.location !== this.href)
            {
                window.opener.location = this.href;
            }
            self.close();
        }
    });
    $('div.thumbnail .popup').click(function () {
        var features = 'menubar=no,location=no,toolbar=no,scrollbars=no,width=710,height=500';
        window.open(this.href, 'popup', features);
        return false;
    });
    $('.newWindow').click(function () {
        window.open(this.href, 'newWindow');
        return false;
    });
    $('.vcard').each(function () {
        var hCardId = $(this).attr('id') === null ? '%hcard' : $(this).attr('id');
        $(this).after('<p><a href="http://feeds.technorati.com/contacts/' + window.location + '/%23' + hCardId + '">Add to Address Book</a></p>');
    });
    $('#player').each(function () {
        var flashvars, params, attributes;
        flashvars = {
            height: "257",
            width: "320",
            file: document.getElementById("videoFile").value,
            id: this.id,
            displayheight: '240',
            displaywidth: '320',
            autostart: 'true',
            showdigits: 'false',
            usefullscreen: 'false',
            frontcolor: '0x373771',
            backcolor: '0xc7c7e2',
            enablejs: 'true'
        };
        params = {
            wmode: "opaque",
            allowscriptaccess: "always",
            allowfullscreen: "true"
        };
        attributes = {
        };
        swfobject.embedSWF("/flash/mediaplayer.swf", "playerArea", "320", "257", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
    });
    // Add This
    addthis_options = 'email, favorites, facebook, twitter, myspace, digg, stumbleupon, delicious, google, more';
    $('.navGlobal li#share_this a')
        .mouseover(function () {
            return addthis_open(this, '', addthisUrl, addthisTitle);
        })
        .mouseout(function () {
            addthis_close();
        })
        .click(function () {
            return addthis_sendto();
        });
    $('#promoReplay').click(function () {
        document.getElementById('playerArea').sendEvent('playpause');
        return false;
    });
    $('#promoComment').click(function () {
        $('#comment').focus();
        $('html, body').animate({scrollTop: $('#comment').offset().top}, 1000);
        return false;
    });
    // birthday reminders
    $('#birthday_reminders').each(function () {
        enableEl($(this).find('input#submit'), false);
        $(this).find('li.checkbox[id^="remind"]').find('> input').removeAttr('checked').end() // unchecked email checkbox
        .find('input[type="checkbox"]').bind('click', function () {
            enableEl($('#birthday_reminders input#submit'), $('#birthday_reminders li.checkbox[id^="remind"] > input:checked').length !== 0);
        }).end()
        .find('select, input[type="text"]').bind('change keyup', function () {
            $('#birthday_reminders input#remind_' + parseInt($(this).attr('id').replace(/([a-z]*_)*/, ''))).attr('checked', 'checked');
            enableEl($('#birthday_reminders input#submit'), $('#birthday_reminders li.checkbox[id^="remind"] > input:checked').length !== 0);
        });
    });
    characterLimit($('#share_ecard #optional_message'), 200);
    $('body.popupWindow:has(#content > #eCard)').find('#header').hide();
});
