/****************************************************************************************

DOC			Global Scripts
VERSION 	1.1
AUTHOR		Doug Scamahorn
EMAIL		dscamahorn@fusionalliance.com

DATE       	NAME           	DESCRIPTON
03/25/2011 	Doug Scamahorn 	Initial creation.
12/08/2011  Stacy Kagiwada  Changed "lillyhub" to "elancocentral"

****************************************************************************************/

/* =DOM MANIPULATION
---------------------------------------------------------------------------------------*/

	//Setup a hover event for image rollovers
	function hoverImages() {
		$("img.hoverImage").each(function(i){
			var vImageSourcePath = $(this).attr("src").slice(0,-4);
			var vImageSourceType = $(this).attr("src").slice(-4);
			//Preload images
			$.preLoadImages(vImageSourcePath + "Hover" + vImageSourceType);
			$(this).hover(
				function () {
					$(this).attr({src: vImageSourcePath + "Hover" + vImageSourceType});
				},
				function () {
					$(this).attr({src: vImageSourcePath+vImageSourceType});
				}
			);
		});
	}
	
/* =SLIDERS
---------------------------------------------------------------------------------------*/

	//
	function publishSliders(){
		
		//Determine if the interactive components are enabled
		if ($.cookie("interactiveComponents") != "disabled") {
			
			//Homepage Slider
			$("#hpSlider").slides({
				container: 'slidesContainer',
				generateNextPrev: true,
				effect: 'fade',
				play: 5000,
				pause: 2500,
				hoverPause: true
			});
			
		}
		
	}
	
/* =DIALOG WINDOWS
---------------------------------------------------------------------------------------*/

	function publishDialogs(targetedSelector){
		
		//Determine if the interactive components are enabled
		if ($.cookie("interactiveComponents") != "disabled") {
				
			//
			if (targetedSelector == undefined) {
				targetedSelector = "";
			}
			
			//Modify Markup
				
				//Locate dialog containers
				$(targetedSelector+"div.dialog").each(function(){
					
					$(this).hide().addClass("dialogEnabled").wrapInner("<div class='dialogOuter'><div class='dialogInner'><div class='dialogContent'></div></div></div>").prepend('<div class="dialogTitlebar"><span class="dialogTitle">'+$(this).attr("title")+'</span><a href="#" class="dialogTitlebarClose"><span>close</span></a></div>').attr("title","").insertAfter(".pageContainer");
								
				});
		
			//Events
			
				//Open dialog link
				$(targetedSelector+"a[class*='openDialog']").each(function(){
					$(this).click(function(){
						var dialogWidth;
						var dialogHeight;
						var linkClass = $(this).attr("class").match(/openDialog_(\d*)_(\d*)/);
						if (linkClass != null) {
							dialogWidth = parseInt(linkClass[1]);
							dialogHeight = parseInt(linkClass[2]);
						} else {
							dialogWidth = 640;
							dialogHeight = 540;
						}
						openDialog($(this).attr("href"),dialogWidth,dialogHeight);
						return false;
					});
				});
		}
	}
	
	//Open Dialog
	function showAlert() {
		alert('test');
	}
	
	function openDialog(dialogID,dialogWidth,dialogHeight){
		
		//Modify Markup
		
			//Make the dialog active
			$(dialogID).addClass("dialogActive");
			
			sizeDialog(dialogID,dialogWidth,dialogHeight);
			
			//Insert markup for the overlay and disable scrolling
			$("body").append('<div class="dialogOverlay"></div>')/*.css({"overflow":"hidden"})*/;
			
			//Overlay dimensions and fade in
			$(".dialogOverlay")./*height($(document).height()).*/animate({"opacity":"0.75"}, 400, "linear", function(){
				$(dialogID).fadeIn(200, function(){
					publishHiddenFlash("#"+$(this).attr("id"));
				});
			}).bgiframe();
			
		//Events
		
			//Track Event
			trackEvent("Dialogs", "Open Dialog", $(dialogID+" .dialogTitle").text());
			
			//Attach close dialog events
			//Bind close to the overlay
			$(".dialogOverlay").bind("click",function(){
				//Remove the event so it is not bound again the next time the dialog is opened
				$(this).unbind("click");								   
				closeDialog();
				return false;				   
			});
			//Bind close to dialog close button
			$(dialogID+" .dialogTitlebarClose").bind("click",function(){
				//Remove the event so it is not bound again the next time the dialog is opened
				$(this).unbind("click");								   
				closeDialog();
				return false;
			});
		
	}
	
	//
	function sizeDialog(dialogID,dialogWidth,dialogHeight){
		
			//Size the dialog
			$(dialogID).find(".dialogContent").css({
				"width":dialogWidth,
				"height":dialogHeight
			});
			
			$(dialogID).find(".dialogTitle").css({
				"width":dialogWidth-40
			});
			
			//Position the dialog
			if ( !(jQuery.browser.msie && jQuery.browser.version < 7)){
				//If the browser is not IE and not less than version 7					
					$(dialogID).css({
						"margin-left":-((dialogWidth)/2),
						"margin-top": -((dialogHeight)/2)
					});
			} else {
					$(dialogID).css({
						"margin-left":-((dialogWidth)/2),
						"margin-top": -((dialogHeight)/2)
					});
			}
			
	}
	
	//
	function closeDialog(){
				
		//Stop Flash playback - pass in ID of Flash object
		flashInterface($(".dialogActive").find(".flaPlayer object").attr("id"), "stopFlashObjectPlayback");
				
		//Fade out the dialog
		$(".dialogActive").fadeOut(100,function(){
			$(this).removeClass("dialogActive");
		});
		//Fade out and remove the overlay
		$(".dialogOverlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(this).remove();
		});
		
		//Turn back on scrollbars
		//$("body").css("overflow","auto");
		
	}

