/**
 * Used to add new page widgets to their assigned positions, and remove widgets
 * not assigned to the current page.
 * @param widgets array of positions containing arrays of widget data
 * @return null
 */
function refactorWidgets(widgets) {
	
	$('.widget-box').removeClass('retain');
	
	for (i=0;i<widgets.length;i++) { //Loop each container
		
		if (widgets[i].length > 1) {
			
			for (j=1;j<widgets[i].length;j++) { //Loop each element in each container
				
				if (
						$('#widget-'+widgets[i][j][0]).length == 1
						&&
						!$('#widget-'+widgets[i][j][0]).hasClass('static-box')
					) {
					
					$('#widget-'+widgets[i][j][0]).addClass('retain');
					
				} else if ($('#widget-'+widgets[i][j][0]).length == 0) {
					
					$('#'+widgets[i][0]).append(unescape(widgets[i][j][1]));
					
					$('#widget-'+widgets[i][j][0]).addClass('retain');
					
				} else if (
						$('#widget-'+widgets[i][j][0]).length == 1
						&&
						$('#widget-'+widgets[i][j][0]).hasClass('static-box')
					) {
					
					$('#widget-'+widgets[i][j][0]).addClass('retain');

				}
				
				// alert ('#widget-'+widgets[i][j][0]+' a[href^=/]:not(#admin-menu a,a[href^=/what-we-think],.static-box a)');
				
				//This causes overlap issues
				ajaxify('#widget-'+widgets[i][j][0]+' a[href^=/]:not(#admin-menu a,a[href^=/what-we-think],.static-box a,a.popup,a[href*=.])');
				
			}
			
		} 
		
	}

	$('#featured-projects').addClass('enabled');
	$("#featured-projects").tabs({fx:{opacity: "toggle", event: 'mouseover'}}).tabs("rotate", 10000, true);
	/*
	$(".contact:not(.static-box)").validate({
		debug: true,
		submitHandler: function(form) {
			form.submit();
	   	},
	   	errorClass: "invalid",
	   	rules: {
	   		name: {
	   			required: true,
	   			minlength: 3
	   		},
	   		num: {
	   			minlength: 6
	   		},
	   		mail: {
	   			required: true,
	   			email: true
	   		},
	   		when: "required",
	   		recaptcha_response_field: "required",
	   		message: "required"
	   	},
	   	messages: {
	   		name: {
	   			required: "You or your companies name",
	   			minlength: "Enter a longer name!"
	   		},
	   		num: {
	   			minlength: "That number isn't long enough"
	   		},
	   		mail: {
	   			required: "We need an e-mail address",
	   			email: "Enter a valid e-mail address"
	   		},
	   		when: "Choose a subject",
	   		recaptcha_response_field: "",
	   		message: "We need some details to go on"
	   	}
	});
	*/
	/* Hide all those elements which don't belong! */
	var allwidgets = $('.widget-box:not(.retain)');
	
	allwidgets.fadeTo(
		400,
		0,
		function() {
			$(this).remove();
		}
	);
	
	return true;

}

