var jsEnabled = {
	init: function() {
		// load the other functions
		highlightSecondaryNav();
		highLightTextSwitcherTag();
		CookieCurrentSection();
		initQuestionaire();
		activateEmail();
		activatePrint();
		assignPopUps();
		getFlashVideo();
		checkForVideo();
		ADHomePopUp();
		segmentedLink();
	}
}


var theSheetSize = "small";
function checkForCookie() {
	theSheetSize = GetCookie("UserTextSize");
	if(theSheetSize) {
		writeStyleSheet(theSheetSize);
	}else {
		SetCookieNam("UserTextSize", "small");
		writeStyleSheet("small");
	}
}
function checkForPrint() {
	if(hasIndexOf(document.URL, "?")) {
		var QS = document.URL.substring(document.URL.indexOf("?") + 1);
		if(hasIndexOf(QS, "print=")) {
			writeStyleSheet("print");
		}
	}
}
function writeStyleSheet(theSheetSize) {
	var styleSheetToWrite = "<style type=\"text/css\">@import url(/inc/" + theSheetSize +".css);</style>";
	document.write(styleSheetToWrite);
	document.close();
}

var resizerOnClick = function() {
	removeClass(this, "active");
	if(!hasClass(this, "bold")) {
		var size = this.className;
		SetCookieNam("UserTextSize", size);
		if(document.all) {
			window.location.reload();
		}else {
			location = document.URL;
		}
		
	}
};

function assignTextSwitcherFunctionality(pageUtilities) {
	var aTags = grabElesByTag("A", pageUtilities);
	for(var i = 0; i < aTags.length; i++) {
		if(hasClass(aTags[i], "bold")) {
			removeClass(aTags[i], "bold")
		}
		if(hasClass(aTags[i], theSheetSize)) {
			addClass(aTags[i], "bold");
		}
		aTags[i].href = "Javascript: void(0);"
		aTags[i].onclick = resizerOnClick;
	}
}

function highLightTextSwitcherTag() {
	var pageUtilities = grabElement("textSizeUtility");
	if(!pageUtilities) {return}
		assignTextSwitcherFunctionality(pageUtilities);
	pageUtilities.id += "_first";
	var pageUtilities2 = grabElement("textSizeUtility");
	if(!pageUtilities2) {return}
		assignTextSwitcherFunctionality(pageUtilities2);
}

function highlightSecondaryNav() {
	var leftNav = grabElement("leftNav");
	if (!leftNav) return;
	var items = grabElesByTag("A", leftNav );
	var globalItems = grabElesByTag("A", grabElement("globalNav") );
	var URLLocation = location.href;
	URLLocation = URLLocation.toString();
	//alert(URLLocation)
	if (URLLocation.indexOf('?') > -1) {
		URLLocation = URLLocation.substring( 0, URLLocation.indexOf( '?' ) );
	}
	var specialCase = grabElement("specialCase");
	//alert( URLLocation );
	if(URLLocation.length > 0) {
		for(var i = 0; i < globalItems.length; i++) {
			var itemshref = globalItems[i].href;
			if(itemshref) {
				if(itemshref == URLLocation) {
					globalNavLink = true;
					addClass(globalItems[i], "active");
					globalItems[i].href = "Javascript: void(0);";
				}
			}
		}
		for(var i = 0; i < items.length; i++) {
			var itemshref = items[i].href;
			if(itemshref) {
				if(hasIndexOf(URLLocation, "Result")) {
					addClass(specialCase, "active");
					specialCase.href = "Javascript: void(0);";
					return;
				}
				if(itemshref == URLLocation) {
					addClass(items[i], "active");
					items[i].href = "Javascript: void(0);";
				}
			}
		}
	}
}

function CookieCurrentSection() {
	var url = document.URL;
	for(var i = 0; i < sectionsToLog.length; i++) {
		if(hasIndexOf(url, sectionsToLog[i])) {
			var start = url.substring(url.indexOf(rootSectionSearch) + rootSectionSearch.length);
			var croppedURL = start.substring(0, start.indexOf("/"));
			SetCookieNam("NavSection", croppedURL);
		}
	}
}

