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

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); 
}

/* dynamic select */
var isIE = navigator.userAgent.indexOf("MSIE") > 1;
var isMoz = navigator.userAgent.indexOf("Mozilla/5.") == 0;

function textboxSelect (oTextbox, iStart, iEnd) {
	switch(arguments.length) {
		case 1:
			oTextbox.select();
			break;
		case 2:
			iEnd = oTextbox.value.length;
		case 3:
			if (isIE) {
				var oRange = oTextbox.createTextRange();
				oRange.moveStart("character", iStart);
				oRange.moveEnd("character", -oTextbox.value.length + iEnd);
				oRange.select();
			} else if (isMoz){
				oTextbox.setSelectionRange(iStart, iEnd);
			}
	}
	oTextbox.focus();
}

function textboxReplaceSelect (oTextbox, sText) {
	if (isIE) {
		var oRange = document.selection.createRange();
		oRange.text = sText;
		oRange.collapse(true);
		oRange.select();
	} else if (isMoz) {
		var iStart = oTextbox.selectionStart;
		oTextbox.value = oTextbox.value.substring(0, iStart) + sText + oTextbox.value.substring(oTextbox.selectionEnd, oTextbox.value.length);
		oTextbox.setSelectionRange(iStart + sText.length, iStart + sText.length);
	}
	oTextbox.focus();
}

function autocompleteMatch (sText, arrValues) {
	for (var i=0; i < arrValues.length; i++) {
		if (arrValues[i].indexOf(sText.toLowerCase()) == 0) {
			d.getElementById("cityList").selectedIndex=i;
			return arrValues[i];
		}
	}
	return null;
}

function autocomplete(oTextbox, oEvent, arrValues) {
	switch (oEvent.keyCode) {
		case 38:
		case 40:
		case 37:
		case 39:
		case 33:
		case 34:
		case 36:
		case 35:
		case 13:
		case 9: 
		case 27:
		case 16:
		case 17:
		case 18:
		case 20:
		case 8:
		case 46:
		return true;
		break;
	default:
		textboxReplaceSelect(oTextbox, String.fromCharCode(isIE ? oEvent.keyCode : oEvent.charCode));
		var iLen = oTextbox.value.length;
		var sMatch = autocompleteMatch(oTextbox.value, arrValues);
		if (sMatch != null) {
			oTextbox.value = sMatch;
			textboxSelect(oTextbox, iLen, oTextbox.value.length);
		}
		return false;
	}
}	

/* yellow fade technique */
function YFTinit(x,i){ 
	var colour = ["F","E","D","C","B","A"];
	setTimeout("YFT("+x+",'"+colour[x]+"','"+i+"')", 500);
}

function YFT(x,c,i){
	if(isNaN(x)) { return; }
	d.getElementById(i).style.backgroundColor = "#FF"+c;
	if(x>0) { YFTinit(x-1,i); } 
}

/* 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);
		if(window.attachEvent){
			spanObj.attachEvent("onclick", chkAd) 
		} else if(window.addEventListener) {
			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(){ 
				if(d.getElementById("pagination") && location.search.indexOf("pageRequested=all")==-1){
					qmod = (location.search) ? "\u0026" : "?";
					url = location.href.replace(/pageRequested=([0-9]+)/,"");
					location.href=url+qmod+"pageRequested=all\u0026print=true";
				}	else {
					window.print(); 
				}
				return false; 
			}
			c[x].getElementsByTagName("a")[0].title="Click to print this page";
		}
	}
}

function chkPrint(){
	if(location.search.indexOf("print=true")!=-1 && window.print){
		window.print();
		if(ua.indexOf("safari")==-1) { history.go(-1); }
		else { return; }
	}
}

/* duplicate tools within aricles */
function addArticleTools(){
	if(ua.indexOf("mac")!=-1 && ua.indexOf("msie")!=-1) { return; }
	var aTools = d.getElementById("sidebarTools").cloneNode(true);
	aTools.id = "articleTools";
	aToolsLinks = aTools.getElementsByTagName("a");
	
	if(d.getElementById("articleToolsHolder")){ aToolsHolder = d.getElementById("articleToolsHolder"); }
	else { //legacy
		if(d.getElementById("comments")){
			sibObj = d.getElementById("comments");
		} else 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");
		}
	}
	
	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")) }
		if(aToolsLinks[x].parentNode.className=="article") { aToolsLinks[x].replaceChild(d.createTextNode("Single page"),aToolsLinks[x].firstChild) }
		else if(aToolsLinks[x].parentNode.className=="comment" && d.getElementById("commentRSS")) { 
			if(aToolsLinks[x].className=="closed"){
				commentvalue = aToolsLinks[x].firstChild.nodeValue.replace(/Comments \(([0-9]+)/,"Follow conversation ($1");
			} else if(aToolsLinks[x].firstChild.nodeValue.search(/Comments \(([0-9]+)/)!=-1){
				commentvalue = aToolsLinks[x].firstChild.nodeValue.replace(/Comments \(([0-9]+)/,"Join conversation ($1");
			} else {
				commentvalue = aToolsLinks[x].firstChild.nodeValue.replace(/Comment/,"Leave the first comment");
			}
			url = aToolsLinks[x].href;
			aToolsLinks[x].href = url.substring(0,url.length-1);
			if(url.indexOf("about:blank")!=-1) aToolsLinks[x].href = url.substring(11,url.length-1);
			aToolsLinks[x].firstChild.nodeValue=commentvalue;
		}
		else if(aToolsLinks[x].parentNode.className=="comment") { aToolsLinks[x].appendChild(d.createTextNode(" to the Editor")) }
	}	
	
	if(d.getElementById("articleToolsHolder") && aToolsHolder) { aToolsHolder.appendChild(aTools); }
	else { //legacy
		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";
}

/* get elements exact position */
function geElPos(nObj){
	var l = 0;
	var t = 0;
	if(nObj.offsetParent) {
		while (nObj.offsetParent){
			l += nObj.offsetLeft
			t += nObj.offsetTop
			nObj = nObj.offsetParent;
		}
	}
	var el_pos = [l,t]
	return el_pos;
}			


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

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

changeFontSize(amount);

onload = function init(){
	if(hub!==true){
		if(ua.indexOf("safari")==-1 && d.getElementById("aSMholder")) { 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();
		chkPrint();
	}
}
