$(document).ready(function() {
	
	/********************************************
	  Background Image Init
	********************************************/
	
	$('#bg img').one('load', function() {
		img_width  = $('#bg img').innerWidth();
		img_height = $('#bg img').height();
		win_width  = $(window).width();
		win_height = $(window).height();
	
		adjust_bg_size(); // Resize background image
		adjust_content_size(); // Resize content area
		
		$(window).resize(function() {
			win_width  = $(window).width();
			win_height = $(window).height();
			
			adjust_bg_size(); // Resize background image
			adjust_content_size(); // Resize content area
		})
	}).each(function() {
		if(this.complete)
			$(this).load();
	});
	
	$('.content_close').live('click', function() {
		hide_content();
	});
	
	/********************************************
	  Hashbang URL Mapping
	********************************************/
	
	// Grab all internal links when clicked, format them to use hashbang URL's
	$('a[target!="_blank"]').live('click', function(e) {
	    var href = $(this).attr('href').replace(site_url, ''); // Remove the site URL from link
	    
	    if(href[0] == '/') // Ensure link is infact internal
	    {
	        e.preventDefault();
	        window.location.hash = '#!' + href; // Change URL accordingly
	    }
	});
	
	$('#nav > ul > li > a').click(function() {
		if($(this).parent().hasClass('active'))
		{
			open_nav($(this).parent(), function() {
				hide_content();
				window.location.hash = '#!/home';
			});
		}
	});
	
	// Enable monitoring of the hashbangs
	Path.map('#!(/:page1/)(:page2/)(:page3/)(:page4/)').to(function() {
	    var page1 = this.params['page1'];
	    var page2 = this.params['page2'];
	    var page3 = this.params['page3'];
	    var page4 = this.params['page4'];
	    var path  = '/' + page1 + '/';
	    var p_path = path;
	    
	    // Create path URL based on parameters passed
	    if(page2 != undefined)
	    	path += page2 + '/';
	    	
	    if(page3 != undefined)
	    	path += page3 + '/';
	    	
	    if(page4 != undefined)
	    	path += page4 + '/';

	   	// Create parent URL path (max 2)
	   	if(page2 != undefined)
	    	p_path += page2 + '/';

	  	// Load page data
		$.get(site_url + path, function(data) {
			not_first_load = $('body').hasClass('page_loaded'); // Detect if this is the first page load
			
			if(data.type == 'parent' && data.data != null) // Check if its a parent page and data is loaded
			{
				open_nav($('#nav > ul > li > a[href="' + site_url + '/' + page1 + '/' + '"]'), function() { // Open sub-nav
					set_bg_img(data.data);
				}); // Set backround image
			}
			else if(data.type == 'child' && data.data != null) // Check if its a child page and data is loaded
			{
				if(!not_first_load) // If this is the first page and its a subpage, we need the parent background image
				{
					var parent = $('#nav a[href="' + site_url + p_path + '"]').parents('li:eq(1)').find('a:first');
					
					$.get(parent.attr('href'), function(p_data) { // AJAX call to get background image
						if(p_data.type == 'parent' && p_data.data != null)
						{
							open_nav(parent, function() {
								set_bg_img(p_data.data, function() {
									show_content(function() {  // Show content
										set_content(data.data); // Set content
										set_content_class(data.special); // Set content div class
									});
								}); // Set background image
							}); // Open sub-nav
						}
					}, 'json');
				}
				else
				{
					show_content(function() {  // Show content
						set_content(data.data); // Set content
						set_content_class(data.special); // Set content div class
					});
				}
			}
			else if(data.type = 'modal' && data.data != null)
			{
				$.fn.colorbox({
					'open': true,
					'html': data.data,
					'width': '600px',
					'height': '400px',
					'opacity': 0.5
				});
			}
			
			$('body').addClass('page_loaded'); // Add class to detect if page has been loaded yet
		}, 'json');
	});

	Path.root('#!/home');
	Path.listen();

	/********************************************
 	 Contact Form
	********************************************/

	$('form[name="contact"]').live('submit', function() {
		var error = false;
		$('form .error').hide();

		if($('input[name="name"]').val() == '')
		{
			$('form .error').text('Name is a require field');
			error = true;
		}
		else if($('input[name="email"]').val() == '')
		{
			$('form .error').text('Email is a require field');
			error = true;
		}
		else if($('textarea[name="message"]').val() == '')
		{
			$('form .error').text('Message is a require field');
			error = true;
		}

		if(!error)
		{
			$.post('/tao/?cf=1', $('form[name="contact"]').serialize(), function(data) {
				$('form[name="contact"]').fadeOut(300, function() {
					$('.contact_thankyou').fadeIn(300);
				});
			});
		}
		else
		{
			$('form .error').show();
		}
		return false;
	});
});

/********************************************
  Background Image Functions
********************************************/

var img_width;
var img_height;
var win_width;
var win_height;

