/**
 * @author Aaron.Lisman
 */

if (!window.console) {
	window.console = { log:function(){} };	
}


// Custom Void
var Void=function(){};$.fn.VoidLink=function(){return $(this).attr('href','javascript:Void()')};

$(function() { Site.Init(); }) ;

var Site = {
	
	// runs on page load
	Init: function() {
		
		// call Page object PreInit if exists
		if ( this.Page && typeof this.Page.PreInit == 'function' ) {			
			this.Page.PreInit();
		}
				
		this.CreateNav();
		this.CorrectCSS();
		this.InitGlobalModules();
		this.SetModuleLinkPosition.Init();
		this.Navigation.Init();
		this.SideNav.Init();
		//Site.FixMenuBackgrounds.Init();
		this.WorlwideLinkModal.Init();
		this.qcTabSetter.Init();
		this.localizationSelector.Init();
		this.alphaSelectSetter.Init();
		this.prodListPanes.Init();

		setInterval(Site.qcTabSetter.SetAppearance, ((jQuery.browser.msie && jQuery.browser.version.charAt(0) == '6') ? 1500 : 250));
		this.SetSiteSearch();
		this.AudioOverlay.Init();
		Site.Print.Init();
		Site.Share.Init(); // added for share on 10/06
		
		// call Page object PreInit if exists
		if ( this.Page && typeof this.Page.Init == 'function' ) {			
			this.Page.Init();
		}
		
	},
	Page: null,
	TextResizer: null,
	// create navigation
	CreateNav: function() {
		$(".drop").singleDropMenu({parentMO: "drop-hover", childMO: "ddchildhover"});
	},
	CreateFlashHero: function(){
			swfobject.embedSWF("/includes/audio-video/swf/merck_homepagehero_pureas3.swf", "hero", "975", "461", "9.0.0", null, {videoPlayerSkinURL:"/includes/audio-video/swf/assets/swfs/homevideoskin.swf",dataXMLURL:"/includes/audio-video/swf/assets/xml/homepagehero.xml"}, {wmode:"opaque"}, {id:"hero"});
	},
	CorrectCSS: function() {
		
		$(".moduleContainer-center-threeAccross div:last").css("margin-right","0px");
	},
	CorrectModuleHeights: function(){
		var modeGroups = $(".moduleContainer-center-threeAccross").each( function(){
			var greatestHeight = 0;
			var divs = $(this).children("div");
			divs.each(function(){
				var height = $(this).height();
				// if height exceeds prior greatest height, the reset greatestHeight
				if (height > greatestHeight) { greatestHeight = height; }
			});
			divs.css("height",greatestHeight);
		});
	},
	InitGlobalModules: function(){
		$(".module-merckAccordian").each( function() { $(this).merckAccordian(); });
		
	},
	Navigation: {
		TopNavSelector: 'ul.topNav li a',
		MainNavSelector: 'ul.drop > li > a',
		SideNavSelector: 'div.sideNav ul li a',
		DefaultPages: [ "index.html" ],
		Init: function(){
			var arr = location.pathname.replace("#nojs","").split("/");
			if( Site.Navigation.__OVERRIDE_PAGE ) { arr = Site.Navigation.__OVERRIDE_PAGE.split("/"); }

			Site.Navigation.__CURRENT_PAGE = arr.pop();
			Site.Navigation.__CURRENT_PATH = arr;
	
			if (Site.Navigation.__CURRENT_PAGE.length > 0) {
				//Site.Navigation.Highlight.TopNav();
				//Site.Navigation.Highlight.MainNav();
				//Site.Navigation.Highlight.SideNav();
			}
		},
		Highlight: {
			ElementsByPath: function( selector ) {
				// duplicate the array with slice
				var arr = Site.Navigation.__CURRENT_PATH.slice();

				// keep a blank array of elements in case there are no links to set active
				var eles = $([]);

				// makes ure there's only 1 slash in the begining, when splitting, its an empty string
				while( arr[1] == "" ) { arr.shift(); };

				// if we don't find any elements on this level, then go 1 level up and keep trying.
				while ( arr.length > 1 && eles.length == 0 ) {
					eles = $(selector + '[href^="' + arr.join("/") + '"]');
					arr.pop();
				}
				
				return eles;
			},
			ElementsByPage: function( selector ) {
				var path = Site.Navigation.__CURRENT_PATH.join("/");
				path += "/";
				selector += "[href^=" + path + Site.Navigation.__CURRENT_PAGE + "]";
				var elements = $(selector)
					.addClass("active");
										
				return elements;
			},
			SideNav: function() {
				var eles = Site.Navigation.Highlight.ElementsByPage( Site.Navigation.SideNavSelector ); 
				
				if( eles.length > 0 ) {
					eles.parents('li:last').find('a:first').mouseover();
					eles.VoidLink();
				}	
			}
		}
	},
	 SetSiteSearch: function(){
	 	$("form.search input").focus(function(){
	 		var dat = $(this).data("label");
	 		if (typeof dat == 'undefined') {
	 			$(this).data("label", $(this).val());
	 		}
	 		$(this).val("");
	 	});
	 	$("form.search input").blur(function(){
	 		if ($(this).val().length == 0) {
	 			$(this).val($(this).data("label"));
	 		}
	 	});
	 }
}

