// WGC ajax spot price control
// a method to retrieve the latest spot price every minute
// and also to change the currenct displayed.
// Author: HdotNET@cfp



$(document).ready(function() {

	spotpricetools = new WGC_spotpricetools('spotpricetools');
	spotpricetools.innit();

});

function WGC_spotpricetools()
{
	this.current_currency_code = 'usd';
	this.interval = 60000;
	this.timer = '';
	this.objName = '';
	this.currency_menu_status = 'hidden';
	this.cookie_name = 'wgc_currency_pref';
	this.innit = function(objName)
	{
		this.debug('innit');
		this.objName = objName;
		var _self = this;
		// add events to show/ide the currency menu
		$('a#spotpriceChangeCurrency').click(
		function(event)
		{
			event.preventDefault();	
			_self.show_currency_menu();
		});	
		$('#spotpriceCurrencies').mouseleave(
		function(event)
		{
			_self.hide_currency_menu();
		});
		$('#spotpriceCurrencies').click(
		function(event)
		{
			event.preventDefault();	
			_self.click_currency($(event.target).attr('rel'));
		});		
		
		
		var selected_currency = this.read_cookie();
		if(selected_currency != null)
		{
			this.debug('selected currency '+selected_currency);
			this.click_currency(selected_currency);
		}
		else
		{
			this.debug('no currency cookie');
			this.get_price();
		}
		
	}
	this.click_currency = function(code)
	{
		this.debug('changing currency '+code);
		this.create_cookie(code,14);
		this.current_currency_code = code;
		this.get_price();
		this.show_loading();	
		this.hide_currency_menu();	
	}
	this.get_price = function()
	{
		clearTimeout(this.timer);
		var _self = this;
		this.debug('getting spot price data');
		//use post so the data isnt cached
		var d = new Date();
		var mins = d.getMinutes();
		$.get('/feeds/xml/spot/'+mins+'/',
		function(xmldata)
		{
			_self.process_xml_data(xmldata);
		});
	}
	this.process_xml_data = function(data)
	{
		this.debug('spot price data received');
		
		currency = this.current_currency_code.toUpperCase();
		
		var bid = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] bid').text();
		var mid = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] mid').text();
		var ask = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] ask').text();
		
			
		var _self = this;
		/*
		if(this.check_values([bid,mid,ask]))
		{
			this.debug('Errors in XML values, doing nothing');
			this.timer = setTimeout(function(){_self.get_price()},this.interval);
			return;	
		}
		GAH
		*/
		
		var bid_performance = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] bid').attr('performance');
		var mid_performance = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] mid').attr('performance');
		var ask_performance = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"] ask').attr('performance');
		var currency_symbol = $(data).find('prices item[name="Gold Spot Price"] currency[code="'+currency+'"]').attr('symbol');
		
		var timestamp = $(data).find('prices item[name="Gold Spot Price"] timestamp').text();
		
		
		$('#spotpriceCellBid').text(bid);
		$('#spotpriceCellMid').text(mid);
		$('#spotpriceCellAsk').text(ask);
		$('#spotpriceTools .currency').text(currency_symbol);
		$('#spotpriceTimestamp').text(this.format_datetime(timestamp));
		
		this.reset_performance_class('#spotpriceArrowBid');
		this.reset_performance_class('#spotpriceArrowMid');
		this.reset_performance_class('#spotpriceArrowAsk');
		
		this.set_performance_class(mid_performance,'#spotpriceArrowMid');
		this.set_performance_class(bid_performance,'#spotpriceArrowBid');
		this.set_performance_class(ask_performance,'#spotpriceArrowAsk');
		
		this.hide_loading();
		this.timer = setTimeout(function(){_self.get_price()},this.interval);
		
	}
	this.check_values = function(arr)
	{
		var errd = false;
		this.debug(arr.length);	
		for(c=0;c<arr.length;c++)
		{
			var val = arr[c];

			if(isNaN(val))
			{
				this.debug('Error val '+arr[c]);
				errd = true;	
			}
		}
		return errd;
	}
	this.reset_performance_class = function(ele)
	{
		$(ele).removeClass('arrow');
		$(ele).removeClass('up');
		$(ele).removeClass('down');
		$(ele).removeClass('middle');
	}
	this.set_performance_class = function(value,ele)
	{
		value = parseInt(value);
		if(value === -1)
		{
			$(ele).addClass('arrow');	
			$(ele).addClass('down');	
		}
		else if(value === 0)
		{
			$(ele).addClass('arrow');	
			$(ele).addClass('middle');	
		}
		else if(value === 1)
		{
			$(ele).addClass('arrow');	
			$(ele).addClass('up');	
		}
	}
	this.show_loading = function()
	{
		$('#spotpriceLoading').show();
		$('#spotpriceTable').hide();	
	}
	this.hide_loading = function()
	{
		$('#spotpriceLoading').hide();
		$('#spotpriceTable').show();	
	}
	this.show_currency_menu = function()
	{
		
		this.currency_menu_status = 'shown';
		$('#spotpriceCurrencies').show();
		clearTimeout(this.timer);
	}
	this.hide_currency_menu = function()
	{
		if(this.currency_menu_status == 'hidden')
		{
			return;	
		}
		this.currency_menu_status = 'hidden';
		$('#spotpriceCurrencies').hide();
		this.debug('hiding menu');
		var _self = this;
		this.timer = setTimeout(function(){_self.get_price()},this.interval);
	}
	this.read_cookie = function() {
		var nameEQ = this.cookie_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;
	}
	this.erase_cookie = function() {
		this.create_cookie("",-1);
	}
	this.create_cookie = function(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 = "";
		document.cookie = this.cookie_name+"="+value+expires+"; path=/";
	}	
	this.format_datetime = function(timestamp)
	{
		if(!timestamp)
		{
			return '';	
		}
		parts = timestamp.split(' ');
		if(!parts[1])
		{
			return '';	
		}
		date_parts = parts[0].split('-');
		time_parts = parts[1].split(':');
		return this.format_date(date_parts[0],date_parts[1],date_parts[2]) + ' at '+ time_parts[0] + ':' +time_parts[1];
	}
	this.format_date = function(yyyy,mm,dd)
	{
		mm = parseFloat(mm) -1; // in case it comes through wiht a leading zero, minus 1 because this is an array
		months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
		return dd+' '+months[mm];//+', '+yyyy;
	}		
	this.debug = function(msg)
	{
		debug('WGC_spotpricetools:: ' + msg);
	}
}