/* =FLASH PUBLISHING
---------------------------------------------------------------------------------------*/
	
	//Publish Flash objects
	function publishFlash() {
		
		//Modify Markup
		
			//Remove JavaScript warning from Alt Content Notice
			$("p.altContentNotice span").remove();
					
			//If you don't have Flash we display the alt content and message
			if (!swfobject.hasFlashPlayerVersion("9")) {
				//No Flash
				$("div.altFlashContent").addClass("show");
				$("p.altContentNotice").addClass("show");
			} else {
				//Flash so do something to the DOM
			}
		
		//Embed Flash objects
		
			//Test to see if the visitor has disabled interactive components
			if ($.cookie("interactiveComponents") != "disabled") {
						
				//Embed BOND Flash
				if ( $("div.flaPlayer:not(':hidden') div#flaBOND").length > 0 ) {
					//swfObject Parameters
					var flashvars = {};
						flashvars.v_swfWidth; //The loaded SWF width - required when using the loader.swf
						flashvars.v_swfHeight; //The loaded SWF height - required when using the loader.swf
						flashvars.v_swfFilename = "flaBOND.swf"; //This value may be used by a loader.swf in combination with the base parameter to load in the child swf
						flashvars.v_swfDataPath = "flaDataBOND.xml"; //The name of the XML file referenced by the loaded SWF file
						flashvars.v_swfObjectID = "flaBOND"; //The Flash object ID
						flashvars.v_swfPathPage = location.pathname; //The container path and page
					var params = {};
						params.wmode = "transparent";
						params.allowfullscreen = "true";
						params.base = "../_layouts/richmedia/flash/"; //The path to the SWF, XML, and other assets
					var attributes = {};
					swfobject.embedSWF("../_layouts/richmedia/flash/flaBOND.swf", "flaBOND", "604px", "456px", "9.0.0", false, flashvars, params, attributes);				
				}
													
				//Embed Videos not in hidden containers
				$("div.flaPlayer:not(':hidden') div[id^='flaVideo']").each(function () {
					embedFlashVideo($(this));	
				});
				
		} else {//The visitor has disabled interactive components
			
			//Show the alternate content
			$("div.altFlashContent").addClass("show");
			//Remove the alt content notice b/c this visitor has chosen to disable interactive components
			$("p.altContentNotice").remove();
		
		}
		
	}
	
	//Publish hidden Flash objects when they are shown
	function publishHiddenFlash(hiddenContainer){
		//If the Flash object has not already been embedded in the element
		if ($(hiddenContainer+" div.flaPlayer object").length <= 0) {
			//Publish Flash elements within the now visible container
				
				//Embed Video
				$(hiddenContainer+" div.flaPlayer div[id^='flaVideo']").each(function () {//Find each video
					embedFlashVideo($(this));		
				});
				
				//Embed Flash Sample
				/*
				if ( $(hiddenContainer+" div.flaPlayer div#flaSample").length > 0 ) {
					//swfObject Parameters
					var flashvars = {};
						flashvars.v_swfWidth; - required when using the loader.swf
						flashvars.v_swfHeight; - required when using the loader.swf
						flashvars.v_swfFilename = "flaSample.swf"; //This value is used by the loader.swf in combination with the base parameter to load in the swf
						flashvars.v_swfDataPath = "flaDataSample.xml"; //The name of the XML file referenced by the loaded SWF file
						flashvars.v_swfObjectID = "flaSample"; //The Flash object ID
						flashvars.v_swfPathPage = location.pathname; //The container path and page
					var params = {};
						params.wmode = "transparent";
						params.allowfullscreen = "true";
						params.base = "assets/richmedia/flaSample/"; //The path to the SWF, XML, and other assets
					var attributes = {};
					swfobject.embedSWF("assets/richmedia/flaSample/flaSample.swf", "flaSample", "480", "360", "9.0.0", false, flashvars, params, attributes);
				}
				*/
		}
	};
	
	//Video player embedding
	function embedFlashVideo(videoObject){
		//Capture the video's ID
		var videoID = $(videoObject).attr("id");
		//Capture/set the dimensions
		var playerWidth;
		var playerHeight;
		var playerFormat = $(videoObject).attr("class");
		if (playerFormat == "widescreen") {
			var playerWidth = "640";
			var playerHeight = "390";
		} else {
			var playerWidth = "480";
			var playerHeight = "390";
		}
		//swfObject Parameters
		var flashvars = {};
			flashvars.v_swfWidth = playerWidth; //The loaded SWF width
			flashvars.v_swfHeight = playerHeight; //The loaded SWF height
			flashvars.v_swfFilename = videoID+".swf"; //This value may be used by a loader.swf in combination with the base parameter to load in the child swf
			flashvars.v_swfDataPath = videoID+".xml"; //The name of the XML file referenced by the loaded SWF file
			flashvars.v_swfObjectID = videoID; //The Flash object ID
			flashvars.v_swfPathPage = location.pathname; //The container path and page
		var params = {};
			params.wmode = "transparent";
			params.allowfullscreen = "true";
			params.base = "../_layouts/richmedia/video/"; //The path to the SWF, XML, and other assets
		var attributes = {};
			attributes.styleclass = playerFormat;//Add the styles originally on the replaced DIV to the object/embed element. This should contain the playerFormat (fullscreen/widescreen).
		swfobject.embedSWF("../_layouts/richmedia/video/flaVideoPlayer.swf", videoID, playerWidth, playerHeight, "9.0.0", false, flashvars, params, attributes, embedFlashVideoCallback);
	}
	
	//Execute the following function on completing swfobject activity
	function embedFlashVideoCallback(e){
		if (e.success == true){//If successful
			var videoClass = $("#"+e.id).attr("class");//Get the id/classes (fullscreen/widescreen) of the embedded video object
			$("#"+e.id).parent().addClass(videoClass);//Assign the video class (fullscreen/widescreen) to the parent container. The CSS can then control things such as borders and backgrounds around the player.
		}
	}

	//Work with Flash ExternalInterface
	function flashInterface(flashObjectID, asFunction, asFunctionArguments){
		try {
			if (asFunctionArguments == undefined){
				eval("document['"+flashObjectID+"']."+asFunction+"()");
			} else {
				eval("document['"+flashObjectID+"']."+asFunction+"("+asFunctionArguments+")");//Pass asFunctionArguments as a string in the following format "'argOne','argTwo'"
			}
		} catch(err) {
			//Do nothing
		}
	}
	

	
