// JavaScript Document


var headlinePanels = Array();
// headerPanel and params will be defined via the flash_header_module, but we must declare it here so as not to break the javascript.
var headerPanel = null;
var portalZone = null;
var crossDomain = null;
var headerPanelParams = null;
var hideLoginForm = null;
var headlinesPerPanel = 3;
var headlinePanelIndex = 0;
var timer;
var delay = 7000;
$(document).ready(function(){
	innitNews();
	embedFlashPanels();
	retrieveSpot();
	
	setupLoginLink();
	//analytics tracking for downloads
	$('a[href]').click(function(e)
	{
		href = $(this).attr('href');
		this_page = document.location.pathname;
		// first look for a download.
		filetypes = Array('.pdf','.doc','.xls','.docx','.xlsx');
		for(c=0;c<filetypes.length;c++)
		{
		   if (href.indexOf(filetypes[c]) !== -1)
		   {
			   if(href.indexOf('deliver.php') == -1)// protected downloads are tracked via the deliver.php script.
			   {   
					//e.preventDefault();
					//$('div#portalPanel').after('Download: '+href+'<br />');
					pageTracker._trackEvent("Publications", "Download", href);
					pageTracker._trackEvent("Publications", "Download Location", href+','+this_page);
					return;
			   }
			   else
			   {
					pageTracker._trackEvent("Publications", "Download Secure Location", href+','+this_page);
					return;
			   }
		   }
		}		
		
		// second look for external link
		if(href.indexOf('ttp://')!== -1)
		{
			//e.preventDefault();
			if(	
			   	href.indexOf('gold.org') !== -1 || 
				href.indexOf('utilisegold.com') !== -1 || 
				href.indexOf('goldinspirations.com') !== -1 || 
				href.indexOf('goldinnovationsblog.com') !== -1 
				)
			{
				//$('div#portalPanel').after('Outgoing Portal Link: '+href+','+this_page+'<br />');
				pageTracker._trackEvent("Outgoing", "Portal", href+','+this_page);
		
			}
			else
			{
				//$('div#portalPanel').after('Outgoing Link: '+href+','+this_page+'<br />');
				pageTracker._trackEvent("Outgoing", "External", href+','+this_page);
			}
			return;
		}
		
	});	
	//analytics tracking for external referers.
	referredBy();	
});

function referredBy()
{
	//referral links will have #wgc_refer=some_value in the url
	if(document.location.hash)
	{
		temp = document.location.hash.substr(1,document.location.hash.length);
		if(temp.substr(0,9) == 'wgc_refer')
		{
			refer = temp.split('+');
			//alert(refer);
			if(refer[1].length)
			{
				//set a cookie with the refer value
				var date = new Date();
				days = 30;
				date.setTime(date.getTime()+(days*24*60*60*1000));				
				document.cookie = "wgc_refer="+refer[1]+"; expires="+date.toGMTString()+";domain=gold.org; path=/";
				//trigger a GA event
				if(typeof(pageTracker)!=='undefined')
				{
					pageTracker._trackEvent('Referred By ['+refer[1]+']', 'Incoming Link ['+refer[1]+']', document.location.href);
				}
			}
		}
	}
	// so we need to read the wgc_refer cookie and trigger a GA events with its value if it exists.
	var nameEQ = "wgc_refer=";
	var ca = document.cookie.split(';');
	var val = null;
	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) val = c.substring(nameEQ.length,c.length);
	}		
	// ...just confirmed our email address.
	if (val != null && (document.location.href.indexOf('user/normal/activated') !== -1))
	{
		if(typeof(pageTracker)!=='undefined')
		{
			pageTracker._trackEvent('Referred By ['+refer[1]+']', 'User Registration Complete ['+refer[1]+']', document.location.href);
		}
	}		
	// ...just compeleted the reg form.
	if (val != null && (document.location.href.indexOf('user/normal/register/thanks') !== -1))
	{
		if(typeof(pageTracker)!=='undefined')
		{
			pageTracker._trackEvent('Referred By ['+refer[1]+']', 'User Registration Attempt ['+refer[1]+']', document.location.href);
		}
	}
}



