var d = document;
var biscuit = d.cookie;
var agtname = navigator.appName;
var agt = navigator.userAgent.toLowerCase();
var major = parseInt(navigator.appVersion);
var	minor = parseFloat(navigator.appVersion);

checkLoginStatus(location.href); //confirm cookies

window.onresize = function (){
	if(d.getElementById("rectAd")) adDisplay();
	detectBrowser();
}

window.onload = function (){
	if(location.hash=="#colPeople") d.inSearch.query.focus();
	detectBrowser();
	
}
detectBrowser();

window.onload = init;

function init(){
  detectBrowser();
}

function detectBrowser()
{

  var browser=navigator.appName;
  var b_version=navigator.appVersion;
  var version=parseFloat(b_version);
  if (browser=="Microsoft Internet Explorer" && (version>=4))
  {
    if (document.getElementById('header')){
    //alert(document.body.clientWidth);
    //alert(document.getElementById('header').style.width);
      width = document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
      if (width <= 1000){
        document.getElementById('header').style.width = "1000px";
      } else {
        document.getElementById('header').style.width = "";
      }
    }
    
  }

}

/* login check */
function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = d.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (d.cookie.substring(i, j) == arg) { return getCookieVal (j); }
		i = d.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;	
	}
	return null; 
}
	
function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) {	endstr = d.cookie.length; }
	return unescape(d.cookie.substring(offset, endstr)); 
}

function checkLoginStatus(url){		
	var baseurl = "http://fc.globeinvestor.com/";
	var loginurl = "http://golddb.globeinvestor.com";
	
	var newurl = baseurl;
	
	/*if((GetCookie('globeinvestor_uid')!=null)) { 
		(url.indexOf("home2.html")!=-1) ? newurl = baseurl+"/home4.html" : newurl = url;
	} else */
	if(!(GetCookie('globeinvestor_uid')!=null)	&& (GetCookie('auto_login'))) { 
		newurl = loginurl+"/invest/investSQL/fc.login?pi_back_url="+url;
	}	else if(GetCookie('fc_registration') =='yes') {
		newurl = url;
	}
	if(
	url!=newurl && 
	(url.indexOf("home4.html")==-1) && 
	url.indexOf("/public/")==-1 && 
	url.indexOf("/promo/")==-1 && 
	url.indexOf("/tradefreedom/")==-1 &&
	url.indexOf("/plus/login.html")==-1 &&
	url.indexOf("/plus/index.html")==-1 &&
	(url.indexOf("/plus/ ") > 0 && url.indexOf("html")==-1) &&
	url.indexOf("fc.gam_conversion")==-1 &&  
	url.indexOf("/fundtrade/")==-1 && 
	url.indexOf("set_online_trading")==-1 && 
	url.indexOf("fc.contest")==-1  &&
	url.indexOf("fc.join_group")==-1  &&
	url.indexOf("fc.my_stocks")==-1  &&
	url.indexOf("fc.view_ranking")==-1  &&
	url.indexOf("fc.most_picked")==-1  &&
	url.indexOf("fc.check_user")==-1  &&
	url.indexOf("/servlet/GIS.Servlets.PollDisplay")==-1 && 
	url.indexOf("fc.new_regist")==-1 &&
	url.indexOf("fc.login")==-1 &&
	url.indexOf("fc.convert_symp_users")==-1 &&
 	url.indexOf("fc.upsell_page")==-1)
	
	{
	top.location = newurl ; }
}



/*generic functions*/
function QuickPopup(popup_URL,pop_width, pop_height) {
  surv_win = window.open(popup_URL,'pop_win2','toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=0,width='+pop_width+',height='+pop_height).focus();
}

function getCookie(name) {
  var index = biscuit.indexOf(name + "=");
  if (index == -1) return null;
  index = biscuit.indexOf("=", index) + 1;
  var endstr = biscuit.indexOf(";", index);
  if (endstr == -1) endstr = biscuit.length;

  return unescape(biscuit.substring(index, endstr));
  alert("cookie value: " + getCookie(name));
}

function getCookieValue(cookieName){    
var search, offset, end;   
search = cookieName + "=";  
if (biscuit.length > 0)   { 
  // if there are any cookies
	offset = biscuit.indexOf(search);
 		if (offset != -1)       {
      // if cookie exists
			offset += search.length;           
      // set index of beginning of value
			end = biscuit.indexOf(";", offset);           
      // set index of end of cookie val
			if (end == -1)		        
				end = biscuit.length;		
				return unescape(biscuit.substring(offset, end));        
			}    
		}
}

function createRdmTextLink(i,contents,targets,style){
	var content = randomArray(contents);
	var target = randomArray(targets);
	if(d.createElement){
		var nObj = d.createElement("A");
		nObj.href = target;
		nObj.className = style;
		nObj.appendChild(d.createTextNode(content));
		d.getElementById(i).appendChild(nObj);
	} else { d.write("<a href=\""+target+"\" class=\""+style+"\">"+content+"</a>");	}
}		