/* =ANALYTICS
---------------------------------------------------------------------------------------*/
	
	//Track JavaScript Events 
	function trackEvent(eventType, eventAction, elementTitle) {
		eventPage = $(document).url();
		if (eventPage.attr("file") == null) {
			eventPage = "/";
		}
		//Pass event parameter value pairs to the dcsMultiTrack function
		passTrackingAttributesToAnalyticsEngine("dcsMultiTrack('DCS.dcsuri','/"+eventType+"','WT.ti','"+elementTitle+"','DCSext.video_name','Video:"+elementTitle+"','DCSext.page_name','"+eventPage+"','DCSext.action','"+eventAction+"')");
	}
	
	/*<analyticsFormat>dcsMultiTrack('DCS.dcsuri','/video','WT.ti','Video:+videoTitle_v+','DCSext.video_name','Video:+videoTitle_v+','DCSext.page_name','+swfPathPage_v+','DCSext.action','+eventAction_v+')</analyticsFormat>*/
	
	//Analytics Tracking
	function passTrackingAttributesToAnalyticsEngine(trackingParameters){
		//debugScript(trackingParameters);
		try {
			eval(trackingParameters);
		} catch(err){
			//alert(parameterValuePairs);
		}
	}

/* =SEP ANXIETY QUESTIONNAIRE
---------------------------------------------------------------------------------------*/

	function validateAnswers()
	{
		var isValid = true;
		for (i=1; i<11; i++) {
			if (!($("#Q" + i.toString() + "_1:checked").val() || $("#Q" + i.toString() + "_0:checked").val())) {
				if (i==7 && $("#Q6_0:checked").val()) continue; // if they answered no to question #6, skip validating question #7
				$("#Q" + i.toString() + "_Row").addClass("required");
				isValid = false;
			} else {
				$("#Q" + i.toString() + "_Row").removeClass("required");
			}
		}
		if (isValid) {
			$("#formErrorSummary").hide();
			$("div.quiz").addClass("hide");
			$("div.results").addClass("show");
		}
		else 
		{
			$("#formErrorSummary").show();
			passTrackingAttributesToAnalyticsEngine("dcsMultiTrack('DCS.dcsuri','/analytics/sa-quiz/error')");
		}
		return isValid;
	}
		
	function getAnswers()
	{
		var r = "";
		for (i=1; i<11; i++) {
			r = r + ($("#Q" + i.toString() + "_1:checked").val() ? "1" : "0");
		}
		return r;
	}
	
	function showAnswers()
	{
		if (! validateAnswers()) return;
		var answers = getAnswers();
		
		if (answers.indexOf("1") != -1) // did user answer yes to anything
		{
			$("#allNo").hide();
		}
		else
		{
			$("#anyYes").hide();
			$("#anyYes2").hide();
		}
		
		if (answers.substring(0, 7).indexOf("1") == -1) // did user answer no to 1-8
		{
			$("#ask1").hide();
			$("#ask2").hide();
			$("#ask3").hide();
		}
		
		if (answers.substring(3, 4) == "0") // did the user answer no to #4
			$("#ask4").hide();
			
		if (answers.substring(5, 7) == "00") // did the user answer no to #6 and #7
			$("#ask5").hide();
		
		if (answers.substring(9) == "0") // did the user answer no to #9
			$("#ask6").hide();
			
		for (i=1; i<11; i++) {
			$("#A" + i.toString()).text($("#Q" + i.toString() + "_1:checked").val() ? "Yes" : "No");
		}
		$("#quiz").hide();
		$("#results").fadeIn();
		
		passTrackingAttributesToAnalyticsEngine("dcsMultiTrack('DCS.dcsuri','/analytics/sa-quiz/success','DCSext.answer','SA"+answers+"')");
	}
	
	function publishQuestionnaire() {
		//Attach events to quiz form
		$("body.questionnaire a.cancelForm").click(function(){
			//debugScript("close");
			window.close();
			return false;
		});
		$("body.questionnaire input[name='Submit']").click(function(){
			//debugScript("show answers");
			showAnswers();
			return false;
		});
		$("body.questionnaire input[name='Print']").click(function(){
			//debugScript("print");
			window.print();
			passTrackingAttributesToAnalyticsEngine("dcsMultiTrack('DCS.dcsuri','/about-separation-anxiety/separation-anxiety-questionnaire.aspx/submit/print')");
			return false;
		});
	}

