/*
Modernizr test for cssgradients, excluding old webkit syntax
*/
Modernizr.addTest('lineargradient', function () {
	var test = document.createElement('div'),
		prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
		str1 = 'background-image:',
		str2 = 'linear-gradient(left top,#9f9, white);';

	test.style.cssText =  (str1 + prefixes.join(str2 + str1)).slice(0,-str1.length);
	return ((''+test.style.backgroundImage).indexOf('linear-gradient') !== -1);
});

/*
Mini jQuery plugins: outerHTML & equalHeights
*/
(function($) {
	$.fn.outerHTML = function() {
		return $('<div></div>').append(this.clone()).html();
	};
	$.fn.equalHeights = function() {
		h = 0;
		this.each(function() {
			if($(this).height() > h) {
				h = $(this).height();
			}
		});
		return this.each(function() {
			$(this).height(h);
		});
	}
})(jQuery);

var MNMC = MNMC || {};
MNMC.pages = {
	common: {
		init: function() {
			MNMC.components.autocomplete.init();
			$('img.label').length ? MNMC.components.img.bar() : null;
			$('div.tabs').length ? MNMC.components.tabs() : null;
			$('div.accordion').length ? MNMC.components.accordion() : null;
			$('div.callout-boxes').length && Modernizr.flexbox == false ? MNMC.components.boxes() : null;
			$('div.featured-gallery').length ? MNMC.components.featuredGallery() : null;
			$('#top-articles').length ? MNMC.components.topArticleSwitcher() : null;
			$('div.media-library div.video-box').length ? MNMC.components.videoSlide() : null;
			$('div.audio-box').length ? MNMC.components.boxFlip() : null;
			$('div.article-callout-spotlight').length && Modernizr.flexbox == false ? MNMC.components.articleCalloutSpotlight() : null;
		},
		finalize: function() {
			$('input').placeholder();
		}
	},
	home: {
		init: function() {
			MNMC.components.mainFeatureCycle.init();
			MNMC.components.alertsDropDown();
		}
	}
};

