
//var jQuery = jQuery;

// Used down below...
var ticker_animate = false;
var ticker = null;
var first_currency = null;
var first_currency_width = null;

jQuery(document).ready(function(jQuery) {
	
	if(jQuery.cookie('TEXT_SIZE')) {
		jQuery('body').addClass(jQuery.cookie('TEXT_SIZE'));	
	}
	
	jQuery('.controls .text a').click(function() {
		var textSize = jQuery(this).attr('class');
		if (jQuery('body').hasClass('large')) {
			jQuery('body').removeClass('large');
			jQuery.cookie('TEXT_SIZE', null, { path: '/', expires: 10000 });
		} else {
			jQuery('body').addClass(textSize)
			jQuery.cookie('TEXT_SIZE', textSize, { path: '/', expires: 10000 });
		}
		return false;
	});
	
	jQuery('.controls .print a').click(function() {
		window.print();
		return false;
	});
	
	if ( jQuery("#currency-group-form").length != 0 ) {
		jQuery("#currency-group-select").change(function() {
			jQuery("#currency-group-form").submit();
			return false;
		});
	}
	
	if ( jQuery("#future-exchange-form").length != 0 ) {
		jQuery("#future-exchange-select").change(function() {
			jQuery("#future-exchange-form").submit();
			return false;
		});
	}
	
	if ( jQuery("#delete-coin").length != 0 ) {
		jQuery("#delete-coin").click(function() {
			return confirm('Are you sure you want to delete this coin?');
		});
	}
	
	if ( jQuery("#delete-fix-rate").length != 0 ) {
		jQuery("#delete-fix-rate").click(function() {
			return confirm('Are you sure you want to delete this fix rate?');
		});
	}
	
	if ( jQuery("#metal-dashboard-container").length != 0 && jQuery("#metal-price-dashboard").length != 0 ) {
		refreshSectionData(jQuery("#metal-dashboard-container"), window.location, {'ajax':true});
	}
	
	if ( jQuery("#spot-rates-home-container").length != 0 && jQuery("#spot-price-home").length != 0  ) {
		refreshSectionData(jQuery("#spot-rates-home-container"), '/', {'spot':true});
	}
	
	if ( jQuery("#coins-home-container").length != 0 && jQuery("#coins-home").length != 0  ) {
		refreshSectionData(jQuery("#coins-home-container"), '/', {'coins':true});
	}
		
	jQuery('.external').attr('target','_blank');

	Shadowbox.init();
	
	function initFeature() {

		jQuery("#feature-carousel").carouFredSel({
			auto: {
				fx: 'slide',
				delay			: 3000,
				pauseDuration	: 5000
			},
			circular: true,
			infinite: true,
			height: 357,
			items: {
				visible: 1,
				minimum: 1,
				width: 960,
				height: 357
			},
			padding: [0],
			pagination : {
				container       : "#feature-carousel-pagination",
				anchorBuilder   : function(nr) {
					return "<li><a href=\"#\">"+nr+"</a></li>";
				}
			},
			scroll: {
				pauseOnHover: true
			},
			width: 960
		});
		
	}
	
	function initTwitterFeature() {

		jQuery("#twitter-feed").carouFredSel({
			auto: {
				fx: 'slide',
				delay: 3000,
				pauseDuration: 5000
			},
			direction: 'up',
			circular: true,
			infinite: true,
			items: {
				visible: 5,
				minimum: 4
			},
			padding: [0],
			scroll: {
				items: 1,
				pauseOnHover: true
			}
		});
		
	}
	
	function initSubscribeSticky() {

		var element = jQuery('#subscribe'),
			stickyTop = element.css('top').replace("px","");

		jQuery(window).scroll(function() {
			
			var scrollTop = jQuery(window).scrollTop()
			
			if (scrollTop > stickyTop) {
				element.css('position','fixed');
				element.css('top',0);
			} else {
				element.css('position','absolute');
				element.css('top', stickyTop + "px");
			}
			
		});
		
	}
	
	if (jQuery("#feature-carousel").length != 0)
		initFeature();
	
	if (jQuery("#twitter-feed").length != 0)
		initTwitterFeature();
		
	if (jQuery("#subscribe").length != 0)
		initSubscribeSticky();
		
		
	// Add accordions
	var accordion_headers = jQuery('.accordion .header');

	accordion_headers.each(function(idx) {
		jQuery(this).click(function() {
			jQuery(this).next().toggle('slow');
			return false;
		});
		
		// Hide not-first-element
		if ( idx > 0 ) {
			jQuery(this).next().hide();
		}
	});
	
	
	// Add ticker functionality
	if ( jQuery('#ticker-inner').length != 0 ) {
		ticker = jQuery('#ticker-inner');
		setTimeout(function() {	animateTicker(jQuery); }, 50);
		
		jQuery('#ticker-inner').mouseenter(function() {
			ticker_animate = true;
		});
		
		jQuery('#ticker-inner').mouseleave(function() {
			ticker_animate = false;
		});
		
	}

	
	// Deal with gCharts
	
	if ( jQuery('#g-price-chart').length != 0 ) {
		google.setOnLoadCallback(loadHomepageChart);
		
		jQuery('#price-chart-filter span').click(function (){
			jQuery("#price-chart-filter span").removeClass('current');
			
			jQuery(this).addClass('current');
			jQuery('#price-chart-metal').val(jQuery(this).text());
			
		    // Re-request data
		    requestHomepageChartData();
		});
		
		jQuery('#price-chart-frequency').change(function () {
		    // Re-request data
		    requestHomepageChartData();
		});
	}
	
});



