var Site = {
	// Chart trackers
	charts: {},
	chartData: {},
	chartTimeouts: {},
	chartDefault: 'ASXSP200',
	accordion: '',
	
	start: function(){
		
		//alert(Site.accordionX);
		
		// Launch-in-new-window links automagically created
		var extLinks = $$('a.external');
		if ( extLinks.length ) {
			extLinks.each(function(elem, idx) { 
				elem.setProperty('target', '_blank');
			});
		}
		
		// Safari Suckerfish 'fix'
		if ( navigator.appVersion.toLowerCase().indexOf('safari') != -1 ) {
			var navElems = $$('#navigation li a');
			navElems.each(function(elem, idx) {
				elem.set('title', '');
			});
		}
		
		
		// Form validation automagic
		var valForms = $$('form.validate-form');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) { 
				new Form.Validator.Inline(elem, {
					onFormValidate: Site.formHandler,
					useTitles: true,
					'errorPrefix':		''
				});
			});
		}
		
		// YouTube url re-write
		var youtubeLinks = $$('a.youtube');
		if ( youtubeLinks.length ) {
			youtubeLinks.each(function(elem, idx) { 
				elem.setProperty('href', elem.getProperty('href').replace(new RegExp("watch\\?v=", "i"), 'v/'));
			});
		}
		
		// Add Accordions
		Site.attachAccordions();		
		
		// Add Tabions
		Site.attachTabions();		
		
		// Add Overtexts
		Site.attachOverTexts();
		
		// Add Shadowbox
		if ( !$('home') ) {
			Shadowbox.init({
				flashVars: { 
					image : '/images/player-placeholder.png',
					backcolor: 'FFFFFF',
					frontcolor : '007dc5',
					lightcolor : '222222',
					screencolor : 'FFFFFF'
				}
			});
		}
		
		if ( graph = $('market-graph') ) {
			Site.loadAsxFeedChart(Site.chartDefault);
		}
	},
	
	loadAsxFeedChart: function(market) {
		// Set the chart up
		Site.charts.asx = new google.visualization.LineChart(document.getElementById('market-graph'));
	    
	    // Do our initial request
		Site.requestAsxFeedData(market);
	},

	requestAsxFeedData: function(market) {
		new Request.JSON({
			'url':			'/',
			'method':		'get',
			'data':			{'graph': 'asx'},
			'noCache':		true,
			'onRequest':	function() {},
			'onComplete':	function() {},
			'onSuccess':	function(json, stringData) {
								Site.chartData.asx = json;
								Site.refreshAsxFeedData(market);
							},
			'onFailure':	function() {}
		}).send();
	},
	
	refreshAsxFeedData: function(market, delay) {
		// Cancel existing timeout, if any
		if ( Site.chartTimeouts.asx ) {
			clearTimeout(this.chartTimeouts.asx);
			Site.chartTimeouts.asc = 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 ( Site.chartData.asx[market] ) {
			var price_data = Site.chartData.asx[market].data;
			var text_every = 15;
			
			// Add the rows
			Object.each(price_data, function(item, idx) {
				data.addRow([item.date, parseFloat(Number.from(item.last).format({'decimal': '.', 'group': '', 'decimals': 2}))]);
			});
			
			// Draw the chart
	        this.charts.asx.draw(	data, 
				        			{	'width': 			$('market-graph').getCoordinates().x, 
				        				'height': 			$('market-graph').getCoordinates().y,
				        				'title':			Site.chartData.asx[market].name,
				        				'legend':			'none',
				        				'backgroundColor':	'#ffffff',
				        				'hAxis':			{	'showTextEvery':	text_every,
				        										'textStyle':		{	'color': '#222222'
				        															}
				        									},
				        				'vAxis':			{	'baselineColor':	'#222222',
				        										'gridlineColor':	'#dde0e2',
				        										'textStyle':		{	'color': '#222222'
				        															}
				        									},
				        				'series':			[	{	'color':		'#007dc5'
				        										}
				        									]
				        			});
		}
		
		// Now update the market list
		var container = $('market-list');
		var market_list = new Element('ul', {});
		container.empty();
		container.adopt(market_list);
		
		for ( var x = 0; x < 2; x++ ) {
			var li = new Element('li', {'class': 'header'});
			li.adopt(new Element('div', {'html': "&nbsp", 		'class': 'market-name'}));
			li.adopt(new Element('div', {'text': "Last",		'class': 'market-last'}));
			li.adopt(new Element('div', {'text': "Change",		'class': 'market-net-change'}));
			li.adopt(new Element('div', {'text': "%",			'class': 'market-pct-change'}));
											
			market_list.adopt(li);
		}
		
		Object.each(Site.chartData.asx, function(market_data, market_id) {
			var last_price = market_data.data[market_data.data.length - 1];
			
			var li = new Element('li');
			var market_div = new Element('div', {'text': market_data.name, 		'class': 'market-name'});
			market_div.set('market_id', market_id);
			market_div.addEvent('click', function() {
				Site.refreshAsxFeedData(this.get('market_id'));
			});
			
			var amnt_class = (parseFloat(last_price.netchange) > 0) ? 'increase' : 'decrease';
			
			li.adopt(market_div);
			li.adopt(new Element('div', {'text': Number.from(last_price.last).format({'decimal': '.', 'group': ',', 'decimals': 2}), 		
											'class': 'market-last'}));
			li.adopt(new Element('div', {'text': Number.from(last_price.netchange).format({'decimal': '.', 'group': ',', 'decimals': 2}), 	
											'class': 'market-net-change ' + amnt_class}));
			li.adopt(new Element('div', {'text': Number.from(last_price.pctchange).format({'decimal': '.', 'group': ',', 'decimals': 2}) + '%', 	
											'class': 'market-pct-change ' + amnt_class}));
			market_list.adopt(li);
		});
		
		delay = (delay) ? delay : 60000;
		
		this.chartTimeouts.asx = setTimeout(function() {	Site.requestAsxFeedData(market);	}, delay);
	},
	
	formHandler: function(pass, form, submitEvent) {
		// Do anything necessary here
	},
	
	attachAccordions: function() {
		var initial_display = -1;
		
		if ( accordion_id = window.location.toString().match(/\#.*/gi) ) {
			accordion_id = accordion_id.toString().replace(/#/gi, '');
			initial_display = Site.getAccordionNum(accordion_id);
		}
		
		// Add the actual accordion
		Site.accordion = new Fx.Accordion('.toggler', '.stretcher', {
			alwaysHide: true,
			display: initial_display,
			opacity: false,

			onActive: function(toggler, element){
				if ( toggler ) {
					toggler.addClass('toggler-active');
				}
			},
			onBackground: function(toggler, element){
				if ( toggler ) {
					toggler.removeClass('toggler-active');
				}
			}
		});
		
		
		// Need to add events to the footer to magically update the current
		// accordion since we're using same-page anchors
		var count = 0;
		var base_url = window.location.toString().replace(/\#.*/gi, '').replace(/http\:\/\/[^\/]+/, '');
		
		if( base_url != '/' ) {
			$$('#footer-inner > .grid-9 a').each(function(link, idx) {
				if ( link.get('href').match(base_url) ) {
					link.addEvent('click', function(e) {
						var id = link.get('href').toString().match(/\#.*/gi);
						id = id.toString().replace(/#/gi, '');
						Site.accordionX.display(Site.getAccordionNum(id));
						e.stop();
					});
				}
			});
		}
	},
	
	
	getAccordionNum: function(id) {
		var return_idx = -1;
		
		$$('.toggler').each(function(toggler, idx) {
			if ( toggler.get('id') == id ) {
				setTimeout(function() {
					new Fx.Scroll(window, {}).toElement($(id));
				}, 50);
				return_idx = idx;
			}
		});
		
		return return_idx;
	},
	
	openAccordion: function(id) {
		Site.accordion.display(Site.getAccordionNum(id));
	},
	
	attachTabions: function() {
		var tabs = $$('#tabs > span');
		var content = $$('#tab-contents > div');
		
		// Add events
		if ( tabs.length ) {
			// Add initial widths etc
			if ( content.length ) {
				content.each(function(item, idx) {
					// Measure the content items since they may be hidden
					var coords = item.measure(function() {	return this.getSize();	});
					
					// Store the dimensions so they can be transitioned later
					item.initialHeight = coords.y;
					item.initialWidth = coords.x;
					
					// Set our initial styles so the tabs are hidden
					item.setStyles({	'opacity': 0,
										'width': 0,
										'height': 0
									});
									
					// Add out content area FX
					item.fx = new Fx.Morph(item, {	'duration': 500,
													'transition': Fx.Transitions.Quad.easeOut,
													'link': 'cancel'
												});
				});
			}
			
			
			tabs.each(function(tab, idx) {
				// Add dummy headers to content for printing to work nicely
				var elem = new Element('h4', {'text': tab.get('text'), 'class': 'print-header'});
				elem.inject(content[idx], 'top');
				
				// Add click events to the tabs
				tab.addEvent('click', function(e) {
					var target_content = tab.get('id') + '-content';
					var target_content_elem = $(target_content);
					
					// Do the content transition hides
					content.each(function(content_pane, cidx) {
						if ( content_pane.get('id') != target_content ) {
							content_pane.fx.start({	'opacity': 0, 
													'height': 0, 
													'width': 0
												}).chain(function() {		content_pane.setStyle('display', 'none');	});
						}
					});
					
					// Show the one we actually want and transition it in
					target_content_elem.setStyle('display', 'block');
					target_content_elem.fx.start({	'opacity': 	1, 
													'height': 	target_content_elem.initialHeight,
													'width':	target_content_elem.initialWidth
												});
												
					// Update classes accordingly
					tabs.removeClass('active');
					this.addClass('active');
		
					// And the max height on the container
					$('tab-contents').fx.start({'height': target_content_elem.initialHeight});
				});
			});
			
			// Add the contents container FX
			$('tab-contents').fx = new Fx.Morph($('tab-contents'), {	'duration': 500,
																		'transition': Fx.Transitions.Quad.easeOut,
																		'link': 'cancel'
																	});
			
			// Set the positioning for the tabby thing content
			content.setStyles({'position': 'absolute', 'top': '0px', 'left': '0px'});
			
			
			// See if we've linked to a specific tab to show
			if ( tab_id = window.location.toString().match(/\#.*/gi) ) {
				tab_id = tab_id.toString().replace(/#/gi, '');
				$(tab_id).fireEvent('click');
			} else {
				// Show the first one by default
				tabs[0].fireEvent('click');
			}
		}
		
	},
	
	
	/**
	 *	Pre-emptive text for input fields
	 *
	 */
	attachOverTexts: function() {
		// We want to clear alt texts from values if the form is submitted
		var forms = $$('form');
		forms.each(function(elem, idx) { 
			elem.addEvent('submit', function() {
				if ( elem.getProperty('valPassed') == true ) {
					formElems = elem.getElements('input, textarea');
					
					formElems.each(function(input, idx) {
						if ( input.getProperty('alt') == input.value ) {
							input.value = '';
						}
					});
				}
			});
		});
		
		
		var overElems = $$('input.overtext, textarea.overtext');
		if ( overElems.length ) {
			overElems.each(function(elem, idx) {
				
				if ( elem.getProperty('type') ) {
					elem.setProperty('overType', elem.getProperty('type'));
				}
				
				if ( elem.getProperty('alt') ) {
					// Focus state
					elem.addEvent('focus', function() {
						if ( this.value == this.getProperty('alt')) {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'password', true);
							} else {
								this.value = '';
							}
							
							this.removeClass('overtext');
						}
					});
					
					// Blur state
					elem.addEvent('blur', function() {
						if ( this.value == '') {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'text');
								elem.value = elem.getProperty('alt');
							} else {
								this.value = this.getProperty('alt');
							}
							
							this.addClass('overtext');
						}
					});
					
					// Default state
					if ( elem.value == '') {
						if ( elem.getProperty('overType') == 'password' ) {
							elem = Site.cloneAndChangeInputType(elem, 'text');
						}
						
						elem.value = elem.getProperty('alt');
					} else {
						if ( elem.value != elem.getProperty('alt') ) {
							elem.removeClass('overtext');
						}
					}
				}
			});
		}
	}
	
};

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
			
// Do stuff on load
window.addEvent('domready', Site.start);
