/**
 * Creates a new function that, when called, itself calls this function in
 * the context of the provided this value, with a given sequence of arguments
 * preceding any provided when the new function was called.
 *
 * developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
 */
if(!Function.prototype.bind) {
	Function.prototype.bind = function(oThis) {
		// closest thing possible to the ECMAScript 5 internal IsCallable function
		if(typeof this !== "function") {
			throw new TypeError("Function.prototype.bind - what is trying to be fBound is not callable");
		}
		var aArgs = Array.prototype.slice.call(arguments, 1),
			fToBind = this,
			fNOP = function () {},
			fBound = function () {
				return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments)));
			};
		fNOP.prototype = this.prototype;
		fBound.prototype = new fNOP();
		return fBound;
	};
}

/**
 * Window logging function for pretty and safe logging calls
 *
 * usage: log('inside coolFunc', this, arguments);
 * paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
 */
window.log = function() {
	log.history = log.history || [];
	log.history.push(arguments);
	arguments.callee = arguments.callee.caller;
	if(this.console) {
		console.log(Array.prototype.slice.call(arguments));
	}
};

// Upgrade MSIE5.5-8 to be compatible with modern
// browsers. We're only going have this apply to
// MSIE7-8 though due to the IE6 chrome frame prompt
// http://code.google.com/p/ie7-js/
yepnope({
	load:'ielt9!http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js',
	callback:function(url,result,key){if(!window.IE7) yepnope(dir+'/js/ie9.js');}
});

// A fast & lightweight polyfill for min/max-width
// CSS3 Media Queries (for IE 6-8, and more)
// Visit j.mp/respondjs for project information
/*
yepnope({
	load:dir+'/js/respond.js'
});
*/

if(ga) {
	// More consistent way of loading the google analytics
	// tracking code but please be sure to change the above
	// @ga var to the correct site ID
	window._gaq=[['_setAccount',ga],['_trackPageview'],['_trackPageLoadTime']];
	yepnope({
		load:('https:'==location.protocol?'https://ssl':'http://www')+'.google-analytics.com/ga.js'
	});
}

// Prompt IE 6 users to install Chrome Frame.
yepnope({
	load:'ielt7!http://ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js',
	callback:function(url,result,key){CFInstall.check({mode:'overlay'});}
});