function adjust_bg_size()
{	
	$('#bg').css('width', win_width + 'px');
	$('#bg').css('height', win_height + 'px');
	
	ratio = img_height / img_width; // Figure out image ratio

	new_height = ratio * win_width;
	new_width  = win_width;
	
	
	if(new_height < win_height) // Make sure image is not smaller then viewing area, recalc image size if needed
	{
		ratio = img_width / img_height;
		
		new_height = win_height
		new_width  = ratio * win_height
	}
	
	$('#bg img').css('height', new_height + 'px'); // Set image dimentions on image
	$('#bg img').css('width', new_width + 'px');
}

function set_bg_img(image, callback)
{
	var img_style = $('#bg img').attr('style');
	var new_img = $('<img />');  // Clone current image, make changes to that
	
	new_img.attr('src', image).attr('style', img_style);
	new_img.load(function() {
		$(this).prependTo('#bg');
		
		$('#bg img:eq(1)').fadeOut(600, function() { // Fade out current image
		$('#bg img:eq(1)').remove(); // Remove current image
		
		if(callback != null)
				callback();
		});	
	});
}

/********************************************
  Navigation Functions
********************************************/

function open_nav(nav_item, callback)
{
	current_menu_item_id = $('#nav > ul > li.active').attr('id');
	new_menu_item_id     = $(nav_item).parent().attr('id');

	hide_content();
	
	// Close any existing menus, open selected menu
	if($(nav_item).parent().find('ul.sub-menu:visible').length > 0) // Current menu item is open
	{
		$('#nav ul li.active').removeClass('active');
		
		$('#nav ul li ul.sub-menu:visible').slideUp(300, function() {
			if(callback != null)
				callback();
		});
	}
	else if($('#nav ul li ul.sub-menu:visible').length > 0) // Opening current menu item while one is open
	{	
		$('#nav ul li ul.sub-menu:visible').slideUp(300, function() {
			$(nav_item).parent().find('ul.sub-menu').slideDown(300, function() {
				if(callback != null)
					callback();
			});
			$('#nav > ul > li.active').removeClass('active'); // Remove active state from current item
			$(nav_item).parent().addClass('active'); // Add active class to new item
		});
	}
	else // Opening current menu item no menu open
	{
		$(nav_item).parent().find('ul.sub-menu').slideDown(300, function() {
			if(callback != null)
				callback();
		});
		$(nav_item).parent().addClass('active'); // Add active class to new item
	}
}

/********************************************
  Content Functions
********************************************/

function adjust_content_size()
{
	var content_div  = $('#content');
	var inner_height = content_div.innerHeight();
	var outer_height = content_div.height();
	var padding      = inner_height - outer_height;
	var margin_top   = content_div.css('top');
	margin_top       = parseInt(margin_top.substring(0, margin_top.length - 2));
	
	content_div.attr('data-margin-top', '20px');

	if((win_height - padding - margin_top) < outer_height)
		content_div.height((win_height - padding - margin_top) + 'px');
	else
		content_div.css('height', 'auto');

	$('#site').height(win_height + 'px');
}

function set_content(content, callback)
{	
	var content_div = $('#content');

	content_div.html(content);
	content_div.prepend('<div class="content_close">X</div>');

	if(callback != null) // Check if callback function is set, run if needed
			callback();
}

function set_content_class(new_class)
{	
	if(new_class != null && new_class != undefined)
	{
		$('#content').attr('class', 'special_' + new_class);
	}
	else
	{
		$('#content').removeAttr('class');
	}
}

function show_content(callback)
{	
	
	hide_content(function() {
		if(callback != null) // Check if callback function is set, run if needed
			callback();
		
		var content_div = $('#content');
		var margin_top  = content_div.attr('data-margin-top');

		content_div.removeAttr('style'); // Remove stles for proper calulations
		content_div.css('top', win_height + 'px').show(); // Place the content window below the visible viewing area, then show it		
		
		var inner_height = content_div.innerHeight();
		var outer_height = content_div.height();
		var padding      = inner_height - outer_height;
		var con_top      = parseInt(content_div.attr('data-margin-top'));

		if((outer_height + con_top) < win_height) // Level height
			content_div.height((win_height - padding - con_top) + 'px');

		setTimeout(function() {
			var content_div = $('#content');
			var margin_top  = content_div.attr('data-margin-top');

			content_div.removeAttr('style'); // Remove stles for proper calulations
			content_div.show(); // Place the content window below the visible viewing area, then show it		
			
			var inner_height = content_div.innerHeight();
			var outer_height = content_div.height();
			var padding      = inner_height - outer_height;
			var con_top      = parseInt(content_div.attr('data-margin-top'));

			if((outer_height + con_top) < win_height) // Level height
				content_div.height((win_height - padding - con_top) + 'px');
		}, 100)
		
		content_div.animate({ // Animate the content window
			'top' : margin_top
		}, 600, function() {
			$('#site').height(win_height + 'px');
			$('#container').css('overflow', 'visible');
		});
	});
}

function hide_content(callback)
{
	if($('#content:visible').length == 1)
	{
		$('#site').height('100%');
		$('#container').css('overflow', 'hidden');
		
		$('#content').animate({ // Animate the content window
			'top' : win_height
		}, 600, function() {
			$('#content').hide();
			
			if(callback != null) // Check if callback function is set, run if needed
				callback();
		});
	}
	else
	{
		if(callback != null) // Check if callback function is set, run if needed
			callback();
	}
}