function randomArray(a) {
	return a[Math.floor(Math.random()*a.length)];
}

/*specific*/

function doCheck(name) { 
  var val = getCookie(name);
	var daysleft = getCookieValue("trial_days_remaining");
  var frag = null;
  if (val != null) {
		if (daysleft > '1' || daysleft == null || daysleft == "") {
      // they have xx days left or are subscribed
      // alert("cookie name: " + getCookie(name));
      // alert("cookie value: " + daysleft);
		  frag = frag1;
    } else if (daysleft == '0') {
      // they are expired
      // alert("cookie name: " + getCookie(name));
      // alert("cookie value: " + daysleft);
		  frag = frag2;
		} else {
  		frag = frag2;
		}
  } else {
      // alert("cookie name: " + getCookie(name));
      // alert("cookie value: " + daysleft);
	   frag = frag2;
  }
  var re = /\+/gi;
  var cleanFrag = frag.replace(re, " ");
  d.writeln( unescape(cleanFrag) );
}

function noteworthyCheck(name) { 
  var val = getCookie(name);
	var daysleft = getCookieValue("trial_days_remaining");
  if (val != null) {
		if (daysleft > '1' || daysleft == '0') {
      // they have xx days left or are expired trial users
      // alert("cookie name: " + getCookie(name));
      // alert("cookie value: " + daysleft);
  		d.write('<br><img src="/images/trans.gif" width="1" height="1" vspace="2" alt=""><br><a href="http://gold.globeinvestor.com/public/help/popup/help_orderbyphone.html" onClick="snapWin = window.open (\'http://gold.globeinvestor.com/public/help/popup/help_orderbyphone.html\', \'snapWin\', \'height=350,width=490,menubar,scrollbars\');snapWin.focus();return false" target="_blank">Subscribe by Phone</a><br>Subscribing is easy. Call us today!');
    } else if (daysleft == null || daysleft == "") {
      // they are subscribed
      // alert("cookie name: " + getCookie(name));
      // alert("cookie value: " + daysleft);
  		d.write("");
		} else {
  		d.write("");
		}
  } else {
    // no cookie
    // alert("cookie name: " + getCookie(name));
    // alert("cookie value: " + daysleft);
    d.write('<br><img src="/images/trans.gif" width="1" height="1" vspace="2" alt=""><br><a href="http://gold.globeinvestor.com/public/help/popup/help_orderbyphone.html" onClick="snapWin = window.open (\'http://gold.globeinvestor.com/public/help/popup/help_orderbyphone.html\', \'snapWin\', \'height=350,width=490,menubar,scrollbars\');snapWin.focus();return false" target="_blank">Subscribe by Phone</a><br>Subscribing is easy. Call us today!');
  }
}

function chartchange(indexbar,indexsymbol,sym1,symm){ 
	var ran_number=Math.floor(Math.random()*1000000000);
	d.charts.pi_symbol.value = symm;
	d.imagech.src = "/images/mar-" + indexbar + "-gold.gif";
	d.image1.src ="http://www.globeinvestor.com/generated/charts/" + sym1 + ".png?ord=" + ran_number;
}

/*tracker*/


// Verify browser
function verifyBrowser(){

	nav  = ((agt.indexOf('mozilla') != -1) && ((agt.indexOf('spoofer') == -1)
			&& (agt.indexOf('compatible') == -1)));
	nav4up = (nav && (major >= 4 && minor >= 4.08));
	nav6up = (nav && (major >= 5));
	
	ie   = (agt.indexOf("msie") != -1);
	ie4up  = ie  && (this.major >= 4);

	if (nav6up || (!nav4up && !ie4up))
	{
		alert("We're sorry, the GOLD Tracker applet will not run on versions of Netscape 6 (or higher) or Netscape 4.07 (or lower). Please use a browser that is Microsoft Internet Explorer 4 or higher, or Netscape 4.08 to Netscape 4.79.");
		return false;
	}

	return true;
}

// Create a popup window
function createPopupWindow(url, name, width, height, resizable, centered, scrollbars){
  // Calc position (center window).
	var x = (screen.availWidth - width) / 2;
	var y = (screen.availHeight - height) /2;

  // Reset position if user requested not to center.
	if (typeof(centered) != 'undefined' && centered == false)
	{
		x = 0;
		y = 0;
	}

	var wndopts = "toolbar=0,height=" + height + ",width=" + width + ",menubar=0";
	
	if (typeof(resizable) != 'undefined' && resizable == false)
		wndopts += ",resizable=0";
	else
		wndopts += ",resizable=1";
	
	if (typeof(scrollbars) != 'undefined' && resizable == false)
		wndopts += ",scrollbars=0";
	else
		wndopts += ",scrollbars=1";

    var agt = navigator.userAgent.toLowerCase();
	if ((agt.indexOf('mozilla') != -1) && ((agt.indexOf('spoofer') == -1)
			&& (agt.indexOf('compatible') == -1)))
		wndopts += ",screenX=" + x + ",screenY=" + y;
	else
		wndopts += ",left=" + x + ",top=" + y;

	return window.open(url, name, wndopts).focus();
}