function checkedAction() {
	if(this.checked) { 
		this.checked = false;
	}else {
		this.checked = true;
	}
}
function activeCheckBoxes() {
	var items = grabElesByTag("INPUT");
	for(var i = 0; i < items.length; i++) {
		items[i].onclick = checkedAction;
	}
}
var questionaireItemHover = function() {
	addClass(this, "over");
}
var questionaireItemHoverOff = function() {
	removeClass(this, "over");
}
var questionaireItemClick = function() {
	var thisCheckBox = grabElesByTag("INPUT", this);
	if(thisCheckBox.length > 0) {
		thisCheckBox[0].onclick = checkedAction;
		thisCheckBox[0].onclick();
	}
}

function initQuestionaire() {
	var questionaire = grabElement("questionaire");
	if(questionaire) {
		var items = grabElesByTag("TR", questionaire);
		for(var i = 0; i < items.length; i++) {
			if(i % 2 != 0) {
				addClass(items[i], "altRow");
			}
			items[i].onclick = questionaireItemClick;
		}
		//this is only if where are making whole table rows clickable
		//do not call this function unless that is the case
		//checkboxes will not be able to be actived if so
		activeCheckBoxes();
	}
}

function activateEmail() {
	var emailButton = grabElement("emailPageLink");
	if(!emailButton) {return}
	emailButton.id += "_first";
	var emailButton2 = grabElement("emailPageLink");
	emailButton.href += "?PageTitle=" + escape(document.title);
	if(!emailButton2) {return}
	emailButton2.href += "?PageTitle=" + escape(document.title);
}
var printOnClick = function() {
	var URL = location.href + "?print=true";
	window.open(URL, null, "height=600, width=800, location=1, menubar=1, resizable=1, scrollbars=1, status=1, titlebar=1, toolbar=1");
	return false;
}
function activatePrint() {
	var printButton = grabElement("printPageLink");
	if(!printButton) {return}
	printButton.id += "_first";
	var printButton2 = grabElement("printPageLink");
	printButton.href="";
	printButton.onclick = printOnClick;
	if(!printButton2) {return}
	printButton2.href="";
	printButton2.onclick = printOnClick;
}

function assignPopUps() {
	var theFooter = grabElement("footer");
	if(!theFooter) {return}
	var popUpEles = grabEleByNameAndClass("A", "isPopUp", theFooter);
	var frxPop = '';
	for(var i = 0; i < popUpEles.length; i++) {
		//popUpEles[i].newURL = popUpEles[i].href;
		//alert(popUpEles[i].newURL);
		//popUpEles[i].href = "Javascript: void(0);";
		popUpEles[i].onclick = function() {
			if (!frxPop.closed && frxPop.location) {
				frxPop.location.href = this.href;
			}
			else {
				frxPop = window.open(this.href, null, "height=400, width=400, location=0, menubar=0, resizable=1, scrollbars=1, status=1, titlebar=1, toolbar=0");
			}
			if (window.focus) {frxPop.focus();}
			return false;
		};
	}
}

function ADHomePopUp() {
	var ADHome = grabElement("ADHome");
	var ADHomePop = '';
	if(!ADHome) {return}
	//ADHome.newURL = ADHome.href;
	//ADHome.href = "Javascript: void(0);";
	ADHome.onclick = function() {
		if (!ADHomePop.closed && ADHomePop.location) {
			ADHomePop.location.href = this.href;
		}
		else {
			ADHomePop = window.open(this.href, null, "height=480, width=690, location=0, menubar=0, resizable=01, scrollbars=0, status=0, titlebar=1, toolbar=0");
		}
		if (window.focus) {ADHomePop.focus();}
		return false;
	};
}

//check for these in the URL, if they are there, we know that we need to
//store this fact in a cookie so ASP can read it and include the right nav
//section for the global pages
var sectionsToLog = ["/10/", "/20/", "/30/"];
var rootSectionSearch = "/sections/"; 
function pngFix() { 
	alert("DOING IT");
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	
	if ((version >= 5.5) && (document.body.filters)) 
	{
	   for(var i=0; i<document.images.length; i++)
	   {
	      var img = document.images[i]
	      var imgName = img.src.toUpperCase()
	      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	      {
	         var imgID = (img.id) ? "id='" + img.id + "' " : ""
	         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
	         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
	         var imgStyle = "display:inline-block;" + img.style.cssText 
	         if (img.align == "left") imgStyle = "float:left;" + imgStyle
	         if (img.align == "right") imgStyle = "float:right;" + imgStyle
	         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
	         var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
	         img.outerHTML = strNewHTML
	         i = i-1
	      }
	   }
	}
}


