$(document).ready(function(){
	
	var largeContainer = $('#large-container'),
		businessHome = $("#business-home"),
		youHome = $("#you-home"),
		businessServices = $("#business-subservice"),
		youServices = $("#business-subservice"),
		gridBlock = $(".gridblock"),
		defaultBlock = $("#defaultblock"),
		businessBlockImage = $("#businessblockimage").val(),
		youBlockImage = $("#youblockimage").val(),
		activeServiceBlock = $("#activeserviceblock").val(),
		overlayDiv = function(){ 
			return $("<div />",{ 
						//class: 'overlay',
						
						click: function(){
							
							var href = $(this).parent()
											  .find('a:first')
											  .attr('href'); 
											  
							if(href) window.location = href ;	
						}
					}).addClass('overlay');
		},
		menus = [ //0 = link that triggers element, 1 = menu element
			[$('#business-link'),$('#business-top')],
			[$('#for-you-link'),$('#you-top')],
			[$('#foryou-people-nav-link'),$('#our-people-2')],
			[$('#business-people-nav-link'),$('#our-people-1')]
		],
		
		businessContent = ('<h2>services for business</h2>' +
						  '<span class="line"></span>' + 
						  '<div id="font-sizing">' +
    							'<a class="decrease-font" href="javascript:void(0)">Decrease font size <span>Click to decrease the font size</span></a>' +
    							'<a class="increase-font" href="javascript:void(0)">Increase Font size <span>Click to increase the font size</span></a>' +
							'</div><div class="editor-content">' + $('#hidden-content-sfb').html() + '</div>'), 
						 
						  				  
		youContent = ('<h2>services for you</h2>' +
					 '<span class="line"></span>' + 
					  '<div id="font-sizing">' +
    							'<a class="decrease-font" href="javascript:void(0)">Decrease font size <span>Click to decrease the font size</span></a>' +
    							'<a class="increase-font" href="javascript:void(0)">Increase Font size <span>Click to increase the font size</span></a>' +
							'</div><div class="editor-content">' + $('#hidden-content-sfy').html() + '</div>');
		
				 
	//interactive blocks
	youHome.append(overlayDiv)
		   .addClass('visible')
		   .bind('click',function(){
			   if( !$(this).hasClass('notClickable') ){
				  animateImageBlock(businessHome,1);
				  animateH2(youHome,'bottom');
				  setActiveMenu(menus[1]);
				  setMainContent(youContent);
				  setSideBar('foryou');
			   }
			});
		   
	businessHome.append(overlayDiv)
				.addClass('visible')
				.bind('click',function(){
					if( !$(this).hasClass('notClickable') ){
					    animateImageBlock(youHome,0);
					    animateH2(businessHome,'top');
						setActiveMenu(menus[0]);
						setMainContent(businessContent);
						setSideBar('business');
					}
				});
	
	
	//if on a subpage set default block
	if( defaultBlock && defaultBlock.val() !== '' ){
		var defaultBlockName = defaultBlock.val(),
			defaultServicesBlock = (defaultBlockName == 'business') ? businessServices : youServices,
			blockToShow = (defaultBlockName == 'business') ? businessHome : youHome;
			blockToHide = (defaultBlockName == 'business') ? youHome : businessHome;
			
			setDefaultBlock(blockToHide,blockToShow,defaultServicesBlock,activeServiceBlock);
	}
	setBlockImages(businessHome,youHome,businessBlockImage,youBlockImage);
	
	
	//profiles grid
	$('#profiles-grid .gridblock, .grid .gridblock, #business-home, #you-home').bind('mouseenter',function(){
		$(this).find('.overlay').animate({
			opacity:0
			
		},{
			duration:200
		});
	})
	.bind('mouseleave',function(){
		if(!$(this).find('.overlay').hasClass('active')){
			$(this).find('.overlay').animate({
				opacity:0.1
				
			},{
				duration:200
			});
		}
	})
	
	
	
	
	$('#profiles-grid').find('.gridblock').bind('click',function(){
		var self = $(this);
		if( self.hasClass('no-overlay') ){
			return false;	
		}
		var	profileBlock = $('#main-profile-block'),
			profileBlockImg = $('#large-profile-image'),
			strapline = $('.imageblock-strapline'),
			mainContent = $('#mainContent'),
			profileData = $('#profile-data'),
			preloader = (function(){ 
				return $("<span>",{ 
							//class: 'preloader'
						}).addClass('preloader');
			});
		
		//change active grid item
		$('.gridblock .overlay.active').removeClass('active')
									   .animate({ opacity: 0.1 });
		
		//set contact form
		$('#contact-form').find("select[name='person']")
						  .find("option[value='" + self.find('input[name="email"]').val() + "']")
						  .attr('selected','selected');
		
		self.find('.overlay')
		    .addClass('active');
		
		//animate strapline
		strapline.animate({
			bottom: '-130'
		},{
			duration: 600,
			easing: 'easeOutQuad',
			complete: function(){
				strapline.find('h2').html( self.find('input[name="name"]').val() );
				strapline.find('#profile-position').html( self.find('input[name="position"]').val() );
				strapline.find('#mail-link').attr('href','mailto:' + self.find('input[name="email"]').val());
				strapline.find('#profile-telephone').html( self.find('input[name="telephone"]').val() );
				
				//only show linkedin link if profile has linked in
				var linkedinlink = self.find('input[name="linkedinurl"]').val();
				if(linkedinlink !== ''){
					strapline.find('#linkedin-link').attr('href',self.find('input[name="linkedinurl"]').val()).show();
				}
				else {
					strapline.find('#linkedin-link').hide();
				}
				
				strapline.find('#download-vcard').attr('href',self.find('input[name="vcardurl"]').val() );
			}
		});
		
		//change main content details
		profileData.fadeOut(400,function(){
			var pd = $(this);
			pd.find('h2').html( 'profile' );
			pd.find('#profiletext').html( self.find('input[name="profiletext"]').val() );
			mainContent.append(preloader);
			mainContent.find('.preloader').hide().fadeIn(200);
		});
		
		//change image
		profileBlock.append(preloader);
		profileBlockImg.fadeOut(200,function(){
			$(this).attr('src', 'users_content/profile_images/full/' + self.find('input[name="largeimage"]').val() + '?v=' + (new Date()).getTime() ).load(function(){
				profileBlock.find('.preloader').fadeOut(600,function(){
					$(this).remove();
					setTimeout(function(){
						profileBlockImg.fadeIn(600);
						mainContent.find('.preloader').fadeOut(200,function(){
							$(this).remove();
							profileData.fadeIn(600);
						});
						
						strapline.animate({
								bottom: 20
							},{
								duration: 600,
								easing: 'easeOutQuad'
							});
					},500);
				});
			});
		});
	
		
	});				                       
	
	//when department change, employee dropdown changes to suit	 
	$("select[name='team']").bind('change',function(){
		$.getJSON('ajax.php?action=getpeople', 'team=' + $(this).val(), function(data){
			var html;
			for(x in data){
				var employee = data[x];
				html += "<option value='"+employee.email+"'>"+employee.name+"</option>";
			}
			$("select[name='person']").html( html );
		});
	});
	
	
	//profiles grid pagination
	var gridcontainer = $('#profiles-grid');
	gridcontainer.append('<input type="hidden" id="gridScrollTracker" value="0" />');
	
	var	numprofiles = gridcontainer.find('.gridblock').length,
		perrow = 3,
		visiblerows = 4,
		numrows = Math.ceil(numprofiles / perrow),
		numofscrolls = numrows - visiblerows,
		hideScrollCSS;
		
	if(numrows > visiblerows){
		gridcontainer.bind('mousemove',function(e){
			if( e.pageY > 440){
				if($('#gridScrollTracker').val() < numofscrolls){ 
					showScroll('bottom',1,numofscrolls);
				}
			}
			if( e.pageY < 150){
				if($('#gridScrollTracker').val() > 0){ 
					showScroll('top',0,numofscrolls);
				}
			}
			if( e.pageY > 150 && e.pageY < 440){
				hideScroll();
			}
		})
	}
	
	
	
	//content slider
	var mbSlider = $('.slider').mbSlider({
		pagination: false,
		showControls: false,
		startSlide: 1,
		mousewheelsupport: false,
		slideSpeed: 600,
		easing: 'easeOutCirc'
	})
	.get(0)
	.mbSlider;

	
	//Navigation link bindings
	$('#top-menu a').bind('click',function(e){
		var urlParts = (window.location.pathname).split('/'),
			currentPage = urlParts[urlParts.length-1],
			href = $(this).attr('href');
		
		if(currentPage == href){
			e.preventDefault();
			
			//change active link
			$('#top-menu a.active').removeClass('active');
			$(this).addClass('active');
			
			hideAllMenus(); //hide all active menus
			setMainContent(); //restore original content
			setSideBar('original'); //restore sidebar
			
			
			if( $('#ourpeople-subnav-links').css('opacity') == 1 ){
				$('#ourpeople-nav-link').trigger('click');	
			}
			
			if(typeof mbSlider !== 'undefined' && mbSlider.currentSlide !== 1){
				mbSlider.moveprev();	
			}
		}
	});
	
	
	//contact page contact form
	$('.contact-form').submit(function(event){
		event.preventDefault();
		var contactFormContainer = $('#large-contact'),
			errorContainer = $('<div>',{
				id: 'error-container'
			}),
			errors = [],
			name = $('#name').val(),
			email = $('#emailaddress').val(),	
			telephone = $('#tele').val(),
			enquiry = $('#details').val(),
			comments = $('#details').val(),
			emailRegex = /^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
			
		if(name == ''){
			errors.push('You have not entered a name');	
		}
		
		if(!emailRegex.test(email)){
			errors.push('You have not entered a valid email Address');	
		}
		
		if(telephone == ''){
			errors.push('You have not entered a telephone number');	
		}
		else if(isNaN(telephone)){
			errors.push('You have not entered a valid telephone number');	
		}
		
		if(enquiry == ''){
			//errors.push('You must select an enquiry type');	
		}
		
		if(comments == ''){
			errors.push('You have not entered a message');	
		}
		else if(comments.length < 20){
			errors.push('Your message must be greater than 20 charcters');	
		}
		
		if(errors.length > 0){
			var html = '';
			html += '<ul id="errors">';
			for(i=0; i<=errors.length - 1; i++){
				html += '<li>'+errors[i]+'</li>';	
			}
			html += '</ul>';
			
			if( $('#errors').length > 0 ){
				$('#errors').fadeOut(200,function(){
					$(this).remove();
				});
				$('#error-container').html( html );
				$('#errors').hide().fadeIn(200);
			}
			else {
				contactFormContainer.after(errorContainer);
				$('#error-container')
				.html( html )
				.animate({
					right: 480
				},600);
			}
		}
		else {
			var html = "<p id='success'>Thank you for your message</p>";
			if( $('#errors').length > 0 ){
				$('#errors').fadeOut(200,function(){
					$(this).remove();
				});
				$('#error-container').html( html );
				$('#success').hide().fadeIn(200);
			}
			else {
				contactFormContainer.after(errorContainer);
				$('#error-container')
				.html( html )
				.animate({
					right: 480
				},600);	
			}
			
			$.ajax({
				url: 'ajax.php?action=contactform',
				type: 'POST',
				data: $('#contact-form').serialize()
			});
			
			setTimeout(function(){
				$('#error-container').animate({
					right: 0
				},600,function(){
					$(this).remove();
					$('#emailaddress, #tele, #details, #name').val('');
				})
			},3000);
		}
	});

	
	//our people links
	$('#ourpeople-subnav-links')
		.data('original-width', $('#ourpeople-subnav-links').width()) 
		.css({
			width: 0,
			opacity: 0
		});
	
	$('#ourpeople-nav-link').bind('click',function(){
		var subnav = $('#ourpeople-subnav-links'),
			topmenu = $('#top-menu'),
			animateWidth,
			animateOpacity,
			operator,
			subnavoriginalwidth = subnav.data('original-width');
		
		//hide all submenus when our people link is clicked
		if( $('#business-link').hasClass('active') ){
			$('#business-link').trigger('click')
		}
		else if( $('#for-you-link').hasClass('active') ){
			$('#for-you-link').trigger('click');	
		}
		else {
			hideAllMenus();
		}
		
		
		if(subnav.css('opacity') < 1){
			animateWidth = subnav.data('original-width');
			animateOpacity = 1;
			operator = '+=';
		}
		else {
			animateWidth = 0;
			animateOpacity = 0;
			operator = '-=';
		}
		
		subnav.animate({
			width: animateWidth,
			opacity: animateOpacity
		},{
			duration: 200
		});
		
		topmenu.animate({
			width: operator + subnavoriginalwidth
		},{
			duration: 200	
		});
	});

	//***********************************************
	// On Page Load
	//***********************************************
	
	//cache original main content on #mainContent
	$('#mainContent').data('original-html',$('#mainContent').html());
	
	//cache original sidebar on .sidebar
	$('.sidebar').data('original-html',$('.sidebar').html());

	//cache navigation css height, set link event bindings
	$.each(menus,function(x){
		var menuObj = menus[x],
			menuLink = menuObj[0],
			menu = menuObj[1];
	
		menu.data('original-height',menu.height());
		
		if(!menu.hasClass('visible-on-load')){ //if not to be visible on load
			menu.css({
					'height' : 0,
					'opacity' : 0
				})
				.addClass('hidden');
		}
		else { //if should be visible on load
			menu.addClass('visible')
				.css('display','block');	
		}
		
		
		//initially set as display none so doesnt break menu when page first loads,
		$('#ourpeople-subnav-links').css('display','block');
		
		menuLink.bind('click',function(){
			var self = $(this),
				id = self.attr('id'),
				targetBlock = (id == 'business-link') ? businessHome : youHome,
				time = 800 //slider timer

			switch(id){
				case 'business-link':
					if(businessHome.hasClass('active')){ //trigger interactive block
						youHome.trigger('click');
					}
				break;
				case 'for-you-link':
					if(youHome.hasClass('active')){ //trigger interactive block
						businessHome.trigger('click');	
					}
				break;
				default: //if not triggering interactive block
					setActiveMenu(menuObj);
					return false;
				break;
			}
			
			if( $('#ourpeople-subnav-links').css('opacity') == 1 ){
				$('#ourpeople-nav-link').trigger('click');	
			}
			
			t = setTimeout(function(){ targetBlock.trigger('click') },time); //trigger click when slide has finished
			
			if(typeof mbSlider !== 'undefined' && mbSlider.currentSlide == 1){
				mbSlider.movenext();	
			}
		});
		
		$('.decrease-font').live('click',function(){
			$('#mainContent p, .sidebar p, .sidebar span, .sidebar a').each(function(){
				var fsize = parseInt($(this).css('font-size'))
				$(this).css('font-size',fsize - 1);
			})
		})
		
		$('.increase-font').live('click',function(){
			$('#mainContent p, .sidebar p, .sidebar span, .sidebar a').each(function(){
				var fsize = parseInt($(this).css('font-size'))
				$(this).css('font-size',fsize + 1);
			})	
		})
		
		
		
	});
	
	//add overlay to grid blocks
	gridBlock.each(function(){
		var self = $(this);
		if( !self.hasClass('no-overlay') ){
			self.append(overlayDiv);
		}
	});
	
	
	//profiles page on load
	//set active gridblock
	var activeGridBlockIndex = $('#default_active_gridblock').val(),
		activeGridBlock = $('input[name="id"][value="'+activeGridBlockIndex+'"]').parent()
	
		activeGridBlock.find('.overlay')
					   .css({ opacity : 0.001 })
					   .addClass('active');
		
	$("select[name='person']").find("option[value='"+ activeGridBlock.find('input[name="email"]').val() +"']").attr('selected','selected');

	
	//fade in homepage images
	$('#business-home-img, #you-home-img').load(function(){
		$(this).fadeIn(200);
	})


//***********************
// Sub Navigation Menus
//***********************

function setActiveMenu(menuObj)
{
	$('#top-menu a.active').removeClass('active');
	if(menuObj[1].hasClass('visible')){
		hideAllMenus();
	}
	else {
		hideAllMenus();
		animateMenu( menuObj[1], 1);
		menuObj[0].addClass('active');
	}
}

//hides all submenus
function hideAllMenus()
{
	$('.sub-nav').each(function(){
		animateMenu( $(this), 0);
	});
}

//animates a submenu
function animateMenu(menu,showhide)
{
	var rmClass,addClass,h,o,d;
	if(showhide == 1){
		animateMenu($('.sub-nav.visible'),0); //hide any active sub navs
		rmClass = 'hidden';
		addClass = 'visible';
		h = menu.data('original-height');
		o = 1;
		d = 'block';
	}
	else {
		rmClass = 'visible';
		addClass = 'hidden';
		h = 0;
		o = 0;	
		d = 'none';
	}
	
	menu.removeClass(rmClass)
		.addClass(addClass)
		.stop().animate({
			height : h,
			opacity: o	
		},400,function(){
			menu.css('display',d);	
		});	
}


//************************
// Image Block
//************************

//animates imageblock
function animateImageBlock(target,direction)
{
	var direction = (direction == 0) ? '-' : '',
		isVisible = target.hasClass('visible'),
		animation = (isVisible) ? { top: direction + target.height(), opacity:0, filter: ''	} : { top: 0, opacity:1, filter: '' };
	
	target.stop().animate(animation,{
		duration: 800,
		easing: 'easeOutCirc'
	})
	.toggleClass('visible')
	.toggleClass('active');
}

//animates H2 block on imageblock
function animateH2(target,cssPos)
{
	var animatedState = '210px',
		originalState = '20px',
		h2 = target.find('.imageblock-header'),
		text = target.find('.imageblock-desc'),
		isAnimated = h2.hasClass('animated');
	
	if(cssPos == 'top'){
		animation = {
			top : (isAnimated) ? originalState : animatedState
		}
	}
	else {
		animation = {
			bottom : (isAnimated) ? originalState : animatedState
		}	
	}
	
	textAnimation = (isAnimated) ? { height:0, opacity:0, filter: '' } : { height:50, opacity:1, filter: '' };
	
	h2.stop().animate(animation,{
		duration: 800,
		easing: 'easeOutCirc'
	}).toggleClass('animated');
	
	text.animate(textAnimation,600);
}

function setDefaultBlock(blockToHide,blockToShow,defaultServicesBlock,activeServiceBlock)
{
	var cssPos = (blockToShow.attr('id') == 'business-home') ? 'top' : 'bottom';
	
	blockToHide.css({
		'top' : '-' + $(this).height() + 'px',
		'opacity' : '0.1'
	})
	.toggleClass('active')
	.toggleClass('visible');
	
	blockToShow.find('.imageblock-header')
			   .css(cssPos,'210px')
			   .toggleClass('animated')
			   .find('.imageblock-desc')
			   .css({ 'height':'50px', 'opacity':'1', 'display':'block' })
			   
	defaultServicesBlock.find('.gridblock')
			 			.eq(activeServiceBlock - 1)
						.addClass('active')
						.find('.overlay').remove(); 
}	

function setBlockImages(businessBlock,youBlock,businessDefaultImage,youDefaultImage)
{
	var businessBlockImage = businessBlock.find('img:first'),
		youBlockImage = youBlock.find('img:first');
	
	businessBlockImage.attr('src',businessDefaultImage);	
	youBlockImage.attr('src',youDefaultImage);	
}





//***********************
// Profiles Grid Scroll
//***********************

//shows grid scroll bars
function showScroll(pos,dir,numofscrolls)
{
	var instance = $('#scrollbar').length,
		gridContainer = $('#profiles-grid'),
		scrollBarClass = (pos == 'bottom') ? 'bottom' : 'top',
		animCSS = (pos == 'bottom') ? { bottom: 0 } : { top: 0},
		scrollBar = (function(){
			return $("<div>",{
						id: 'scrollbar',
						click: function(){
							scrollGrid(dir,numofscrolls);
						},
						mouseout: function(){
							hideScroll();	
						}
					})
					.addClass(scrollBarClass);
		});
		
	if(instance == 0){
		gridContainer.append(scrollBar);
		var scrollbar = $('#scrollbar');
		hideScrollCSS = (pos == 'bottom') ? { bottom: scrollbar.css('bottom') } : { top: scrollbar.css('top')}
		scrollbar.stop().animate(animCSS, 200);
	}
}

//hide scrollbar
function hideScroll()
{
	var scrollbar = $('#scrollbar');
	if(scrollbar.length > 0){
		scrollbar.stop().animate(hideScrollCSS,100,function(){
			$(this).remove();
		});
	}
}

//animate grid scroll
function scrollGrid(dir,numofscrolls)
{
	var scrollTracker = parseInt( $('#gridScrollTracker').val() );
	if((dir == 0 && scrollTracker !== 0) || (dir == 1 && scrollTracker !== numofscrolls)){
		var gridContainer = $('#profiles-grid'),
			rowSize = gridContainer.find('.gridblock').eq(0).height(),
			animCSS = (dir == 1) ? { marginTop: '-=' + rowSize } : { marginTop: '+=' + rowSize };
		
	
		$('#profiles-grid-container').stop().animate(animCSS,200,function(){
			if(dir == 1){
				$('#gridScrollTracker').val( scrollTracker + 1 );
			}
			else {
				$('#gridScrollTracker').val( scrollTracker - 1 );
			}	
		});
	}
}




//***********************
// Other Misc Functions
//***********************

//changes the main content of a page
function setMainContent(pageContent)
{
	var mc = $('#mainContent');
	if(!pageContent){
		pageContent = mc.data('original-html');
	}
	if(mc.html()!== pageContent){
		mc.fadeOut(200,function(){
			$(this).html(pageContent)
				   .fadeIn(200);
		});
	}
}


//changes the sidebar on the page
var currentnews = 0;
function setSideBar(caller)
{
	var sb = $('.sidebar'),
		newscat = (caller == 'foryou') ? '3' : '2',
		newnews = newscat,
		content;
		
	if(caller == 'original'){
		content = sb.data('original-html');
		newnews = 0;
	}
	else {
		$.get('ajax.php?action=getnews&cat=' + newscat,function(data){
			content = data;
		});
	}
	
	
	if(sb.html() !== content && currentnews !== newnews){
		sb.fadeOut(200,function(){
			$(this).html(content)
				   .fadeIn(200);
			currentnews = newnews;
		});	
	}
}


//profiles gridblock tooltip
$('.profile-gridblock')
	.mouseenter(function(){
		var self = $(this),
			pname = self.find("input[name='name']").val(),
			ppos = self.find("input[name='position']").val(),
			tooltip = "<div id='profiles-tooltip'>"+
					  "    <h4>"+pname+"</h4>"+
					  "    <h5>"+ppos+"</h5>"+
					  "</div>";
		
		self.append(tooltip);
	
	})
	.mouseleave(function(){
		$(this).find('#profiles-tooltip').remove();
	});


});


