var d = document;
var ua = navigator.userAgent.toLowerCase();

var chgCSS = (ua.indexOf("safari")==-1 && ua.indexOf("opera")==-1 && d.styleSheets[0].addRule) ? true : false;
var tgam_domain =  "http://www.theglobeandmail.com";
var thisURL = window.location+"";
var isTGAM = (thisURL.indexOf(tgam_domain)!=-1) ? true : false;

/*Cookies*/
function getCookie(name){  
	var the_cookie = name + "="; 
	if (d.cookie.length > 0) {        
		begin = d.cookie.indexOf(the_cookie);  
		if (begin != -1) {       
			begin += the_cookie.length;
			end = d.cookie.indexOf(";", begin);
			if (end == -1) { end = d.cookie.length; }
			return unescape(d.cookie.substring(begin, end));
		} 
	} return null;
}

function setCookie(name, value){
	var time = new Date();
	time.setTime(time.getTime() + (1000*60*60*24*365));//expires in a year
	d.cookie = name + "=" + escape(value) + "; path=/; expires=" + time.toGMTString();
}

function deleteCookie(name) {
	if(getCookie(name)) d.cookie = name + "=" + "; path=/; expires=Mon, 01 Jan 01 01:01:01 GMT";
}	

/* site menu */
function createASMenu(){
	var nObj = d.getElementById("aSMholder");
	nObj.name = nObj.id;
	nObj.style.visibility = "visible";
	nObj.onmouseover=function(){ this.style.height = "397px"; }
	nObj.onmouseout=function(){ this.style.height = "19px"; }
}

menuHover = function() {
	var menu = document.getElementById("siteSections");
	menu.onmouseover=function() { this.className+=" hover"; }
	menu.onmouseout=function() { this.className=this.className.replace(new RegExp(" hover\\b"), ""); }
}

if(window.attachEvent && d.getElementById("siteSections")){ 
	d.getElementById("allSectionMenuLink").onclick = function(){ return false; }
	window.attachEvent("onload", menuHover); 
}

/* font size */
function createFontSizer(){	
	var fsObj = d.createElement("p");
	fsObj.id = "fontSize";
	fsObj.style.display = "none";
	d.getElementById("breadcrumb").appendChild(fsObj);

	var spanObj;
	for(x=2;x>-3;x--){
		spanObj = d.createElement("span");
		spanObj.id = "fs"+x;
		spanObj.onclick = function () { 
			changeFontSize(this); 
			var size = this.id.split("fs")[1];
			var fsObj = this.parentNode.getElementsByTagName("span");
			highlightFontSize(this,size,fsObj); 
		}
		spanObj.appendChild(d.createTextNode("G"));
		fsObj.appendChild(spanObj);
		(spanObj.attachEvent) ? spanObj.attachEvent("onclick", chkAd) :	 spanObj.addEventListener("click",chkAd,false);
	}
	fsObj.appendChild(d.createTextNode("Text Size:"));
	addCSS("screen","fontsizer");
}

function highlightFontSize(nObj,size,fsObj){
	changeFontSize(nObj);
	for(x=0;fsObj.length>x;x++) { 
		fsClass = fsObj[x].id;
		if(fsClass!="active") {
			fsObj[x].onclick = function () { highlightFontSize(this,this.id.split("fs")[1],this.parentNode.getElementsByTagName("span")); }
			fsObj[x].className = "";
		}
		othersize = fsObj[x].id.split("fs")[1];
		change = parseInt(othersize)-parseInt(size);
		if (change > 0) {
			fsObj[x].title = "Increase your text size by "+change+" level";
		} 	else {
			change = Math.abs(change);
			fsObj[x].title = "Decrease your text size by "+change+" level";
		}
		if(change>1) fsObj[x].title += "s";
	}
	nObj.className = "active"; 
	nObj.title = "This is you current text size level"; 
	nObj.onclick = null;
}

function changeFontSize(v){
	var css,rule,nObj;
	var amount = (v.nodeType==1) ? v.id.split("fs")[1].split(" active")[0] : parseInt(v);
	var fS = (1 + (amount*0.08))+"em";
	var rSB = ["headline","author","article","sidebar"];
	if(chgCSS && isTGAM) { //IE
		css = d.styleSheets[0];
	} else if(d.createElement) { // W3C DOM
		css = d.createElement("style");
		css.media = "screen";
		css.type = "text/css";
		d.getElementsByTagName("head")[0].appendChild(css);
	}
	for(x=0;rSB.length>x;x++){ 
		if(d.getElementById(rSB[x])){
			if(rSB[x]=="sidebar"){ fS = 11+parseInt(amount)+"px"; }
			rule = "#"+rSB[x]+" { font-size: "+fS+"; }";
			if(v.nodeType==1){
				d.getElementById(rSB[x]).style.fontSize = fS; 
			} else if(css.addRule && isTGAM){ //IE
				css.addRule("#"+rSB[x],"font-size: "+fS);
			} else if(d.createStyleSheet){// GT in Opera/IE
				d.createStyleSheet().cssText = rule;	
			} else if(d.createTextNode) {// W3C DOM
				rule = d.createTextNode(rule);
				css.appendChild(rule);
			}
		}
	}
	
	setCookie("gam_style", "fS="+amount+";")
}