var whichBucket = null;
function checkBucket() {
	if(!whichBucket) {
		whichBucket = GetCookie("NavSection");		
	}
	return whichBucket;
}


function getFlashVideo() {
	var videoLinks = grabEleByNameAndClass('A', 'video', document.body);
	for(var i = 0; i < videoLinks.length; i++) {
		videoLinks[i].onclick = function() {
			var userID = this.rel.split('_')[0];
			var videoID = this.rel.substring(0,this.rel.lastIndexOf('_'));
			var bucket = this.rel.split('_')[2];
			var srcFile = "/Flash/swf/namenda_video_large.swf?userID=" + userID + "&thumbnailPath=/img/testimonials/&videoFileID=" + videoID + "&xmlPath=/Flash/XML/&bucket=" + bucket;
			var pContainer = document.getElementById(userID);
			var flashContainer = grabEleByNameAndClass('div', 'flashStoryContainer', pContainer);
			
			resetInactiveVideos(pContainer);

			pContainer.className += ' active';
			
			//clear flashContainer children
			while (flashContainer[0].hasChildNodes()) {
				flashContainer[0].removeChild(flashContainer[0].firstChild);
			}

			var flashContent = createTestimonialObject(srcFile, '523', '310', '8');
			flashContainer[0].innerHTML = flashContent;

			return false;
		};
	}
}

function checkForVideo() {
	if(hasIndexOf(document.URL, "?")) {
		var queryString = document.URL.substring(document.URL.indexOf("?") + 1);
		if(hasIndexOf(queryString, "id=")) {
			queryString = queryString.substring(queryString.indexOf("=") + 1,queryString.length);
			var userID = queryString.split('_')[0];
			var videoID = queryString.substring(0,queryString.lastIndexOf('_'));
			var bucket = queryString.split('_')[2];
			var srcFile = "/Flash/swf/namenda_video_large.swf?userID=" + userID + "&videoFileID=" + videoID + "&xmlPath=/Flash/XML/&bucket=" + bucket;
			var pContainer = document.getElementById(userID);
			var flashContainer = grabEleByNameAndClass('div', 'flashStoryContainer', pContainer);

			pContainer.className += ' active';

			var flashContent = createTestimonialObject(srcFile, '523', '310', '8');
			flashContainer[0].innerHTML = flashContent;

			scrollToElement(userID);
		}
	}
}

function languageToggle( ele ) {
	var es = "/espanol"
	var pathName = location.pathname;
	if( hasIndexOf( document.URL, es ) ) {
		var URLString = pathName.replace( es, '' );
		ele.href = URLString;
	} else {
		ele.href = es + pathName;
	}
}


function resetInactiveVideos(obj) {
	var rootObj = obj.parentNode;
	while (rootObj.className.indexOf('content') == -1 && rootObj != 'document.body') {
		rootObj = rootObj.parentNode;
	}

	var arrULs = rootObj.getElementsByTagName('ul');
	for (var i = 0; i < arrULs.length; i++) {
		var arrContainers = arrULs[i].getElementsByTagName('li');
		for (var j = 0; j < arrContainers.length; j++) {
			if (arrContainers[j] != obj) {
				if(arrContainers[j].className.indexOf('' + 'active' + '') > -1) {
					var flashContainer = grabEleByNameAndClass('div', 'flashStoryContainer', arrContainers[j]);
					//clear flashContainer children
					while (flashContainer[0].hasChildNodes()) {
						flashContainer[0].removeChild(flashContainer[0].firstChild);
					}

					arrContainers[j].className = arrContainers[j].className.replace('active','');
				}
			}
		}
	}
}

// close all video testimonials
function destroyAllMonsters() {
	var arrStories = gETAC('ul', 'stories', document.body);
	for (var i = 0; i < arrStories.length; i++) {
		var arrContainers = arrStories[i].getElementsByTagName('li');
		for (var j = 0; j < arrContainers.length; j++) {
			if(arrContainers[j].className.indexOf('' + 'active' + '') > -1) {
				var flashContainer = grabEleByNameAndClass('div', 'flashStoryContainer', arrContainers[j]);
				//clear flashContainer children
				while (flashContainer[0].hasChildNodes()) {
					flashContainer[0].removeChild(flashContainer[0].firstChild);
				}

				arrContainers[j].className = arrContainers[j].className.replace('active','');
			}
		}
	}
}