MNMC.components = {
	accordion: function() {
		$('div.accordion').accordion({
			active: false,
			autoHeight: false,
			collapsible: true
		});
	},
	autocomplete: {
		init: function() {
			this.site();
			this.specialties();
		},
		site: function() {
			$.widget('custom.categoryautocomplete', $.ui.autocomplete, {
				_renderMenu: function(ul, items) {
					var self = this,
						currentCategory = "";
					$.each(items, function(index, item) {
						if (item.section != currentCategory) {
							ul.append('<li class="ui-menu-item ui-autocomplete-category"><span>' + item.section + '</span></li>');
							currentCategory = item.section;
						}
						self._renderItem(ul, item);
					});
				}
			});
			$('#sitesearch').categoryautocomplete({
				delay: 1,
				source: '/assets/scripts/SearchCustom.ashx',
				appendTo: '#search',
				focus: function() {
					return false;
				},
				select: function(event, ui) {
					window.location = ui.item.value;
					return false;
				}
			});
		},
		specialties: function() {
			$('#FooterSpecialtiesSearch').autocomplete({
				source: '/assets/scripts/SpecialtiesAndServices.ashx',
				minLength: 2,
				select: function(event,ui) {
					this.value = ui.item.value;
					document.getElementById('search-ss').submit();
				}
			});
			$('#HeaderSpecialtiesSearch').autocomplete({
				source: '/assets/scripts/SpecialtiesAndServices.ashx',
				minLength: 2,
				open: function(event, ui) {
					$('.ui-autocomplete').addClass('specialty-and-services-dropdown').mouseover(function() {
						$('#primary').find('.advanced').addClass('active');
					});
				},
				close: function() {
					$('#primary ').find('.advanced').removeClass('active');
					$('body').find('.specialty-and-services-dropdown').removeClass('specialty-and-services-dropdown');
				},
				select: function(event,ui) {
					this.value = ui.item.value;
					document.getElementById('search-ssHead').submit();
				}
			});
		}
	},
	boxes: function() {
		$('div.callout-boxes').each(function() {
			$(this).find('div.box').equalHeights();
		});
	},
	featuredGallery: function() {
		$('div.featured-gallery').each(function() {
			$("div.featured-gallery a").colorbox({
				current: "",
				fixed: true
			});
		});
	},
	img: {
		bar: function() {
			$('img.label').each(function() {
				$img = $(this),
					w = $img.attr('width'),
					ow = $img.outerWidth(),
					title = $img.attr('title'),
					klass = $img.attr('class');
				imgNew = '<div class="' + klass + '" style="width:' + w + 'px">';
				imgNew += $img.clone().removeAttr('class').outerHTML();
				imgNew += '<span class="strip" style="width:' + w + 'px">' + title + '</span>';
				imgNew += '</div>';
				
				$img.replaceWith(imgNew);
			});
		}
	},
	articleCalloutSpotlight: function() {
		$('div.article-callout-spotlight').each(function() {
			$bd = $(this).find('.bd'),
			$paper = $(this).find('.paper'),
			$sec = $(this).find('.secondary'),
			  ph = $paper.height(),
			  sh = $sec.outerHeight();
			  
			  if (ph > sh) {
			  	$bd.find('.secondary').height(ph);	
			  } else {
			  	$bd.find('.paper').height(sh);
			  }
		});
	},
	mainFeatureCycle: {
		init: function() {
			this.bindEvents();
			$('html.lte7').length ? $('#main-features-pager').prepend(' ') : null;
		},
		bindEvents: function() {
			$('#main-features-rotator').cycle({
				speed:			1000,
				sync:			0,
				timeout:		6000,
				pager:			'#main-features-pager',
				pagerAnchorBuilder: function(index, slide) {
					return '<li>' + (index+1) + '</li>';
				}
			});
		}
	},
	alertsDropDown: function() {
		$('#alerts').delegate('.reveal-alerts', 'click', function(e) {
			$(this).siblings('div').slideToggle(500);
			$(this).children('p').text($(this).children('p').text() == 'Click to hide' ? 'Click to reveal more' : 'Click to hide').toggleClass('alert-toggled');
			
		});
	},
	tabs: function() {
		$('div.tabs').tabs();
	},
	topArticleSwitcher: function() {
		$container = $('#top-articles');
		$container
			.find('article')
			.hide()
			.first()
			.show();
		$('#top-articles-nav').delegate('li', 'click', function(e) {
			i = $(this).index();
			$(this).siblings().removeClass('current');
			$(this).addClass('current');
			$container.find('article:visible').fadeOut(200 , function() {
				$container.find('article').eq(i).fadeIn(200);
			});
		});
	},
	videoSlide: function() {
		$video = $('.video-box');
		$video
			.find('.hd')
			.css({'height':'0', 'display':'none'})
			.first()
			.css({'height':'132px	', 'display':'block'});
		$video
			.removeClass('active-media')
			.eq(0).addClass('active-media');
		$('.video-box').delegate('.bd', 'click', function(e) {
			if ( $(this).parent().hasClass('active-media') ) {
				$(this).parent().removeClass('active-media');
				$(this).siblings('.hd').animate({'height':'0'}, 750);
			} else {
				$(this).parent().addClass('active-media');
				$(this).siblings('.hd').css('display', 'block').animate({'height':'132px'}, 750);
			}
		});
	},
	boxFlip: function() {
		if ( $('body').hasClass('ie6') ) {
			// Do nothing
		} else {
			$('.audio-clip').delegate('h3', 'click',function(e){
				var elem = $(this).parent();
				
				if ( elem.data('flipped') ) {
					elem.revertFlip();
					elem.data('flipped',false);
					elem.removeClass('flipped');
				} else {
					elem.flip({
						direction:'lr',
						speed: 350,
						color: '#FFF',
						onBefore: function(){
							elem.html(elem.siblings('.audio-controls').html());
							elem.addClass('flipped');
						}
					});
					elem.data('flipped',true);
				}
			});
		}
	}
};

UTIL = {
	fire: function(func,funcname, args){
		var namespace = MNMC;
		
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace.pages[func] && typeof namespace.pages[func][funcname] == 'function'){
			namespace.pages[func][funcname](args);
		}
	},
	loadEvents: function() {
		var bodyId = document.body.id;
		
		UTIL.fire('common');
		
		$.each(document.body.className.replace(/(-)([a-z])/g,function(a,b,c){return c.toUpperCase()}).split(/\s+/),function(i,classnm){
			UTIL.fire(classnm);
			UTIL.fire(classnm,bodyId);
		});
		
		UTIL.fire('common','finalize');
	}
};

$(function() { UTIL.loadEvents() });

window.log = function(){
	log.history = log.history || [];
	log.history.push(arguments);
	if(this.console){
		console.log(Array.prototype.slice.call(arguments));
	}
};

(function(doc){
	var write = doc.write;
	doc.write = function(q){ 
		log('document.write(): ',arguments); 
		if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
	};
})(document);