function ajaxify(target) {
	$(target).click(
		function () {
			$.ajax({
				type: "GET",
				url: unescape($(this).attr('href')),
				dataType: "json",
				beforeSend: function (xhr) {
					$('#load-indicator').fadeTo(400,1);
					$('#dom-target').fadeTo(
						400,
						0
					);
					
				},
				'success': function(i) {
					try {
						window.location.hash = i.location;
						document.title = i.meta.title;
						baseAliasToClass();
						$('.content-title span:last-child').text(i.title);
						$('#dom-target').html(unescape(i.content));
						
						try {
							
							if (pageTracker) {
								
								pageTracker._trackPageview(unescape(loc));
								
							}
							
							if (Recaptcha && $('#recaptcha_target').size() > 0) {
								Recaptcha.create(
									"6LdIiwMAAAAAAMyegWQECmDY5nf5giaX5pWFAOew",
									document.getElementById('recaptcha_target')
								);
							}
						
						} catch (e) { 
							
							$('#dom-target').prepend('<div class="error">You seem to be blocking external scripts, site functionality may be impaired</div>');
							
						}
						
						if ($('#project .tab').size() > 1) {
							$('#project').tabs({
								fx: { 
									opacity: 'toggle'
								}
							});
						}
						if (i.option.showtitle == 0) {
							
							$(".content-title:not(:hidden)").hide(
								'blind', 
								{direction: "vertical"},
								500
							);
							
						} else {
							
							$(".content-title:not(:visible)").show(
								'blind', 
								{direction: "vertical"},
								500
							);
								
						}
							
						$('#load-indicator').fadeTo(750,0);
						
						$('#dom-target').fadeTo(1000,1);
						
						$('#featured-projects-page').addClass('enabled');
						$("#featured-projects-page").tabs({
							fx:{
								opacity: "toggle",
								event: 'mouseover'
							}
						}).tabs("rotate", 5000, true);
						
						tb_init('#dom-target a.thickbox');
						
						refactorWidgets(i.widgets);
						
					} catch (e) {
						
					}
				},
				'error': function (xhr, textStatus, errorThrown) {
					$('#dom-target').fadeTo(1000,1);
					$('#load-indicator').fadeTo(750,0);
				}

			});
			return false;
		}
	);
}

function initMenu() {
	$('#vertical-accordion-1 ul').hide();
	$('#vertical-accordion-1 .a ul').show();
	$('#vertical-accordion-1 a:not(a[href^=/what-we-think])').click(
		function() {
			var checkElement = $(this).next();
			var optionClass  = $(this).attr('rel');
			var oldClass	 = $('#content-body').attr('class');
			var linkLocation = $(this).attr('href'); 
			var aniColour 	 = $(this).css("background-color");
			
			$('#load-indicator').fadeTo(400,1);
			
			return false;
			
		}
	);
	$('.popout-container .popout-label a').click(
		function() {
			if ($('.popout-container .popout-content').hasClass('popped')) {
				$('.popout-container .popout-content').hide(
					'blind', 
					{direction: "vertical"},
					500
				);
			} else {
				$('.popout-container .popout-content').show(
					'blind', 
					{direction: "vertical"},
					500
				);
			}
			$('.popout-container .popout-content').toggleClass('popped');
			return false;
		}
	);
}
/**
 * Takes the current path name and converts it to the location hash format.
 * 
 * @return string the converted location hash
 */