function checkFontSize(v){
	var cookie = getCookie("gam_style");
	if(cookie==null){ cookie = "fS=0;"; }
	cookie = cookie.split(";");
	for(x=0;cookie.length>x;x++){
		if(cookie[x].indexOf("fS")!=-1) {	return cookie[x].split("fS=")[1]; }
	}
}

/* windows print */
function printThis(nObj){
	var c = nObj.childNodes;
	for(x=0;c.length>x;x++){
		if(c[x].className=="print"){
			c[x].getElementsByTagName("a")[0].onclick=function(){ window.print(); return false; }
		}
	}
}

/* duplicate tools within aricles */
function addArticleTools(){
	var aTools = d.getElementById("sidebarTools").cloneNode(true);
	aTools.id = "articleTools";
	aToolsLinks = aTools.getElementsByTagName("a");
	if(d.getElementById("storyAd")){
		sibObj = d.getElementById("storyAd");
	} else if(d.getElementById("siteSearch")){
		sibObj = d.getElementById("siteSearch");
	} else if(d.getElementById("ppvHelpPromo")){
		sibObj = d.getElementById("ppvHelpPromo");
	} else {
		sibObj = d.getElementById("backLink");
	}
	if(ua.indexOf("mac")!=-1) { d.getElementById("chewy").insertBefore(aTools,sibObj); } // IE 5 Mac needs it here (non-IE others don't care)
	for(x=0;aToolsLinks.length>x;x++){
		if((aToolsLinks[x].parentNode.className=="email") || (aToolsLinks[x].parentNode.className=="print")) { aToolsLinks[x].appendChild(d.createTextNode(" this article")) }
		else if(aToolsLinks[x].parentNode.className=="comment") { aToolsLinks[x].appendChild(d.createTextNode(" to the Editor")) }
	}	
	try {
		d.getElementById("chewy").insertBefore(aTools,sibObj); // IE Win needs it here (non-IE others don't care)
	} catch (DOMException) {
		sibObj.previousSibling.previousSibling.appendChild(aTools); // For GI, and node not found
	};
}

/* get stories, and hide if listed */
function getSLinks(i,s_id,count){
	var s_links = d.getElementById(i).getElementsByTagName("a");
	for(x=0;s_links.length>x;x++){
		if((s_links[x].href.indexOf(s_id)>1) || (x>=count)){
			nObj = ((i=="relatedNewsNav" || i=="wiseNav") && s_links[x].parentNode.parentNode.nodeName=="LI") ? s_links[x].parentNode.parentNode : s_links[x].parentNode;
			nObj.style.display = "none";
			return;
		}
	}
}

/* enlarge image */
function viewBigImage(w,h,url,n,t){
	var iW;
	t = "Image from \u201C"+t+"\u201D";
	n = "__"+n;
	var regex = /\W+/;
	if(regex.test(n)) { n = n.replace(/\W+/,'_'); }
	var scrolling = false;
	try {
		if(w>screen.availWidth) {
			w = screen.availWidth;
			scrolling = true;
		}
		if(h>screen.availHeight) {
			h = screen.availHeight;
			scrolling = true;
		}
	}
	catch(e) {}
	var f = "width="+w+",height="+h;
	f += ",left=10,top=10,menubar=no,toolbar=no,status=no,screenX=0,screenY=0";
	f += (!scrolling) ? ",scrollbars=0" : ",scrollbars=1";
	(window.iW==null||iW.closed) ? iW=window.open("",n,f) : iW.location.href = ""; 
	iW.document.write("<html lang=\"en-ca\"><head><title>"+t+"</title></head><body style=\"margin:0px;padding:0px\"><div><img src=\""+url+"\" width=\""+w+"\" height=\""+h+"\" alt=\""+t+"\"></div></body></html>");
	iW.document.close(); 	
	iW.focus();
	return false;
}

/* pop-up window */
function _open_popup_window(w,h,url,slug,t) {
	var regex = /\W+/;
	if(regex.test(slug)) { slug = slug.replace(/\W+/, '_'); }
	if(w != '' && h != '') { 
		framesPopUp(url,t,slug,w,h); 
		return false;
	}
	return true;
}