Site.AudioOverlay = {
	Init: function() {
		$(".audioPlayer")
			.VoidLink()
			.click( Site.AudioOverlay.Show );
	},
	Show: function() {
		var html = $('#audioPlayerOverlay').html();
		modal.enter( html );
	}
}

Site.Print = { 
	TemplateUrl: "/includes/print-friendly.html",
	ShowTemplate: function() {
		Site.Print.__CONTENT = $("#columnCenter").html();
		var popWin = window.open(Site.Print.TemplateUrl, '_printMerck','status=no,toolbar=no,width=600,height=700,scrollbars=yes,menubar=no');
	},
	// this fires on the print friendly page itself
	PageInit: function() {
		$('.close a')
			.VoidLink()
			.click(function() {
				window.close();
			});
			
		$('.printPage a')
			.VoidLink()
			.click( function() { 
				window.print();
			});
	},
	Init: function() {
		$('.utility-buttons .printButton a')
			.VoidLink()
			.click( Site.Print.ShowTemplate );
	},
	SetContent: function(popWin) {
		if( popWin.opener && popWin.opener.Site.Print.__CONTENT ) { 
			popWin.$("#columnCenter").html( popWin.opener.Site.Print.__CONTENT );
		}
	}
}

// added for share on 10/06
Site.Share = {
    
    ShowTemplate: function() { 
        var popWin = window.open("/share/share-site.html", "_shareSite",
                                 "status=no,toolbar=no,width=500,height=450,top=100,left=250,scrollbars=no,menubar=no");
        try {popWin.focus();} catch(e) {}
    },

    Init: function() {
       $('.utility-buttons .shareButton a')
           .VoidLink()
           .click( Site.Share.ShowTemplate );
	}

}

// handles the resizing of text on the page
/**
Site.TextResizer = {
	CssClass: "alternativeSize",
	Init: function() {
		Site.TextResizer.__ELEMENT = $(document.body);
		$(".textSizeButton a").VoidLink().click( Site.TextResizer.ChangeFontSize );
		if( $.cookie('alternativeSize') && $.cookie('alternativeSize') != 'false' ) {
			Site.TextResizer.ChangeFontSize();
		}
	},
	ChangeFontSize: function() {
		Site.TextResizer.__ELEMENT
			.toggleClass( Site.TextResizer.CssClass );
		$.cookie('alternativeSize', Site.TextResizer.__ELEMENT.hasClass( Site.TextResizer.CssClass ).toString() );
	}
}
**/

// handles positioning of middle module footer links
Site.SetModuleLinkPosition = {
	LinkSelector : 'div[class^=module-bucket-container-]<div.module-bucket-container-inner',
	Init : function() {
		$(Site.SetModuleLinkPosition.LinkSelector).each(function(){
		// for some reason immediate child selector doesn't work for more than one nesting ... jquery bug?
		// need this logic to compensate to detect immediate child-parent relationship
		var isSingleCol = (/\-oneCol\-/.test(this.parentNode.className));
				$(this).find('div.module-bucket>a.baseArrow').each(function(){
						var leftOffset     = ($($('html')[0]).hasClass('ie6')) ? ((isSingleCol) ? 0 : this.parentNode.offsetLeft) : this.offsetLeft;
						var linkHref       = this.getAttribute('href') || '#';
						var linkLabel      = this.innerHTML;
						this.style.display = 'none'// TODO: jquery.
						$(this.parentNode.parentNode).append('<a href="'+linkHref+'" class="arrow-moved" style="left: '+leftOffset+'px;">'+linkLabel+'</a>').addClass('module-contain-moved-arrows');
				});
		});
	}
};

