$(function () {
$.fn.delegatePopupAnchors = function(what) {
	$(what).delegate('a[rel=appendix], a[rel=glossary]', 'click', function(e) {
		
	    var link = $(this);
	    var contentRef = link.attr('href');
	
	    var container = $('<div class="throbber iePngFix"><div class="throbberImg"></div></div><div class="popupTop iePngFix"></div><div class="popupBody iePngFix"></div><div class="popupBase iePngFix"></div>');
	
	    var body =container.filter('.popupBody');
	
	    var title = $('<h1></h1>').appendTo(body);
	   $('<a class="close iePngFix" href="javascript:void(0)"></a>').appendTo(container.filter('.popupTop')).click(function() {
	       $(this).trigger('close');
	   });
	   	
	    if(contentRef.charAt(0) == '#') {
	        // clone and show existing DOM
	        var content = $(contentRef).clone().removeAttr('id').show().appendTo(body);
	        title.text(content.attr('title'));
	    } else {
	    	
	    	if (link.attr('rel').toLowerCase() == "glossary") {
	    		var img = $('<img />');
	    		img.addClass('slide');
	    		
	    		body.append($('<h3>').text(link.attr('title')).addClass('slideTitle'));
	    		
	    		body.append(img);
				
				img.load(function () {
					setTimeout(function () {
						body.trigger('contentchanged');
						container.parent().removeClass('popupAjaxPending');
						
					},0);
				});
				img.attr('src', contentRef);
				
    	    } else {
	    		
				// load popup content
			    body.append('<div class="loadingPlaceholder"></div>');
			    title.text('Loading...');
			
		        body.load(contentRef, function() {
		            title.text(body.children('[title]:first').attr('title'));
		            body.removeClass('loadingPlaceholder').trigger('contentchanged');
		            container.parent().removeClass('popupAjaxPending');
		            $.fn.delegatePopupAnchors('.popup');
		        });
		        
	        }
	    }
	
	    container.popup();
		
	    // rig asynchronous forms
			container.delegate('form', 'submit', function(e){
				e.preventDefault();

				var form = $(this);

				container.find('p.success').hide();
				container.find('p.error').remove();
				container.addClass('popupAjaxPending');

				$.post(form.attr('action'), form.serialize(), function(data){
					container.removeClass('popupAjaxPending');

					if (/<title>\s*Error\s*<\/title>/.test(data)) {
						var errorMatch = /<ul>\s*<li>(.*?)<\/li>/.exec(data);
						$('<p class="error"></p>').appendTo(container.find('fieldset:last')).hide().fadeIn().text(errorMatch[1]);
					} else {
						container.find('p.success').show().prevAll().hide();
						form.attr('action', 'javascript:void(0)'); // prevent further form subit

						// special handling if marked for redirect/reload
						var redirect = form.attr('data-redirect');
						if(redirect == null || redirect == '')
							location.reload(true); // force refresh even if cached
						else
							location.href = redirect;
					}

					form.trigger('contentchanged');
				});

				return false;
			});

	    
	    e.preventDefault();
	    return false;
	});
};

$.fn.delegatePopupAnchors('#userDashboard, #forgotPasswordForm, #footer, #headerLogin, #loginLink, #mediaAttachments');

});







(function($) {

    var ie6 = $.browser.msie && /^6[.]/.test($.browser.version);

    $.fn.popup = function(isPermanent) {
    
    	//Close existing popups
    	$('div.popup').trigger('close');
    
        // measure before any changes
        var bodyHeight = $(document).height();

        // insert overlay markup right under root element
        var overlay = $('<div></div>').appendTo($('body'));
		      
        var background = $('<div class="popupBackground iePngFix"></div>').appendTo(overlay);
        var popup = $('<div class="popup popupAjaxPending"></div>').appendTo(overlay);
	  	
	  	// append the content
        this.appendTo(popup);

        // schedule focus on first input
        setTimeout(function() { popup.find('label:first').focus(); }, 0);

        // redirect focus from any element outside the popup back to first input
        // NOTE: the handler detaches self if the popup is no longer visible
        if(!ie6) $('*').live('focus', function(e) {
            if($(e.target).parents().index(popup) < 0) {
                // detach ourselves if the popup was dismissed
                if(overlay.parents().index($('body')) < 0) {
                    $('*').die('focus', arguments.callee);
                    return;
                }

                $(this).blur();
                popup.find('label:first').focus(); // focus on first input if available
                return false;
            }
        });

        // required CSS for positioning
        overlay.css({
            position: 'absolute',
            top: 0, left: 0, width: '100%', height: bodyHeight,
            'z-index': 500
        });

        background.css({
            position: 'absolute',
            top: 0, left: 0, width: '100%', height: '100%'
        });

        // take out of flow first, for proper width calculation
        popup.css({
            position: 'absolute',
            'overflow': 'hidden',
            top: $(window).scrollTop() + $(window).height() * 0.5, left: '50%'
        });

        // force the popup width and height (for later content changes)
        var popupWidth = popup.width();
        var popupHeight = popup.height();

        popup.css({
            'width': popupWidth,
            'height': popupHeight,
            'margin-left': -(popupWidth / 2),
            'margin-top': -(popupHeight / 2),
            'text-align': 'left'
        });
        
        var throbber = popup.find('.throbber');
        
        throbber.css('height', popupHeight - 123);
        

        

        // listen for content change hook for fancy resizing
        popup.bind('contentchanged', function() {
            var oldHeight = popupHeight;
            popup.stop(true); // stop prior animation

            popup.css('height', 'auto'); // NOTE: need to reset height for proper measuring
            popupHeight = popup.height();

            popup.css('height', popupHeight);
            popup.css('margin-top', -(popupHeight / 2));
            
            throbber.css('height', popupHeight - 123);
            
            });

        // event to close popup
        popup.bind('close', function() {
            if(isPermanent)
                return;

            overlay.remove();
            popup.unbind('close', arguments.callee);
        });

        // clicking background should close the popup
        background.click(function() { popup.trigger('close'); });

        return this;
    }

})(jQuery)