function locationToHash() {
	
	hash = window.location.pathname;

	hash = hash.replace(/^\//,'#');
	hash = hash.replace(/\/$/,'' );
	//hash = hash.replace(/\//, '|');
	
	return hash;
	
}
/**
 * Converts the base links (level one) from the location hash, looks up the accordion
 * menu, grabs the rel attribute from it (which we use to store the section's class name).
 * We then perform the style modifications and animations accordingly.
 * 
 * @return null
 */
function baseAliasToClass() {
	
	classname 	= 'home';
	hash 		= window.location.hash;
	
	if (hash != '') {
		
		hash 		= hash.replace(/^#/   ,'/');
		min_hash	= hash.replace(/\/(\w+)\/.*/,'/$1');
		hash		= hash.replace(/\//g  ,'/');
		min_hash	= (min_hash == "/home") ? '/' : min_hash;
	}
	
	el = $("#vertical-accordion-1 a[href^="+min_hash+"]");
	
	newClass = el.attr('rel');
	
	oldClass = $('#content-body').attr('class');
	
	$('#content-body').attr('class',newClass);
	
	colour = $('#content-body .content-title').css("color");

	$('body').attr('class',newClass);
	
	if (newClass != oldClass) {
		$('#vertical-accordion-1 ul:visible').slideUp('normal');
	}
	
	$('#vertical-accordion-1 li.l1.p.'+newClass+' ul').slideDown('normal');
	
}

/** 
* Normalises the URL when using legacy entrance points. Unfortunately, it causes the home
* page to flicker in between the initial load, the JavaScript re-direct and the AJAX
* hash load. The advantage of this method is that it enables users a smooth transition
* between pages and allows them to book-mark pages.
* 
* @return string|null The resulting pathname converted from the location hash.
*/
function parseLocationHash() {
	
	hash = window.location.hash;
	
	if (hash != '') {
		
		hash = hash.replace(/\//g, '/');
		hash = hash.replace('#',   '/')+'/';
		
	} else if (window.location.pathname != "/") {
		
		hash = locationToHash();

		window.location.href = "http://"+window.location.hostname+"/"+hash;
		
	} else hash = '/home';
	
	return hash;
	
}
/**
 * Performs an AJAX load action based on the parsed location hash and submits the Google
 * tracking information too. 
 * 
 * @return null
 */
function gotoLocationHash() {

	loc = parseLocationHash();
	
	if (loc) {
	
		$.ajax({
			type: "GET",
			url: unescape(loc),
			dataType: "json",
			beforeSend: function (xhr) {
				$('#load-indicator').fadeTo(400,1);
			},
			success: function(i) {
				try {
					window.location.hash = i.location;
					document.title = i.meta.title;
					baseAliasToClass();
					$('.content-title span:last-child').text(i.title);
					$('#dom-target').html(unescape(i.content));
					
					try {
						
						if (pageTracker) {
							
							pageTracker._trackPageview(unescape(loc));
							
						}
						
						if (Recaptcha && $('#recaptcha_target').size() > 0) {
							Recaptcha.create(
								"6LdIiwMAAAAAAMyegWQECmDY5nf5giaX5pWFAOew",
								document.getElementById('recaptcha_target')
							);
						}
					
					} catch (e) { 
						
						$('#dom-target').prepend('<div class="error">You seem to be blocking external scripts, site functionality may be impaired</div>');
						
					}
					
					if ($('#project .tab').size() > 1) {
						$('#project').tabs({
							fx: { 
								opacity: 'toggle'
							}
						});
					}
					if (i.option.showtitle == 0) {
						
						$(".content-title:not(:hidden)").hide(
								'blind', 
								{direction: "vertical"},
								500
						);
						
					} else {
						
						$(".content-title:not(:visible)").show(
								'blind', 
								{direction: "vertical"},
								500
						);
						
					}
					
					$('#load-indicator').fadeTo(750,0);
					
					tb_init('#dom-target a.thickbox');
					
					if (refactorWidgets(i.widgets))
					
						ajaxify('#dom-target a[href^=/]:not(#admin-menu a,a[href^=/what-we-think],a.popup,.static-box a,a[href*=.])');
					
				} catch (e) {
					
					
					
				}
				
			}
		});
	
	} else {
		
		if (pageTracker)
			
			pageTracker._trackPageview('/');
		
	}
	
}
/**
 * Site Initialisation, instantiates the tracker and initialises behaviours
 */

if (_gat)

	var pageTracker = _gat._getTracker("UA-7196515-1");

$(document).ready(function() {
	$('#dom-target').html('');
	$('.content-title span:last-child').text('');
	gotoLocationHash();
	try { createPositions(); } catch (e) { } //Fail
	initMenu();
	ajaxify('a[href^=/]:not(#admin-menu a,a[href^=/what-we-think],a.popup,a[href*=.])');
	tb_init('#dom-target a.thickbox');
	$('#featured-projects').addClass('enabled');
	$("#featured-projects > ul").tabs({fx:{opacity: "toggle",event: 'mouseover'}}).tabs("rotate", 5000, true);
	/*
	$(".contact").validate({
		debug: true,
		submitHandler: function(form) {
			form.submit();
	   	},
	   	errorClass: "invalid",
	   	rules: {
	   		name: {
	   			required: true,
	   			minlength: 3
	   		},
	   		num: {
	   			minlength: 6
	   		},
	   		mail: {
	   			required: true,
	   			email: true
	   		},
	   		when: "required",
	   		recaptcha_response_field: "required",
	   		message: "required"
	   	},
	   	messages: {
	   		name: {
	   			required: "You or your companies name",
	   			minlength: "Enter a longer name!"
	   		},
	   		num: {
	   			minlength: "That number isn't long enough"
	   		},
	   		mail: {
	   			required: "We need an e-mail address",
	   			email: "Enter a valid e-mail address"
	   		},
	   		when: "Choose a subject",
	   		recaptcha_response_field: "",
	   		message: "We need some details to go on"
	   	}
	});
	*/
});