/* =DEBUGGER
---------------------------------------------------------------------------------------*/

	//Debug Flash/JS
	function debugScript(alertMessage){
		try {
			console.log(alertMessage);
		} catch(err) {
			alert(alertMessage);
		}
	}
	
/* Pop-up window ---------------------------------------------------------------------------- */

function popOpen(){
	$('a.popUp').click(function(){
 		window.open(this.href,"popOpen","toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, width=800,height=620");
	return false;
	});
};

/* Open a new fullpage window ----------------------------------------------------------------- */

function newWindow(){
	//Open in a new full size window
	$("a.newWindow").attr({
		target: '_blank'
	});
}	

/** Track pop-up window ---------------------------------------------------------------------------- */

function trackPopOpen(){
	
	/* Track links which go to other elanco domains */
	$('a.PS').click(function(){
 		dcsMultiTrack('DCS.dcsuri','www.elancocentral.com/Elanco_Global_privacy.htm','WT.ti','Privacy Statement','WT.dl','24');
	});
	$('a.ToU').click(function(){
 		dcsMultiTrack('DCS.dcsuri','www.elancocentral.com/Elanco_Terms_of_Use.htm','WT.ti','Terms of Use','WT.dl','24');
	});
	
	//Veterinarian access button. Links to elancovet.com.
	$('a.VA').click(function(){
		eventPage = $(document).url();
 		dcsMultiTrack('DCS.dcsuri','/veterinarian-access','DCSext.page_name',eventPage);
	});
	
};

/* Rollover title ---------------------------------------------------------------------------- */
 