function animateTicker(jQuery) {
	// Don't do anything if we've got a mouseover event
	if ( !ticker_animate ) {
		var ticker_pos = parseInt(ticker.css('left'));
		
		// Current first currency element info
		if ( !first_currency ) {
			first_currency = jQuery(ticker.children('span')[0]);
			first_currency_width = first_currency.width() + 
									parseInt(first_currency.css('padding-left')) + 
									parseInt(first_currency.css('padding-right')) + 
									parseInt(first_currency.css('margin-left')) + 
									parseInt(first_currency.css('margin-right'));
		}
		
		// See if we need to move elements around
		if ( ticker_pos < (first_currency_width * -1) ) {
			first_currency.appendTo(ticker);
			ticker.css('left', (parseInt(ticker.css('left')) + first_currency_width) + 'px');
			first_currency = null;
		}
	
		// Animate the ticker
		ticker.css('left', (parseInt(ticker.css('left')) - 1) + 'px');
	}
	
	// Set the next timeout
	setTimeout(function() {	animateTicker(jQuery); }, 10);
}


function refreshSectionData(section, address, data, delay) {
	delay = (delay) ? delay : 60000;
	setTimeout(function() {	
		doAjaxRequest(	address,
					data,
					function(json) {
						section.html(json);
						refreshSectionData(section, address, data, delay);
					}
				);
		}, 
		delay
	);		
}




// Chart trackers
var chartTimeouts = {};
var charts = {};

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

function loadHomepageChart() {
	// Set the chart up
    charts.homepage = new google.visualization.LineChart(document.getElementById('g-price-chart'));
    
    // Do our initial request
	requestHomepageChartData();
				
				
}

function requestHomepageChartData() {
	doAjaxRequest(	'/',
					{'graph': true, 'metal': jQuery('#price-chart-metal').val(), 'period': jQuery('#price-chart-frequency').val()},
					function(json) {
						refreshHomepageChart(json)
					}
				);
}

function refreshHomepageChart(price_data, delay) {
	// Cancel existing timeout, if any
	if ( chartTimeouts.homepage ) {
		clearTimeout(chartTimeouts.homepage);
		chartTimeouts.homepage = null;
	}
	
	// Set the datatable up
	data = new google.visualization.DataTable();
	data.addColumn('string', 'Date');
	data.addColumn('number', 'Price');
	
	// If we had data returned, graph it
	if ( price_data ) {
		var text_every = Math.ceil(price_data.length / 5);
		
		// Add the rows
		jQuery(price_data).each(function(idx) {
			data.addRow([this.date, this.price]);
		});
		
		// Draw the chart
        charts.homepage.draw(	data, 
			        			{	'width': 			300, 
			        				'height': 			140,
			        				'legend':			'none',
			        				'backgroundColor':	'#fbfbfb',
			        				'hAxis':			{	'showTextEvery':	text_every,
			        										'textStyle':		{	'color': '#2b3372'
			        															}
			        									},
			        				'vAxis':			{	'baselineColor':	'#2b3372',
			        										'gridlineColor':	'#d4d7eb',
			        										'textStyle':		{	'color': '#2b3372'
			        															}
			        									},
			        				'series':			[	{	'color':		'#f15a29'
			        										}
			        									]
			        			});
	}
	
	delay = (delay) ? delay : 60000;
	
	chartTimeouts.homepage = setTimeout(function() {	requestHomepageChartData();	}, delay);
}





	
function doAjaxRequest(url, data, callback_success) {
	// Do the request
	jQuery.ajax({
			'url': url,
			'dataType': 'json',
			'data': data,
			'type': 'POST',
			'success': 	function(json) {
							callback_success(json);
						},
			'error': 	function(xhr, textStatus, eThrown) {
							// Do nothing
						}
		});
}