function innitNews(){
	//get the news
	$.get("/news/xml/", function(xmlDataSet) {
	// format and output result
	headlines = $("headlines", xmlDataSet).children();
	i=0;
	for(c=0;c<headlines.length;c++){
		if(i==0){
			str = '<ul>';
		}
		str += '<li><a href="'+$(headlines[c]).attr("url")+'">'+$(headlines[c]).text()+'</a></li>';
		i++;
		if(i==headlinesPerPanel){
			str += '</ul>';
			headlinePanels[headlinePanels.length] = str;
			i=0;
		}
	}
	$("#latestnewsScroller").html(headlinePanels[headlinePanelIndex]);
	headlinePanelIndex++;
	timer=setTimeout("animOut()",delay);
	});	
}
function animOut(){
	$("#latestnewsScroller").slideUp("slow",animIn); 
}
function animIn(){
	$("#latestnewsScroller").html(headlinePanels[headlinePanelIndex]);
	$("#latestnewsScroller").slideDown("slow",delayTimer); 
}
function delayTimer(){
	if(headlinePanelIndex == (headlinePanels.length-1)){
		headlinePanelIndex=0;
	}else{
		headlinePanelIndex++;
	}
	timer=setTimeout("animOut()",delay);
}
function embedFlashPanels(){
	if(hostZone == '/'){
		hostZone == '';
	}	
	//first of all embed the portal panel: po
   	var po = new SWFObject("http://www.gold.org"+hostZone+"/common/swf/portal.swf", "portalswf", "100%", "60", "6", "#ffffff");
	if(portalZone != null){ // has portalZone been defined by the module?
		po.addVariable('portalZone', portalZone);
		po.addVariable('hostZone', hostZone);
	}
	po.addParam('allowScriptAccess','always');
	po.addParam("wmode", "opaque");
  	po.write("portalPanel");

	//now embed the header panel: ho
	if($("#headerBox").length){ // has headerPanel been defined by the module? do we have a div to put content into?
		$("#headerBox").show();
   		thisHeight = $("#headerBox").height();
        //only load this one locally.
		nocache = "/common/swf/"+headerPanel;//+'?'+Math.random();
   		var ho = new SWFObject(nocache, "headerswf", "100%", thisHeight, "6", "#ffffff");
		if(headerPanelParams != null){ // has headerPanelParams been defined by the module?
			for(c=0;c<headerPanelParams.length;c++){
				ho.addVariable(headerPanelParams[c][0], headerPanelParams[c][1]); 
			}
		}
		ho.addParam('allowScriptAccess','always');
		ho.addParam("wmode", "opaque");
   		ho.write("headerBox");   
	}
}
function blackenFlashPanels(){
	//alert('hello');
   	thisHeight = $("#headerBox").height();
	$("#headerBox").html('<div style="background-color:#000000;height:'+thisHeight+'px"></div>');
}
function unBlackenFlashPanels(){
	//alert('hello');
	 embedFlashPanels();
}
function retrieveSpot(){
	$.get("/spotprice/", function(xmlDataSet) {
		var valid = $('valid', xmlDataSet).text();	
		if(valid == 1)
		{
		
			var bid =  $('bid', xmlDataSet).text();
			var ask =  $('ask', xmlDataSet).text();
			var diff =  $('diff', xmlDataSet).text();
			var gmt =  $('gmt', xmlDataSet).text();
			var suffix =  $('date_suffix', xmlDataSet).text();
			$("#priceBid").html(' $' + bid);
			$("#priceAsk").html(' $' + ask);
			$("#priceUpdate").html(' ' + gmt + ' ' + suffix);
		}
		else
		{
			$("#priceBid").html(' awaited ');
			$("#priceAsk").html(' awaited ');
		}
	});
	setTimeout(retrieveSpot,60000);
}
function toggle_pr(obj){
	$('#'+obj).toggle()
}
function setupLoginLink(){
	if(hideLoginForm == true){ // loginForm is shown by default in css, this var is false on a login error
		$("#portalLoginForm").toggle();
	}
	$("#portalloginlink").click(function(){
   		$("#portalLoginForm").toggle();
   		return false;
 	});

}

function toggleAdvanced() {
	$("#advancedArea").toggle();
}