Site.WorlwideLinkModal = {
	Markup : null,
	LinkSelector : '.globalWrapper .headerTop a.btn-worldwide',
	Show : function() {
		modal.enter(Site.WorlwideLinkModal.Markup);
		$('#modalPositioner a.closeBtn').click(function(){ modal.exit(); return false; });
		Site.qcTabSetter.Init();
		$('body').applyCssQuadBg();
		return false;
	},
	SetMarkup : function(content) {
		Site.WorlwideLinkModal.Markup = content.split(/\<body\>/)[1].split(/\<\/body\>/)[0]; // TODO: refine.
	},
	Init : function() {
		if ($(Site.WorlwideLinkModal.LinkSelector).length) {
			Site.WorlwideLinkModal.baseMarkup = jQuery.get($(Site.WorlwideLinkModal.LinkSelector).attr('href'), null, Site.WorlwideLinkModal.SetMarkup)
		}
		$(Site.WorlwideLinkModal.LinkSelector)
			.VoidLink()
			.click(Site.WorlwideLinkModal.Show);
	}
}

Site.SideNav = {
	Init: function() {
		//$(".sideNav > ul > li > a").mouseover(Site.SideNav.AnimationHandler); // STRUCK 10/6/09 BY AARON ISMAN
		$(".sideNav > ul > li > ul").css('display','none'); // hide all 
		var activeLink = $(".sideNav a.active");
				
		if( activeLink.length > 0 ) {
			/* THIS WAS STRUCK 10/6/09 BY AARON LISMAN
			$(".sideNav > ul").mouseleave( function() { 
			window.activeLink = activeLink;
				var parentLinkEle = activeLink.parents('li:last').find('a:first').mouseover();
				if( parentLinkEle.next().length == 0 ) {
					$("div.sideNav > ul > li > ul").slideUp(500, function() {});
					$(".sideNav > ul > li > a").removeClass('on');
				}
			});
			*/
			var $link = activeLink.parents('li:last').find('a:first');
			if ($link.siblings("ul").length > 0) {
					$link.addClass("on")
						 .next("ul").show();
			}								
		}

	},
	AnimationHandler: function() {
		if( $(this).next("ul").length != 0 ) {
			$("div.sideNav > ul > li > ul").not( $(this).next("ul") ).slideUp(500, function() {});
			$(".sideNav > ul > li > a").removeClass('on');
			$(this).addClass('on');
			$(this).next("ul").slideDown(400);
		}
	}
}

/*
//// javascript trick to fix background images
Site.FixMenuBackgrounds =  {
	MenuSelector : '.globalNav>ul.drop>li>ul',
	Init : function() {
		$(Site.FixMenuBackgrounds.MenuSelector).each(Site.FixMenuBackgrounds.SetBackgroundProps);
	},
	SetBackgroundProps : function(){
		var menuTargetId = 'cacheImgOrig-' + this.parentNode.className.split(' ').join('');
		var menuTarget   = $(this);
			menuTarget.attr('id', menuTargetId);
		var bgImgUrl     = menuTarget.css('background-image');
			bgImgUrl     = bgImgUrl.split('url(')[1].split(')')[0]; //strip url bracing
			bgImgUrl     = (bgImgUrl.charAt(0) == '\'' || bgImgUrl.charAt(0) == '"') ? bgImgUrl.substring(1, bgImgUrl.length-1): bgImgUrl;
		window[menuTargetId] = document.getElementsByTagName('body')[0].appendChild(document.createElement('img'));
		window[menuTargetId].className = 'cacheImg';
		window[menuTargetId].onload   = function() {
			var srcImgUrl = this.src;
			document.getElementById(menuTargetId).style.backgroundColor = 'transparent';
			document.getElementById(menuTargetId).style.backgroundImage = 'url('+srcImgUrl+')';
		};
		window[menuTargetId].src = bgImgUrl;
	}
}
*/

