//////////////////////////////////////////////////////////
// Constants
//////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////
// Site
// The "Site" object should contain all of the code that adds behavior 
// to the various client side controls.
//////////////////////////////////////////////////////////

var Site = {
   
	start: function() { 	
	} // End start()
};



//////////////////////////////////////////////////////////
// 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()
	,

	urlPathIs: function(localpath) {
		var pathname = window.document.location.pathname.toLowerCase();
		if (pathname == localpath) { 
			return true;
		}
		else {
			return false;
		}
	}
	,

	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 = {

	wireLinks: function() {
	
		/* Add video icon */
		$("div#main div.information div.highlight a[href*='video'], div#main div.information div.video p a").after(" <img class=\"flash\" src=\"/images/icon/adobe-flash.png\" width=\"16\" height=\"16\" alt=\"Video Player\" />");
		
		/* Add PDF icons to all PDF links in main area */
		$("div#main a[href$='.pdf']:not(div#callouts a), div#main a[href*='.cgi']").after(" <img class=\"pdf\" src=\"/images/icon/adobe-pdf.png\" width=\"12\" height=\"14\" alt=\"Adobe PDF\" /> ").attr('target','_blank');
		$("div#navigation ul.info a").append(" <img class=\"pdf\" src=\"/images/icon/adobe-pdf.png\" width=\"12\" height=\"14\" alt=\"Adobe PDF\" /> ").attr('target','_blank');
		
		/* 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;
		});
		
		/* Add External link icon and onclick event for interstitial pages to ALL External links in main area, except for AZ links */
		$("div#main a[href^='/system_pages/SiteExit.aspx']:not([href*='astrazeneca']), div#main a[href^='https://www.drtms.net/aszseroquel/activation/']").after(" <img class=\"external\" src=\"/images/icon/external.png\" alt=\"external link\" />");

	} // 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()

};



//////////////////////////////////////////////////////////
// Replacing
// Replace HTML Tables with stylized graphics
//////////////////////////////////////////////////////////
var Replacing = {

	replaceItems: function() {
		$("table#hcp-types").before("<img src=\"/images/chart/hcp-types.png\" alt=\"Chart showing the different types of health care professionals who focus on treating bipolar disorder\" />").remove();
	} // End replaceItems()
	
};



//////////////////////////////////////////////////////////
// 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()
	,
	wireUXRegion: function() {
		$("div#header a:not([href^='http:'][href^='javascript:'][href^='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "h")});
		$("div#navigation a:not([href^='http:'][href^='javascript:'][href^='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "l")});
		$("div#content a:not([href^='http:'][href^='javascript:'][href^='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "m")});
		$("div#callouts a:not([href^='http:'][href^='javascript:'][href^='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "r")});
		$("div#footer a:not([href^='http:'][href^='javascript:'][href^='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "f")});

		$("div.next-steps a:not([href^='javascript:'][href='/system_pages/'])").attr("href", function() { return Tracking.appendUXRegion(this, "n")});
	} // End UXTrack()
	,
	appendUXRegion: function(p, region) {
		p = new String(p.toString());
		var newVar = "ux="+region;
		var hash = "";
		var hashIndex = p.indexOf("#");
		if (hashIndex>=0) {
			hash = p.substr(hashIndex);
			p = p.substring(0,hashIndex-1);
		}
		if (p.match(/ux=[a-z]/i) != null) {
			p = p.replace(/ux=[a-z]/,newVar);
		} else {
			if (p.indexOf("?")>=0) {
				p += "&";
			} else {
				p += "?";
			}
			p += newVar + hash
		}
		return p;
	} // End appendUXRegion(linkPath, pageRegion)
	
};


//////////////////////////////////////////////////////////
// Formatting
// Hides areas based on Flash and JavaScript capability
//////////////////////////////////////////////////////////
var Formatting = {

    hideJSFlash: function() {
        if (swfobject.getFlashPlayerVersion().major >= 8) {
            $("p.adobe\\ flash").css("display","none");
            $("p.safariflash").css("display","none"); //Hide for safari.
        }
    } // end hideJSFlash()
	,
	
	copyAltTitle: function() {
		$("img").each(function(i) {
			$(this).attr("title",$(this).attr("alt"));
		});
	}
	
};


//////////////////////////////////////////////////////////
// Init Events
//////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////
// Dom Ready Events
//////////////////////////////////////////////////////////



/* Center DIV on the page */
$.fn.center = function () {
    $(this).css("left", ( $(window).width() - $(this).width() ) / 2+$(window).scrollLeft() + "px");
	$(this).css("top", ( $(window).height() - $(this).height() ) / 2+$(window).scrollTop() + "px");
    return $(this);
}



$(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.wireLinks();
	
   //Hide callout div for IE6, to prevent gap above ISI.
   Linking.removeIsiGap();
   
	//Wire links to track UX regions
	Tracking.wireUXRegion();

   //Hide flash alert if JavaScript and Flash are working.
   Formatting.hideJSFlash();
   Formatting.copyAltTitle();

	// Replace items, charts, tables
	Replacing.replaceItems();

    // Set up accordions
    $('div.accordion').accordion({
          header: "h2",
          animated: false,
          clearStyle: true,
          autoHeight: false,
          active: false,
          alwaysOpen: false
    });
    //Accordions are initially hidden via script on page. Show accordions.
    $('div.accordion').show(); 
});

//////////////////////////////////////////////////////////
// Load Events
//////////////////////////////////////////////////////////
$(window).load(function() {
   // Run this when the whole page has been downloaded...
    //setXmlPath("CarolineFriend.xml");
});



function setXmlPath(xml, swf){

    //Set hidden input to xml path so share site control can access it
    $("input:hidden#videoFileName").val(xml);

    //Hard coded paths to the xml and swf files
    var swfpath = "/swf/"
    
    //if swf is not passed in then default it to sqc112c.swf    
    if (arguments.length < 2){    
        swf = 'sqc112c.swf'
    }
    
    // if the first character of the path is a hash sign, rip it out. 
    // the path will have a hash sign if the path is coming from an anchor tag on the site.
    if (xml.indexOf('#') == 0){
        xml = path.substring(1, xml.length);
    }
    
    var flashvars = { configPath: xml };
	var params = {wmode: "opaque"};
	var attributes = {};
	swfobject.embedSWF(swfpath + swf, "video", "697", "585", "8.0.0", "", flashvars, params, attributes);	
}