// Launches the Java client in a new window
function openGIGClient(){
//	if (!verifyBrowser())	return false;
	var width = Math.min(850, screen.availWidth);
	var height = Math.min(550, screen.availHeight);
  // Gain more height (if possible)
	if (screen.availHeight >= 650) height = 650;
	createPopupWindow("http://golddb.globeinvestor.com/invest/investSQL/fc.launch_applet?pi_url=http://finserv.globeinvestor.com/fcclient7/mainframe.htm", "GIGCWnd", width, height, false, (screen.availHeight >= 650 ? true : false));
	return true;
}

// Sets the correct parameters for new searches
function setSearch(form){
	var path = location.pathname;
	if(path.indexOf("rtgam")!=-1) form[0].checked  = true;
	else if(path.indexOf("dowjones")!=-1) form[1].checked  = true;
	else if(path.indexOf("rttrader")!=-1) form[2].checked  = true;
	else if(path.indexOf("cdnwires")!=-1) form[3].checked  = true;
	else if(path.indexOf("uswires")!=-1) form[4].checked  = true;
	else if(path.indexOf("stocks")!=-1) {
		form[0].checked = true;
		form[1].checked = true;
	}	
}	


// With stories with pre at first, hide ad, called in templates
function adDisplay(v){
if(d.getElementById){ // supports W3C DOM?
	var values;
	var nObj = d.getElementById("commentBody");
	var sObj = d.getElementById("rectAd").style;
	var lObj = d.getElementById("hideAdText");
	var firstEl = nObj.childNodes[0];
	if(firstEl.nodeType != 1) firstEl = nObj.childNodes[1];
 	((sObj.display!="none" && v) || (firstEl.nodeName.toLowerCase() == "pre" && !v)) ? values = ["none","Show"] : values = ["block","Hide"];
	sObj.display = values[0];
	lObj.firstChild.nodeValue = values[1]+" advertisement";
	lObj.blur();
}}

function setVisit(CURRENT_STATS_TAG,archive,date,slug){
	var lp = location.pathname;
	var path;
	var secure = (CURRENT_STATS_TAG=="secure" || location.protocol=="https:") ? "s" : "";
	if(
		(CURRENT_STATS_TAG=="home-subscriptionSection" && lp.indexOf("fc.")!=-1) ||
		(lp.indexOf("fc.login")!=-1) ||
		(lp.indexOf("fc.reset_password")!=-1) ||
		(lp.indexOf("fc.new_regist_page")!=-1) ||
		(lp.indexOf("fc.cancel_service")!=-1) ||
		(lp.indexOf("fc.update_registration")!=-1) ||
		(lp.indexOf("fc.account_balance")!=-1)
	) { 
		path = location.pathname.split("fc.");
	}	else if(
		(lp.indexOf("help_orderbyphone")!=-1) ||
		(lp.indexOf("help_pricing")!=-1)
	) { 
		path = location.pathname.split(".html");
		path = path[0].split("/help_");	
	} else if(lp.indexOf("US_pricing")!=-1) { 
		path = location.pathname.split(".html");
		path = path[0].split("promo/");
	}
	var subpage = (path) ? "\u0026page="+path[1] : "";
	var visit = "<img src=\"http"+secure+"://visit.theglobeandmail.com/counter.visit?grp=finance\u0026site=globeinvestor\u0026l1=globeinvestorgold\u0026l2="+CURRENT_STATS_TAG+subpage+"\u0026ord=" + (new Date().getTime());
	if(archive && date && slug) visit += archive+"."+date+"."+slug;
	visit += "\" width=\"1\" height=\"1\" alt=\"\" /><br />";
	return visit;
}	


function WM_readCookie(name) {
    if(document.cookie == '') { // there's no cookie, so go no further
            return false; 
    } else { // there is a cookie
            var firstChar, lastChar;
            var theBigCookie = document.cookie
            firstChar = theBigCookie.indexOf(name);            // find the start of 'name'
            var NN2Hack = firstChar + name.length;
            if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) { // if you found the cookie
                firstChar += name.length + 1; // skip 'name' and '='
                lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
                if(lastChar == -1) lastChar = theBigCookie.length;
                return unescape(theBigCookie.substring(firstChar, lastChar));
            } else { // If there was no cookie of that name, return false.
                return false;
            }
    }       
}

if (document.cookie.indexOf('globeinvestor_uid') != -1)
{var pi_session_id = WM_readCookie('globeinvestor_uid').split('FC/').join('')}
