﻿
//////////////////////////////////////////////////////////
// Constants
//////////////////////////////////////////////////////////
// Font resize constants
var m_intCurrentFontSize = 0;
var FS_FONT_SIZE_BUTTON_1_ID = 'ancFontSize1';
var FS_FONT_SIZE_BUTTON_2_ID = 'ancFontSize2';
var FS_FONT_SIZE_BUTTON_3_ID = 'ancFontSize3';
var FS_HANDLER_URL = '/handlers/ResizeText.ashx?m=settextsize&size=';

//////////////////////////////////////////////////////////
// Site
// The "Site" object should contain all of the code that adds behavior 
// to the various client side controls.
//////////////////////////////////////////////////////////

var Site = {
   
	start: function() { 	
		
		// Check for existence of font resize buttons. 
	   if ($(FS_FONT_SIZE_BUTTON_1_ID) 
			&& $(FS_FONT_SIZE_BUTTON_2_ID) 
			&& $(FS_FONT_SIZE_BUTTON_3_ID)) {
			
			//Wire up buttons.
			TextResizer.createFontSizer();
			
			//Highlight correct text resize button.
			TextResizer.highlightTextResizeButtonOnLoad();
		}
	} // End start()
};

//////////////////////////////////////////////////////////
// TextResizer
// Handles text resize operations
//////////////////////////////////////////////////////////
var TextResizer = {

	//At first page load, we need to retrieve the body classname and
	//highlight the correct text resize button to reflect any cookies
	//that are stored.
	highlightTextResizeButtonOnLoad: function() {
		var elemBody = document.getElementsByTagName('body')[0];
		if (!elemBody.className == '' && elemBody.className.length > 0) {
			var cn = elemBody.className;
			var num = Number(cn.substr(cn.length - 1, 1))
			TextResizer.selectTextButton(num);
		}
	}
	,

	changeFontSize: function(intNewSize) {
	
		var size = Storage.readCookie('textsize');
		var elemBody = document.getElementsByTagName('body')[0];
		var handlerUrl = FS_HANDLER_URL + intNewSize; 
		
		//Set the new font size by swapping the className of the body element.
		if (m_intCurrentFontSize != intNewSize) {
  			elemBody.className = 'textsize' + intNewSize;
		}
		
		// Persist the value in a field for future comparison.
		m_intCurrentFontSize = intNewSize;
		
		//Adjust display of 'A' text.
		TextResizer.selectTextButton(intNewSize);
		
		//Make ajax request to handler to update font size cookie value.
		$.ajax({
		  type: 'GET',
		  url: handlerUrl
		});

	} // End changeFontSize()
	,
		
	// Add the behaviors to the font-size control
	createFontSizer: function() {  
	    
		//Wire up the text resize buttons.
		$('#' + FS_FONT_SIZE_BUTTON_1_ID).click(function(event) { TextResizer.changeFontSize(1); });
		$('#' + FS_FONT_SIZE_BUTTON_2_ID).click(function(event) { TextResizer.changeFontSize(2); });
		$('#' + FS_FONT_SIZE_BUTTON_3_ID).click(function(event) { TextResizer.changeFontSize(3); });
	    
	} // End createFontSizer()
	,
	
	//Adjust css styles for selected text resize button.
	highlightButton: function(btn) {
		btn.css('text-decoration','underline');
	}
	,
	
	//Adjust css styles for deselected text resize button.
	unHighlightButton: function(btn) {
		btn.css('text-decoration','none');
	}
	,
	
	// Change appearance of text resize buttons.
	selectTextButton: function(i) {  

		var btn1 = $('#' + FS_FONT_SIZE_BUTTON_1_ID);
		var btn2 = $('#' + FS_FONT_SIZE_BUTTON_2_ID);
		var btn3 = $('#' + FS_FONT_SIZE_BUTTON_3_ID);

		switch(i) {
			case 1:
				TextResizer.highlightButton(btn1);
				TextResizer.unHighlightButton(btn2);
				TextResizer.unHighlightButton(btn3);
				break;
			case 2:
				TextResizer.unHighlightButton(btn1);
				TextResizer.highlightButton(btn2);
				TextResizer.unHighlightButton(btn3);
				break;
			case 3:
				TextResizer.unHighlightButton(btn1);
				TextResizer.unHighlightButton(btn2);
				TextResizer.highlightButton(btn3);
				break;
		}
	} // End selectTextButton()

};

