if (typeof MB == "undefined") {
    var MB = {

        getDomain: function() {
            return ((window.document.domain === undefined) ? (window.document.hostname) : (window.document.domain));
        },

        secureProtocol: function(d) {
            /* switch for production vs. development */
            return ((d.indexOf('media-bistro.com') >= 0 || d.indexOf('qa.mediabistro.net') >= 0) ? ('https') : ('http'));
        },


        bindsiteSearchHandlers: function() {

            /* site search form autocomplete */
            var $tb = $('#gbl-search-tb');
            if ($tb.length < 1) {
                return;
            }
            var $f = $tb.parents('form:first');

            $tb.autocomplete({
                minLength: 3,
                source: function(request, response) {

                    /* keep this value accessible to success handler */
                    var q = request.term;
                    var n = '';
                    if ($('input[name=n]', $f).length) {
                        /* number of results to display per section */
                        n = $('input[name=n]', $f).val();
                    }
                    var url = location.protocol + '//' + MB.getDomain() + '/search/scripts/SiteSearchAutocomplete.asp';

                    $.ajax({
                        type: 'get',
                        url: url,
                        dataType: 'json',
                        data: { q: q, n: n },
                        success: function(data) {

                            /* autocomplete options */
                            response($.map(data, function(item) {
                                return ({
                                    id: item.id,
                                    /* append result type in gray */
                                    /* label: item.label + ' <span class="ui-autocomplete-dim">in ' + item.resultType.charAt(0).toUpperCase() + item.resultType.slice(1) + 's</span>', */
                                    label: item.label + ' in ' + item.resultType.charAt(0).toUpperCase() + item.resultType.slice(1) + 's',
                                    title: item.title,
                                    type: item.resultType,
                                    term: q
                                });
                            }));
                        },
                        error: function(xhr, status) {
                            var $e = $('.error-container', $f);
                            if ($e.length) {
                                $(e).html('(' + xhr.status + ') ' + xhr.statusText);
                                $(e).show();
                            }
                        }
                    });
                },
                open: function(event, ui) {
                    if (0) {
                        var acData = $(this).data('autocomplete');
                        acData.menu.element.find('li').each(function() {
                            var $e = $(this);
                            /* make the search term bold within the individual results */
                            $e.html($e.text().replace(new RegExp('(' + acData.term + ')', 'gi'), '<span class="ui-autocomplete-term">$1</span>'));
                        });
                    }
                },
                focus: function(event, ui) {
                    /* override default behavior of updating textbox's content with autocomplete text */
                    event.preventDefault();
                },
                select: function(event, ui) {

                    /* redirect to job or course details page */
                    switch (ui.item.type) {
                        case 'course':

                            /* log the selected search term */
                            var mid = $('form.gbl-search:first input[name=mid]').val();
                            MB.logKeywordSearch('course', ui.item.term, mid);

                            /* redirect to course details page */
                            var urlTitle = ui.item.title.toString();
                            urlTitle = urlTitle.replace(/\W+$/, '').replace(/\W+/g, '-');
                            window.location = '/' + urlTitle + '-crs' + ui.item.id + '.html?cfkw=' + encodeURI(ui.item.term);
                            break;

                        case 'job':

                            /* log the selected search term */
                            var mid = $('form.gbl-search:first input[name=mid]').val();
                            MB.logKeywordSearch('job', ui.item.term, mid);

                            /* redirect to job details page */
                            window.location = '/joblistings/jobview.asp?joid=' + ui.item.id + '&keyword_filter=' + encodeURI(ui.item.term);
                            break;

                        default:
                            /* unhandled result type */
                            break;
                    }
                    return (false); /* override default */
                }
            });
        },


        /*
        *  calls AJAX script to log course search term
        *
        */
        logKeywordSearch: function(search_type, term, memberID) {

            var url = '';
            switch (search_type) {
                case 'course':
                case 'courses':
                    url = '/courses/scripts/LogCourseSearchTerms.asp';
                    break;
                case 'job':
                case 'jobs':
                    url = '/joblistings/scripts/LogJobSearchTerms.asp';
                    break;
                default:
                    /* unhandled search type */
                    return (false);
            }

            $.ajax({
                method: 'get',
                url: url,
                data: {
                    term: term,
                    memberID: memberID
                },
                async: false
            });
        },

		/*
		 * Manage clock.
		 */
		doTime: function() {
			var formatMinutes = function(i) {
				return (i < 10) ? '0' + i : i;
			};

			var formatHour = function(h) {
				if (h > 12)
					h = h -12;
				else if (h == 0)
					h = 12;

				return h;
			};

			var d = new Date();

			var m = d.getMinutes();
			m = formatMinutes(m);

			var h = d.getHours();
			var am_pm = (h > 11) ? 'PM' : 'AM';
			h = formatHour(h);

			$('.mbtime').html( h + ':' + m + ' ' + am_pm );

			// Update every minute.
			setTimeout('MB.doTime()', 60 * 1000);
		},

		doDate: function() {
			var formatMonth = function(m) {
				var r = '';
				switch(m) {
					case 0:  r = 'January'; break;
					case 1:  r = 'February'; break;
					case 2:  r = 'March'; break;
					case 3:  r = 'April'; break;
					case 4:  r = 'May'; break;
					case 5:  r = 'June'; break;
					case 6:  r = 'July'; break;
					case 7:  r = 'August'; break;
					case 8:  r = 'Septempber'; break;
					case 9:  r = 'October'; break;
					case 10: r = 'November'; break;
					case 11: r = 'December'; break;
				}
				return r;
			};
			
			var d=new Date();
			var m = formatMonth(d.getMonth());
			var dy = d.getDate();
			var y = d.getFullYear();
			$('.mbdate').html(m + ' ' + dy + ', ' + y);
		}

    };
}