// Grab Google CDN's jQuery, with a protocol relative
// URL; fall back to local if necessary
// The plugin files will start downloading as soon as
// the line is executed, but if the jQuery CDN was down
// it won't be executed until after the local version
// was loaded.
yepnope([{
	load:'http://ajax.googleapis.com/ajax/libs/jquery/'+ (window.jqv ? window.jqv : '1.6.2') +'/jquery.min.js',
	callback:function(url,result,key){
		if(!window.jQuery){
			//if(console.log) console.log('jQuery CDN wasn\'t loaded successfully');
			yepnope({
				load: dir+'/js/jquery-1.6.2.js',
				callback:function(){
					if(log) log('jQuery library was loaded from local');
				}
			});
		} else {
			if(log) log('jQuery CDN was loaded');
		}
	}
}, {
	load:dir+'/js/plugins-jquery.js',
	complete: function() {
		if(log) log('Default jQuery plugins were successfully loaded... Begin loading user defined scripts');
	

/**
 * All of this project's meat scripts are loaded via the yepnope javascript
 * library. This script file contains a common procedure for loading all other
 * required plugins (including those specified within the main page template
 * and the common jQuery plugins used to make life easy.
 *
 * All code processes herein are licenced soley to Click Creative copyright
 * 2011 to author Matthew Kingston <matthewkingston@me.com>
 */

 /* ==|== primary scripts =====================================================
   Author:
   Date: 
   ========================================================================== */

/* <-- INSERT YOUR PROJECT SCRIPT PROCESSES BELOW --> */


yepnope({
	load: 'http://j.maxmind.com/app/geoip.js',
	complete: function() {
		var state_id = geoip_region();
		var date = new Date();
		var time_hours = date.getHours();
		//var day_or_night = time_hours > 4 && time_hours < 18 ? 'day' : 'night';
		var day_or_night = 'day';
		var images = {
			
			// ACT
			'01': {
				day: dir+'/img/home-feature-canberra-day.jpg'
			},
			
			// New South Wales
			'02': {
				day: dir+'/img/home-feature-sydney-day.jpg'
			},
			
			// Northern Territory
			'03': {
				day: dir+'/img/home-feature-darwin-day.jpg'
			},
			
			// Queensland
			'04': {
				day: dir+'/img/home-feature-brisbane-day.jpg'
			},
			
			// South Australia
			'05': {
				day: dir+'/img/home-feature-adelaide-day.jpg'
			},
			
			// Tasmania
			'06': {
				day: dir+'/img/home-feature-hobart-day.jpg'
			},
			
			// Victoria
			'07': {
				day: dir+'/img/home-feature-melbourne-day-1.jpg'
			},
			
			// Western Australia
			'08': {
				day: dir+'/img/home-feature-perth-day.jpg'
			}
		};
		
		var src = images[state_id][day_or_night];
		
		$(function() {
			var container = $('#geo-background');
			var image = $('#geo-background-image');
			
			if(image.length > 0)
			{
				function resize_feature_image() {
					var container_width = container.width();
					var container_height = container.height();
					
					var original_height = image.data('original_height') || 530;
					var original_width = image.data('original_width') || 1490;
					var ratio = original_height / original_width;
					
					//Resize image to proper ratio
					if((container_height / container_width) > ratio) {
						image.height(container_height);
						image.width(Math.ceil(container_height / ratio));
					} else {
						image.width(container_width);
						image.height(Math.ceil(container_width * ratio));
					}
					
					image.css('left', Math.ceil((container_width - image.width()) / 2));
					image.css('top', Math.ceil((container_height - image.height()) / 2));
				}
				
				if(src)
				{
					image.attr('src', src);
				}
				
				if(image[0].width == 0 || image[0].height == 0)
				{
					image.bind('load', function() {
						var image_element = $(this)[0];
						image.data('original_height', image_element.height);
						image.data('original_width', image_element.width);
						resize_feature_image();
						$(window).resize(resize_feature_image);
						image.fadeIn('fast');
					});
					
					image.attr('src', src);
				}
				else
				{
					image.hide();
					image.data('original_height', image[0].height);
					image.data('original_width', image[0].width);
					resize_feature_image();
					$(window).resize(resize_feature_image);
					image.fadeIn('fast');
				}
				
			}
		});
	}
});



/*
$(function() {
	$('#geo-background-image').css('display', 'inline');
});
*/



$(function() {
	
	var real_active_page = $('.header-navigation-link.active');
	var real_section_page = $('.header-navigation-link.section');
	
	var active_url_segment = null;
	var timer = null;
	
	var pri_nav_elements = $('.header-navigation-link.has-children');
	var sub_nav_elements = $('.header-sub-navigation-panel');
	
	sub_nav_elements.hide();
	
	pri_nav_elements.each(function() {
		$(this).data('url_segment', $(this).attr('id').match(/header-navigation-([\w-]+)/)[1]);
	});
	
	sub_nav_elements.each(function() {
		$(this).data('url_segment', $(this).attr('id').match(/header-sub-navigation-([\w-]+)/)[1]);
	});
	
	
	function show_sub_nav() {
		
		real_active_page.removeClass('active');
		real_section_page.removeClass('section');
		
		var active_pri_nav_item = pri_nav_elements.filter(function() {
			return $(this).data('url_segment') == active_url_segment;
		});
		
		if(active_pri_nav_item.length) {
			active_pri_nav_item.addClass('hover');
		}
		
		var active_sub_nav_item = sub_nav_elements.filter(function() {
			return $(this).data('url_segment') == active_url_segment;
		});
		
		if(active_sub_nav_item.length) {
			active_sub_nav_item.show();
			
			if($.browser.msie)
				$('object').addClass('visuallyhidden');
		}
	}
	
	function hide_sub_nav(immediately) {
		
		var active_pri_nav_item = pri_nav_elements.filter(function() {
			return $(this).data('url_segment') == active_url_segment;
		});
		
		var active_sub_nav_item = sub_nav_elements.filter(function() {
			return $(this).data('url_segment') == active_url_segment;
		});
		
		if(immediately) {
			clearTimeout(timer);
			active_sub_nav_item.hide();
			active_pri_nav_item.removeClass('hover');
			
			real_active_page.addClass('active');
			real_section_page.addClass('section');
			
			if($.browser.msie)
				$('object').removeClass('visuallyhidden');
		} else {
			timer = setTimeout(function() {
				active_sub_nav_item.hide();
				active_pri_nav_item.removeClass('hover');
				
				real_active_page.addClass('active');
				real_section_page.addClass('section');
				
				if($.browser.msie)
					$('object').removeClass('visuallyhidden');
			}, 100);
		}
	}
	
	pri_nav_elements.mouseenter(function() {
		if(active_url_segment !== null && $(this).data('url_segment') != active_url_segment) {
			hide_sub_nav(true); // Immediately
		}
		
		active_url_segment = $(this).data('url_segment');
		setTimeout(function() { clearTimeout(timer); }, 20);
		show_sub_nav();
	});
	
	pri_nav_elements.mouseleave(function() {
		hide_sub_nav();
	});
	
	
	sub_nav_elements.mouseenter(function() {
		if(active_url_segment == $(this).data('url_segment')) {
			setTimeout(function() { clearTimeout(timer); }, 20);
		}
	});
	
	sub_nav_elements.mouseleave(function() {
		hide_sub_nav();
	});
	
	
	$('#print-page').click(function() {
		window.print();
	});
	
	
});

yepnope({
	load: dir+'/js/plugins/hintr.js',
	complete: function() {
		$('input[type=text]').hintr();
	}
});

yepnope({
	load: [
		dir+'/js/formalize/formalize.js',
		dir+'/js/formalize/css/formalize.css'
	],
	complete: function() {
	}
});


yepnope({
	load: [
		dir+'/js/jqtransform/jqtransform.js',
		dir+'/js/jqtransform/jqtransform.css'
	],
	complete: function() {
		$('#header-action form').jqTransform();
		$('#header-action').hide().removeClass('invisible').fadeIn('fast');
	}
});



$(function() {
	
	
	$('#IRISPerformanceForm select').change(function(e) {
		
		var date = $(this).val();
		var url = window.location.pathname.replace(/\/$/, '') + '/showTable?date='+date;
		
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			success: function(data) {
				
				var html = $('<div>');
				
				for(i in data)
				{
					var header = $('<h2>'+i+'</h2>');
					var table = $('<table class="tabular"></table>');
					
					table.append($('<thead><tr>' +
							'<th>Name</th>' +
							'<th>Month (%)</th>' +
							'<th>3 Months (%)</th>' +
							'<th>6 Months (%)</th>' +
							'<th>1 Year pa (%)</th>' +
							'<th>3 Year pa (%)</th>' +
							'<th>5 Year pa (%)</th>' +
							'<th>FYTD (%)</th>' +
						'</tr></thead>'));
					
					for(j in data[i])
					{
						var name = data[i][j]['Name'];
						name = name.match(/benchmark/i) ? 'Benchmark' : name;
						
						var row = $('<tr>' +
							'<td>'+name+'</td>' +
							'<td>'+data[i][j]['Monthly']+'</td>' +
							'<td>'+data[i][j]['Quarterly']+'</td>' +
							'<td>'+data[i][j]['Biannually']+'</td>' +
							'<td>'+data[i][j]['Rolling1']+'</td>' +
							'<td>'+data[i][j]['Rolling3']+'</td>' +
							'<td>'+data[i][j]['Rolling5']+'</td>' +
							'<td>'+data[i][j]['Fytd']+'</td>' +
						'</tr>');
						
						row.appendTo(table);
					}
					
					header.appendTo(html);
					table.appendTo(html);
				}
				
				$('#IRISPerformanceTable').html(html.html());
				
			},
			error: function() {
				
				$('#IRISPerformanceTable').html('<strong>Sorry there was an error loading the data</strong>');
				
			}
		});
	});
	
	
	
	$('#IRISCreditRateForm select').change(function(e) {
		
		var date = $(this).val();
		var url = window.location.pathname.replace(/\/$/, '') + '/showTable?date='+date;
		
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			success: function(data) {
				var html = $('<div>');
				
				var table = $('<table class="tabular"></table>');
				
				table.append($('<thead><tr>' +
						'<th>Name</th>' +
						'<th>Earning Rate (%)</th>' +
					'</tr></thead>'
				));
				
				table.appendTo(html);
				
				
				for(i in data)
				{
					var name = data[i]['Name'];
					name = name.match(/benchmark/i) ? 'Benchmark' : name;
					
					var row = $('<tr>' +
						'<td>'+name+'</td>' +
						'<td>'+data[i]['CreditRate']+'</td>' +
					'</tr>');
					
					row.appendTo(table);
				}
				
				$('#IRISCreditRateTable').html(html.html());
			},
			error: function() {
				
				$('#IRISCreditRateTable').html('<strong>Sorry there was an error loading the data</strong>');
				
			}
		});
	});
	
	
	$('#MEIFPerformanceForm select').change(function(e) {
		
		var date = $(this).val();
		var url = window.location.pathname.replace(/\/$/, '') + '/showTable?date='+date;
		
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			success: function(data) {
				var html = $('<div>');
				
				var table = $('<table class="tabular"></table>');
				
				table.append($(
					'<thead><tr>' +
						'<th>Name</th>' +
						'<th>Month (%)</th>' +
						'<th>3 Months (%)</th>' +
						'<th>6 Months (%)</th>' +
						'<th>1 Year pa (%)</th>' +
						'<th>3 Year pa (%)</th>' +
						'<th>5 Year pa (%)</th>' +
						'<th>FYTD (%)</th>' +
					'</tr></thead>'
				));
				
				table.appendTo(html);
				
				for(i in data)
				{
					var name = data[i]['Name'];
					name = name.match(/benchmark/i) ? 'Benchmark' : name;
					
					var row = $(
						'<tr>' +
							'<td>'+name+'</td>' +
							'<td>'+data[i]['Monthly']+'</td>' +
							'<td>'+data[i]['Quarterly']+'</td>' +
							'<td>'+data[i]['Biannually']+'</td>' +
							'<td>'+data[i]['Rolling1']+'</td>' +
							'<td>'+data[i]['Rolling3']+'</td>' +
							'<td>'+data[i]['Rolling5']+'</td>' +
							'<td>'+data[i]['Fytd']+'</td>' +
						'</tr>'
					);
					
					row.appendTo(table);
				}
				
				$('#MEIFPerformanceTable').html(html.html());
			},
			error: function() {
				
				$('#MEIFPerformanceTable').html('<strong>Sorry there was an error loading the data</strong>');
				
			}
		});
		
		
		
		
	});
	
	
	$('#MEIFUnitPriceForm select').change(function(e) {
		
		var date = $(this).val();
		var url = window.location.pathname.replace(/\/$/, '') + '/showTable?date='+date;
		
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			success: function(data) {
				var html = $('<div>');
				
				var table = $('<table class="tabular"></table>');
				
				table.append($(
					'<thead><tr>' +
						'<th>Effective date</th>' +
						'<th>Name</th>' +
						'<th>Application price (you buy)</th>' +
						'<th>Redemption price (you sell)</th>' +
					'</tr></thead>'
				));
				
				table.appendTo(html);
				
				
				for(i in data)
				{
					var name = data[i]['Name'];
					name = name.match(/benchmark/i) ? 'Benchmark' : name;
					
					var row = $('<tr>' +
						'<td>'+date+'</td>' +
						'<td>'+name+'</td>' +
						'<td>'+data[i]['Buy']+'</td>' +
						'<td>'+data[i]['Sell']+'</td>' +
					'</tr>');
					
					row.appendTo(table);
				}
				
				$('#MEIFUnitPriceTable').html(html.html());
			},
			error: function() {
				
				$('#MEIFUnitPriceTable').html('<strong>Sorry there was an error loading the data</strong>');
				
			}
		});
	});
	
});


/**
 * Use cufon library and javascript canvas fonts
 * Uncomment and customise if needed
*/
/*
yepnope([
{
	load: dir+'/js/cufon/cufon-1.09i.js',
},
{
	load: dir+'/js/cufon/cufon-Arial.js',
	callback: function() {
		Cufon.replce('h1', {
			fontFamily: 'Arial'
		});
	}
}
]);



/** End user defined scripts **/
/* <!-- DO NOT CHANGE THE BELOW FUNCTION & OBJECT CLOSURES --> */

}
}]);