//////////////////////////////////////////////////////////
// Common
// Handles common operations
//////////////////////////////////////////////////////////
var Common = {

	refreshMe: function() {
		var url = document.location.href;
		goTo(url);
	} // End refreshMe()
	,
	
	scrollToElement: function(elem) {
	  var selectedPosX = 0;
	  var selectedPosY = 0; 
	  while(elem != null){
		 selectedPosX += elem.offsetLeft;
		 selectedPosY += elem.offsetTop;
		 elem = elem.offsetParent;
	  }
		window.scrollTo(selectedPosX,selectedPosY);
	} // End scrollToElement()
	,
	
	isNumeric: function(sText) {
		var ValidChars = "0123456789.";
		var IsNumber = true;
		var Char;
		for (i = 0; i < sText.length && IsNumber == true; i++){ 
			Char = sText.charAt(i); 
			if (ValidChars.indexOf(Char) == -1){
				IsNumber = false;
			}
		}
		return IsNumber;
	} // End isNumeric()
	,
	
	getExitLink: function(strURL, intType) {
		if (!strURL || !intType) { return; }
		var strSiteExitUrl = '/system_pages/SiteExit.aspx';
		var urlEsc = escape(strURL);
		Common.goTo(strSiteExitUrl + '?url=' + urlEsc + '&type=' + intType);
	} // End getExitLink()
	,
	
	//Navigates to a URL
	goTo: function(strURL) {
		window.location.href = strURL;
	} // End goTo()
	,

	getUrlPath: function() {
		return window.document.location.pathname.toLowerCase();
	}
	,	

	urlPathIs: function(localpath) {
		var pathname = window.document.location.pathname.toLowerCase();
		if (pathname == localpath) { 
			return true;
		}
		else {
			return false;
		}
	}
	,

	preloadImg: function(path, w, h) {
		if (document.images) {
			objImg = new Image(w, h); 
			objImg.src = path;
		}
	}
	,

	enterPress: function(btnid, e) {
	
		var key;
		if (!e) var e = window.event;
		if (e.keyCode) key = e.keyCode;	//IE
		else if (e.which) key = e.which; //FF
		
		if (key == 13) { //Enter key
			document.getElementById(btnid).click(); //Click the button.
		}
		
		//Prevent propagation.
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		
	} // End enterPress()
};


//////////////////////////////////////////////////////////
// Storage
// The storage object handles cookie operations
//////////////////////////////////////////////////////////
var Storage = {

	readCookie: function(name) {
		var nameEQ = name + '=';
		var ca = document.cookie.split(';');
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	} // End readCookie()
	,
	
	createCookie: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = '; expires=' + date.toGMTString();
		}
		else {
			var expires = '';
		}
		var ck = name + '=' + value + expires + '; path=/';
		//	if (days != -1) alert('Cookie\n' + ck + '\ncreated');
		document.cookie = ck;
	} // End createCookie()
	,
	
	expireCookie: function(name) {
		if (name) {
			Storage.createCookie(name,'',-1);
		}
	} // End expireCookie()
	,
	
	cookieQsParam: function(key) {
		key = key.toLowerCase();
		var qs = window.location.search.substring(1);
		var pairs = qs.split('&');
		for (var i = 0; i < pairs.length; i++) {
			var name = pairs[i].split('=')[0];
			var val = pairs[i].split('=')[1];
			if (name.toLowerCase() == key) {
				if (Common.isNumeric(val)) {
					Storage.createCookie(key, val, null);
				}
			}
		}
	} //End cookieQsParam()
	
};