function framesPopUp(filename,t,n,w,h) {
	var n = "__" + n;
	var regex = /\W+/;
	if(regex.test(n)) { n = n.replace(/\W+/, '_'); }
	params = "width="+ w +",height="+h + ",resizable";
	winExec = n +"= window.open('','"+n+"', params)";
	content = "<html lang=\"en-ca\"><html><head><title>"+t+"</title></head><frameset rows='0,*' frameborder='NO' border='0' framespacing='0'><frame name='topFrame' scrolling='NO' src='about:blank'><frame name='mainFrame' src='"+ filename +"' scrolling='auto'></frameset><noframes><body>This require a browser that supports frames.</body></noframes></html>"; 
	eval(winExec);
	eval(n + ".document.open()");
	eval(n + ".document.write(content)");
	eval(n + ".document.close()");
}

/* validate search */
function validateSearch(theForm) {
	var regex = /^(\s)*$/;
	var noSearchWordFound = theForm.query.value.search(regex);
	if(noSearchWordFound != -1) {
		alert("Please enter a search term.");
		return false;
	} else {
		theForm.submit();
	}
}

/* init sIFR */
function runSIFR(){ 
	sIFR.replaceElement("h2", "http://images.theglobeandmail.com/styles/type/walbaum.swf", "#000000", null, null, null, 0, 0, 0, 0, null, null, "opaque");
	sIFR.replaceElement("h1", "http://images.theglobeandmail.com/styles/type/helveticaneue.swf", "#660000", null, null, null, 0, 0, 0, 0, null, "upper", "opaque");
	sIFR.replaceElement("#headline h3", "http://images.theglobeandmail.com/styles/type/walbaum.swf", "#666666", null, null, null, 0, 0, 0, 0, null, null, "opaque");
}

/* add CSS links */
function addCSS(media,url){
	var lObj = d.createElement("link");
	lObj.type = "text/css";
	lObj.rel = "stylesheet";
	lObj.href = "http://images.theglobeandmail.com/styles/"+url+".css";
	lObj.media = media;
	d.getElementsByTagName("head")[0].appendChild(lObj);
}

/* adjust ad position */
function chkAd(){
	if(d.getElementById("a3s")) { 
		var box_y = parseInt(d.getElementById("chewy").offsetTop+d.getElementById("a3s").offsetTop);
		var body = (ua.indexOf("msie 5")!=-1 && ua.indexOf("window")!=-1) ? d.body.scrollHeight :  parseInt(d.getElementsByTagName("body")[0].offsetHeight);
		d.getElementById("a3").style.top = box_y-body+"px";
	}
}

/* hide inline ads */
function hideAds(i,cN,t){
	var nObj = d.getElementById(i).getElementsByTagName("DIV");
	for(x=0;nObj.length>x;x++){
		if(nObj[x].className.indexOf(cN)!=-1 && nObj[x].className.indexOf("ad")!=-1) { 
			for(y=0;nObj[x].childNodes.length>y;y++){
				if(nObj[x].childNodes[y].nodeType == 1 && nObj[x].childNodes[y].firstChild && nObj[x].childNodes[y].firstChild.nodeValue != t) { return; }
			}
			nObj[x].style.display = "none";
			return;
		}
	}
}

/* prevent sidebar overlap */
function getHeight(){

	if(d.getElementById("article") && d.getElementById("sidebar") && d.getElementById("footer")) {	
		var a = d.getElementById("article");
		var s = d.getElementById("sidebar");
		f = d.getElementById("footer");
	} else {
		return;
	}

	a.style.minHeight = 0;
	a.style.height = "auto";
	
	if((s.offsetHeight+s.offsetTop) > f.offsetTop){
		d.getElementById("footer").style.marginTop = s.offsetHeight+s.offsetTop-f.offsetTop+20+"px";
	} 
}

/* set top to height of another object */
function setTop(obj1,obj2,mod){
	obj2.style.top = obj1.offsetHeight+mod+"px";
}

/* init */
var amount = checkFontSize();

if(typeof sIFR == "function"){ 
	addCSS("screen","sifr");
	addCSS("print","sifr-print");
}

changeFontSize(amount);

onload = function init(){
	if(ua.indexOf("safari")==-1) { createASMenu(); }
	createFontSizer(); 
	if(d.getElementById("fs"+amount) && d.getElementById("fontSize")) { 
		highlightFontSize(d.getElementById("fs"+amount),amount,d.getElementById("fontSize").getElementsByTagName("span"));
	}
	hideAds("article","button","Advertisements");
	if(d.getElementById("sidebarTools")) { 
		addArticleTools();
		if(window.print){ 
			printThis(d.getElementById("sidebarTools"));
			if(d.getElementById("articleTools")) { printThis(d.getElementById("articleTools")); }
		}	
		getHeight();
	}
	chkAd();
}