function rolloverTitle(){
	//find the link with .offsite class and add .hoverbox which will activate the file "jquery.hoverbox.min.js"
	$('a.offsite').not($(".footer a.offsite")).hoverbox();
	$('.footer a.offsite').hoverbox({left:-210,top:60});
	//Add the title attribute and open in a new window
	$("a.offsite").attr({
		title: "Please note: If you click this link, you will be leaving Elanco's website Reconcile.com.",
		target: '_blank'
	});
	$("a.offsite[rel=external]").attr({
		title: "Please note: If you click this link, you will be leaving Elanco's website Reconcile.com. Different privacy policies and/or terms and conditions may apply.",
		target: '_blank'
	});
}			

/**/

/* =SHARE PAGE
---------------------------------------------------------------------------------------*/

	//Share page menu
	function sharePage(targetedSelector){
		
		if (targetedSelector == undefined) {
			targetedSelector = "";
		}
		
		//Gather page information
			//URL
				if ($('meta[property=og:url]').length !=0) {
					var sharedURL = encodeURIComponent($('meta[property=og:url]').attr("content"));
				} else {
					var sharedURL = encodeURIComponent((location.href));
				}
			//Title
				if ($('meta[property=og:title]').length !=0) {
					var sharedTitle = encodeURIComponent($('meta[property=og:title]').attr("content"));
				} else {
					var sharedTitle = encodeURIComponent($('meta[name=title]').attr("content"));
				}
			//Description
				if ($('meta[property=og:description]').length !=0) {
					var sharedDescription = encodeURIComponent($('meta[property=og:description]').attr("content"));
				} else {
					var sharedDescription = encodeURIComponent($('meta[name=description]').attr("content"));
				}
			//Image
				if ($('meta[property=og:image]').length !=0) {
					var sharedImage = encodeURIComponent($('meta[property=og:image]').attr("content"));
				} else {
					var sharedImage = encodeURIComponent($("link[rel='image_src']").attr("href"));
				}
			//Site Name
				if ($('meta[property=og:site_name]').length !=0) {
					var sharedSource = encodeURIComponent($('meta[property=og:site_name]').attr("content"));
				} else {
					var sharedSource = encodeURIComponent("");
				}
		
		$(targetedSelector+".shareContent a").each(function(){
			
			//Modify Markup
			
				//Gather the initial link url
				var linkURL = $(this).attr("href");
				
				// Remove default query string
				var parts = linkURL.split("?");
				linkURL = parts[0];
				
				//Add to the link the attributes of additional elements for submission to sharing service
								
				//Twitter
				if (linkURL.indexOf("twitter") != -1) {
					linkURL = parts[0]+"?text="+sharedTitle+"&url="+sharedURL;
					$(this).attr("href",linkURL);
				//Facebook
				} else if (linkURL.indexOf("facebook") != -1) {
					linkURL = parts[0]+"?u="+sharedURL+"&t="+sharedTitle;
					$(this).attr("href",linkURL);
				//If none of the above put the link back to its original state
				} else {
					$(this).attr("href",linkURL);
				}
				
			//Events

				$(this).click(function(){
					window.open($(this).attr("href"),"SharePage","toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=yes, width=700, height=440");
					/* This return false is only needed on the dev server when webtrends is not available. It prevents 2 windows from popping. */
					//return false; 
					
				var linkURL = $(this).attr("href");
 				//Determine which service and analytics
 				if (linkURL.indexOf("twitter") != -1) {
 					dcsMultiTrack('DCS.dcssip','twitter.com/','DCS.dcsuri','/share','DCS.dcsref',linkURL,'WT.ti','Offsite:twitter.com','WT.dl','24');		
 				} else if (linkURL.indexOf("facebook") != -1) {
					dcsMultiTrack('DCS.dcssip','www.facebook.com','DCS.dcsuri','/sharer.php','DCS.dcsref',linkURL,'WT.ti','Offsite:www.facebook.com','WT.dl','24');
 				}  
					return false;
				});			
        });
	
	}


/* =CALL EVENTS
---------------------------------------------------------------------------------------*/
	//$(document).ready(function(){	
		
		//Functions to Execute

			//DOM Manipulation
				hoverImages();
			//INTERACTIVE ELEMENTS
				publishDialogs();
				newWindow();
				publishSliders();
				publishQuestionnaire();
				rolloverTitle();
			//FLASH
				publishFlash();
			//Popup window
				popOpen();
			//Track Terms of Use and Privacy Statement links
				trackPopOpen()
			//Share Links
				sharePage();
			
	//});