if (typeof MB.Lightbox == "undefined") {

    MB.Lightbox = {

        login_form_uri: location.protocol + '//' + MB.getDomain() + '/memberscenter/login/lightbox.asp',
        logout_uri: MB.secureProtocol(MB.getDomain()) + '://' + MB.getDomain() + '/memberscenter/logout.asp',

        /* 
        * Dismisses dialog. 
        * - which: JQuery selector used to identify dialog within DOM 
        */
        dismissDialog: function(sel) {
            if (sel === undefined) {
                var sel = '#mbLightbox';
            }
            var $e = $(sel);
            if ($e.length > 0) {
                $e.dialog('destroy');
            }
        },


        applyLogin: function(ref) {

            if (ref == 'bypass') {
                MB.Lightbox.dismissDialog();
            } else if (ref) {
                window.location = ref;
            } else {
                window.reload();
            }
        },

        /* 
        * Opens global modal dialog containing login form.
        * - ref (optional) Url to load after the login is finished successfully.
        *   If no argument is supplied the current page is reloaded.
        */
        loginDialog: function(ref) {

            /* url to load in frame */
            var ref_uri = ((ref === undefined) ? (window.location.href) : (ref));
            var content_uri = MB.Lightbox.login_form_uri + '?ref=' + ref_uri;

            /* fetch dialog content */
            $('#mbLightbox iframe:first').attr('src', content_uri);

            /* open dialog after markup is fully loaded */
            $('#mbLightbox iframe:first').load(function() {

                /* open dialog in load handler to insure content is all on-hand */
                $('#mbLightbox').dialog({

                    /* dialog properties */
                    width: 480,
                    height: 'auto',
                    modal: true,
                    dialogClass: 'mb-dialog-notitle',
                    closeOnEscape: true,
                    open: function(event, ui) {
                        /* close the dialog on mouseclick outside of dialog */
                        $('.ui-widget-overlay').click(function() {
                            MB.Lightbox.dismissDialog('#mbLightbox');
                        });
                    },
                    close: function(event, ui) {
                        $('.ui-widget-overlay').unbind('click');
                    }
                });

                /* make sure this only gets fired once */
                $('#mbLightbox iframe:first').unbind('load');
            });
        },


        logout: function(ref) {
            var url = MB.Lightbox.logoutUrl + '?ref=' + ((ref) ? (escape(ref)) : (escape(window.location.href)));
            window.location = url;
        },


        setLoginButtonsHandlers: function() {
            $('.login-dlg .mb-button')
	        .hover(
		        function() {
		            $(this).addClass('ui-state-hover');
		        },
		        function() {
		            $(this).removeClass('ui-state-hover');
		        }
	        )
	        .mousedown(function() {
	            $(this).addClass('ui-state-active');
	        })
	        .mouseup(function() {
	            $(this).removeClass('ui-state-active');
	        });
        }
    };
}


$(function() {
	// Sitenav search box
	MB.bindsiteSearchHandlers();

	// Kick off the clock.
	MB.doTime();
	MB.doDate();
});