//// experiments in tab styling
Site.qcTabSetter = {
// applies tab widths to max out available space evenly.
	SetAppearance : function() {
		$('.tabbed-navigation>li, .tabbed-navigation-js>li').each(function(){
			var thisTab  = $(this)
			var tabCount = thisTab.siblings().length+1;
			var tabSpace = Math.round((this.parentNode.offsetWidth-20)/tabCount);
			if( tabSpace > 0 ){ 
				thisTab.css({width: tabSpace+'px'});
			}
		});
	},
// classify child elements.
	SetClassification : function() {
		$('.tabbed-content-js').children().addClass('tabbed-content-passive');
		$('.tabbed-navigation-js').children().addClass('tabbed-content-passive');
	},
// sets initial default content for tabs if no default is set manually.
	SetInitial : function() {
		$('.tabbed-navigation-js').each(function(){
			var tabSet = $(this);
			var activeTabIsSet = (tabSet.children('li.tabbed-navigation-active').length > 0);
			if (activeTabIsSet) {
				
			} else {
				var tabIndex = 0
			}
			tabSet.children('li').eq(tabIndex).addClass('tabbed-navigation-active').removeClass('tabbed-navigation-passive');
			tabSet.nextAll('.tabbed-content-js').eq(0).children().eq(tabIndex).addClass('tabbed-content-active').removeClass('tabbed-content-passive');
		});
	},
// sets tab behaviours for JS tabs.
	SetBehaviour : function() {
		$('.tabbed-navigation-js>li a').click(
			function() {
			// preparatory traversing and fact finding
				var clickedTab = this.parentNode.parentNode;                                    //<-- clicked element (raw) used for acquiring tabindex.
				var tabsParent = $(this).parents().eq(2);                                       //<-- container for tabs.
				var contParent = tabsParent.nextAll('.tabbed-content-js').eq(0);                //<-- container for content elements.
				var tabs       = tabsParent.children();                                         //<-- all tab LI elements.
				var conts      = contParent.children();                                         //<-- all contents DOM elements.
				var tabIndex   = 0;                                                             //<-- tab index, to be incremented by next line.
				tabs.each(function(){ if (this == clickedTab) { return false; } tabIndex++; }); //<-- get the real tabIndex of the clicked tab.
			// set classes for tab states
				tabs.removeClass('tabbed-navigation-active').addClass('tabbed-navigation-passive');
				tabs.eq(tabIndex).addClass('tabbed-navigation-active').removeClass('tabbed-navigation-passive');
			// special handling for media player playback - stop playback of any players within all (relevant) tabs when switching. This is only really needed for challeneged microsoft browsers. Other browsers automatically suspend swf activity when player is hidden.
				conts.each(function(){
					var thisTab = $(this);
					var mediaPlayers = thisTab.find('object[id^=mediaplayerrandomidgen-], embed[name^=mediaplayerrandomidgen-]');
					var playerID     = mediaPlayers.eq(0).attr('id') || mediaPlayers.eq(0).attr('name')
					var playerObj    = (typeof(ActiveXObject) != 'undefined' && document.embeds) ? window[playerID] : document[playerID];
					try { playerObj.stopPlayback(); } catch(e) {  } // NOTE: must catch errors because some browsers temporarily delete movie when it is not visible, resulting in errors.
				});
			// set classes for content states
				conts.removeClass('tabbed-content-active').addClass('tabbed-content-passive');
				conts.eq(tabIndex).addClass('tabbed-content-active').removeClass('tabbed-content-passive');
				return false
			}
		);
	},
// initialize tabbing system.
	Init : function() {
		Site.qcTabSetter.SetClassification();
		Site.qcTabSetter.SetInitial();
		Site.qcTabSetter.SetAppearance();
		Site.qcTabSetter.SetBehaviour();
	}
}

Site.alphaSelectSetter = {
	Init: function() {
		$('.alphabetic-selector li a').each(function(){
			var letter = $(this).attr('href').charAt(1);
			var hasSection = ($('a.alpha-anchor[id='+letter+']').length);
			if (!hasSection) { $(this.parentNode).addClass('disabled'); }
		});
	}
}

Site.localizationSelector = {
	Init : function() {
		$('#localization-nav li').click(function(){
			var currentLang = $(this.parentNode).find('li.active a').attr('href').substring(1);
			var thisLang    = $(this).find('a').attr('href').substring(1);
			if (currentLang != thisLang) {
				$('body#countryBridge div.globalWrapper').addClass(thisLang).removeClass(currentLang);
				$('body#countryBridge div.globalWrapper li.active').removeClass('active');
				$(this).addClass('active');
			}
			return false;
		});
	}
}


Site.prodListPanes = {
	Toggle : function() {
		var drug = $(this.parentNode);
			drug.toggleClass('open');
	},
	Init : function() {
		$('ul.products-list li h5').click(Site.prodListPanes.Toggle);
	}
}