//////////////////////////////////////////////////////////
// Linking
// The tracking object handles sitewide link wiring
//////////////////////////////////////////////////////////
var Linking = {

	formatting: function() {
		
	}
	,
		
	wireLinks: function() {
	
		/* Add PDF icons to all PDF links in main area */ 
		$("div#main a[href$='.pdf']:not([href*='http']), div#main a[href*='.cgi']").after(" <img class=\"pdf\" src=\"/images/icon/adobe-pdf.png\" width=\"12\" height=\"14\" />");
		
		$("div#navigation ul.info a span").after(" <img class=\"pdf\" src=\"/images/icon/adobe-pdf.png\" width=\"12\" height=\"14\" />");
		
		/* Add arrows to certain links */
		$("div.homepage div.banner li a").after(" <img class=\"link\" src=\"/images/bullet/carat-pink.png\" width=\"6\" height=\"8\" />");
		$("div.homepage div#info-bubble p a").after(" <img class=\"link\" src=\"/images/bullet/ribbon-arrow-pink.png\" width=\"7\" height=\"11\" />");
		
		/* Add source code cookie value to all external links for media source attribution */
		$("a[href^='http']:not([href*='astrazeneca'])").each(function() { 
			var innerHTML = this.innerHTML;
			this.href=Linking.appendSource(this.href);
			this.innerHTML = innerHTML;
		});
		
	} // End wireLinks()
	,
	
	appendSource: function(uri) {
		var joinChar = (uri.indexOf("?")>=0) ? "&" : "?";
		var sourceVal = Storage.readCookie("source");
		if (sourceVal > 0)
			return uri + joinChar + "source=" + sourceVal;
		return uri;
	} // End appendSource()
	,
	
	removeIsiGap: function() {
		if ($("div#callouts").length > 0) {
			if ($("div#callouts").get(0).innerHTML.length < 50) {
				//hide the callout div
				$("div#callouts").hide();
			}	
		}
	} // End removeIsiGap()
	
};


//////////////////////////////////////////////////////////
// Tracking
// The tracking object handles client analytics
//////////////////////////////////////////////////////////
var Tracking = {

	gaWirePdfs: function() {
	
		//alert('wiring gaWirePdfs...');
	
		// Adds GA Page Tracking to all *local* PDF links
		$("a[href$='.pdf']:not([href^='http:'])").click(function() {
			targetURI = $(this).attr("href");
			try {
				pageTracker._trackPageview(targetURI);
			} catch(error) {
				// GA Page Tracker isn't implemented correctly.
				alert('Error adding GA tracking to local PDF. Details: ' + error);
			}
			// Either opens PDF in a new window or in same window.
			//if ($(this).attr("target")=="_blank" || true) { window.open(targetURI); }
			//else { window.location=targetURI; }
			//return false;
		});
	} // End gaWirePdfs()
	,
	
	SEOSourceTagging: function() {
	    var engineList = [  "google",
                            "yahoo",
                            "msn",
                            "aol",
                            "aol",
                            "lycos",
                            "ask",
                            "altavista",
                            "netscape",
                            "cnn",
                            "looksmart",
                            "about",
                            "mamma",
                            "alltheweb",
                            "gigablast",
                            "voila",
                            "virgilio",
                            "live",
                            "baidu",
                            "alice",
                            "yandex",
                            "najdi",
                            "aol",
                            "club-internet",
                            "mama",
                            "seznam",
                            "search",
                            "szukaj",
                            "szukaj",
                            "netsprint",
                            "google.interia",
                            "szukacz",
                            "yam",
                            "pchome"];
        // AZCommon Code defines the source code in the HTTP Response Header
        if (Storage.readCookie("source") == 0) {
            for (var i = 0; i < engineList.length; i++) {
            
            }
        }
	} // End SEOSourceTagging()
	
};

//////////////////////////////////////////////////////////
// Init Events
//////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////
// Dom Ready Events
//////////////////////////////////////////////////////////
$(document).ready(function() {
	// Do these operations when the HTML is all ready...
	Site.start();
	
	//Wire the PDFs for GA tracking
	Tracking.gaWirePdfs();
	
	//Wire site links
	Linking.formatting();
   Linking.wireLinks();
   
   //Hide callout div for IE6, to prevent gap above ISI.
   Linking.removeIsiGap();
});

//////////////////////////////////////////////////////////
// Load Events
//////////////////////////////////////////////////////////
$(window).load(function() {
   // Run this when the whole page has been downloaded...
    
});