function createTestimonialObject(srcFile, width, height, version) {
	var string = new Array();
	string.push('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + version + ',0,0,0" width="' + width + '" height="' + height + '" id="video_viewer">');
	string.push('<param name="movie" value="' + srcFile + '" />');
	string.push('<embed src="' + srcFile + '" quality="high" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="video_viewer" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	string.push('</object>');

	var flashContent = string.join('');

	return flashContent;
}

function linkToEmailPage(videoID) {
	var bucket = checkBucket();
	var docTitle = escape(document.title); //escape() potentially not needed
	var emailPage = "/sections/email/Default.aspx?PageTitle=" + docTitle + "&videoFileID=" + videoID + "&bucket=" + bucket;
	window.location = emailPage;
}

function segmentedLink() {
	if( document.getElementById( 'namendaLink' ) ) {
		var ele = document.getElementById( 'namendaLink' );
		var eLink = ele.href;
		var bucket = checkBucket();
		if ( bucket == '10' ) {
			ele.href = eLink.replace( /20/, bucket );
		}
		if ( bucket == '30' ) {
			var str = '20/proven-benefits.shtml';
			ele.href = eLink.replace( str, '30/namenda-difference.shtml' );
		}
	}
}


function scrollToElement(oID) {
	var destination = document.getElementById(oID);
	var destY = destination.offsetTop;
	while (destination.offsetParent && (destination.offsetParent != document.body)) {
		destination = destination.offsetParent;
		destY += destination.offsetTop;
	}
	scrollWindow(destY);
}

function scrollWindow(dest) {
	window.scrollTo(0,dest);
}
function Imageload(n){
        pic=new Image(1,1);
        switch(n){
            case 1:
 		        pic.src="http://switch.atdmt.com/action/nycnma_CTNMAPrintSurveyResultsAnotherMed_9"; break;
 	    case 2:
 		        pic.src="http://switch.atdmt.com/action/nycnma_CTNMAPrintSurveyResultsCurrentlyOnNamen_9"; break;
 	    case 3:
 		        pic.src="http://switch.atdmt.com/action/nycnma_CTNMAPrintSurveyResultsTreatment_9"; break;
 	    case 4:   
 		        pic.src="http://switch.atdmt.com/action/nycnma_CTNMATrackingDiaryPDF_9"; break;
	    case 5:   
			pic.src="http://switch.atdmt.com/action/nycnma_CTNMATrackingDiaryPDFCurrentlyOnNamenda_1"; break;
	    case 6:
	        pic.src = "http://switch.atdmt.com/action/nycnma_CTNMATrackingDiaryPDFTreatment_1"; break;
	        case 7:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_NotOnAlzMed_PrintResults_Mild"; break;
	        case 8:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_NotOnAlzMed_PrintResults_ModtoSevere"; break;
	        case 9:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_NotOnAlzMed_PrintResults_Severe"; break;
	        case 10:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_OnAnotherAlzMed_PrintResults_Mild"; break;
	        case 11:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_OnAnotherAlzMed_PrintResults_ModtoSevere"; break;
	        case 12:
	            pic.src = "http://view.atdmt.com/action/CT_NMA_OnAnotherAlzMed_PrintResults_Severe"; break;

 		}
}

var windowObject = {
	onload: [],
	loaded: function()
	{
		if (arguments.callee.done) return;
		arguments.callee.done = true;
		for (i = 0;i < windowObject.onload.length;i++) windowObject.onload[i]();
	},
	addLoadFunction: function(fireThis)
	{
		for(var index = 0; index < arguments.length; index++) {
			this.onload.push(arguments[index]);
		}
		if (document.addEventListener) 
			document.addEventListener("DOMContentLoaded", windowObject.loaded, null);
		if (/KHTML|WebKit/i.test(navigator.userAgent))
		{ 
			var _timer = setInterval(function()
			{
				if (/loaded|complete/.test(document.readyState))
				{
					clearInterval(_timer);
					delete _timer;
					windowObject.loaded();
				}
			}, 10);
		}
		/*@cc_on @*/
		/*@if (@_win32)
		var proto = "src='javascript:void(0)'";
		if (location.protocol == "https:") proto = "src=//0";
		document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
		document.close();
		var script = document.getElementById("__ie_onload");
		script.onreadystatechange = function() {
		    if (this.readyState == "complete") {
		        setTimeout( function() { windowObject.loaded(); }, 100 );  
		    }
		};
		/*@end @*/
	
	   window.onload = windowObject.loaded;
	}
};

windowObject.addLoadFunction(jsEnabled.init);
