function makeurl(url){
	base = '';
	if(base.length && !url.match( base.replace(/\//,'\/') )) return base+url;
	else return url;
}

var spaceVibes = {
	currentPageIndex: 0,
	scrollWidth : $(window).width(),
	scrollpages : ['welcome','our_services','projects','quotes', 'thankyou'],
	backgrounds: ['welcome','our_services','projects','quotes'],
	previewImg : new Image(),
	tooltip: null,
	viewingProject : {
		href: '',
		p: {left:0, top:0},
		lp: {left:0, top:0},
		w: 0,
		h: 0
	},
	
	/**
	 * Load content based on page we are on
	 */
	Init: function(){
		/**
		 * Are we on a scrollable pages page
		 */
		$.each(spaceVibes.scrollpages, function(i, obj){
			if($('#body_'+obj).get(0)){
				spaceVibes.currentPageIndex = i;
				spaceVibes.loadScrollablePages();
				return false;
			}
		});
		/**
		 * Are we on CMS page
		 */
		if($('#page_content_management_systems').get(0)){
			spaceVibes.loadCMSForms();
		}
	},
	/**
	 * Load in Scrollable pages
	 */
	loadScrollablePages: function(){
		$('#pagenav li').each(function(i){
			var id = this.id.replace(/^link_/,'page_');
			var link = $('a', this);
			if(!$('#'+id).get(0)) spaceVibes.getScrollablePage( link.attr('href') );
			spaceVibes.bindPageNavEvents(link, i);
			link.after( $('<span href="#" class="dummy"/>') );	
		});
		if(!$('#page_thankyou').get(0)) spaceVibes.getScrollablePage( '/thankyou.html?nocache' );
	},
	/**
	 * Load scrollable page
	 */
	getScrollablePage: function(url){
		$.get( makeurl(url+'?nocache'), function(data){
			$('#contentscroll').append(data);
			spaceVibes.orderScrollablePages();
		});
	},
	/**
	 * Set the order of scrollable divs
	 */
	orderScrollablePages: function(){
		if( $('#contentscroll div.content').length<5) return;
		$('#pagenav li').each(function(i){
			var id = this.id.replace(/^link_/,'page_');
			$('#'+id).appendTo('#contentscroll');
		});
		$('#page_thankyou').appendTo('#contentscroll');
		spaceVibes.initContentWidths();
		$('#contentwrap').scrollLeft(spaceVibes.scrollWidth*spaceVibes.currentPageIndex);
		spaceVibes.loadOtherContent();
		spaceVibes.bindProjectNavigationLinks();
	},
	/**
	 * Set each content divs min width
	 */
	initContentWidths: function(){
		var w = $(window).width();
		spaceVibes.scrollWidth = w<1024? 1024 : w;
		$('div.content').css('width',  spaceVibes.scrollWidth+'px');
		setTimeout(function(){ spaceVibes.centerContent(); }, 500);
	},
	/**
	 * Center Content
	 */
	centerContent: function(){
		var bodyel = $('#body_welcome, #body_our_services, #body_projects, #body_quotes, #body_thankyou').get(0);
		if(bodyel){
			var h = $(bodyel).height();
			if(h<580) return;
			var dif = Math.round((h - 580)/2);
			$('div.pagecontents, #pagenav').animate({'top': 75+dif}, 500);
			$('#stripes').animate({'top': 89+dif}, 500);
			$('#project_pagination').animate({'top': 35+dif}, 500);
			$('h1.pagetitle').animate({'top': 12+dif}, 500);
			$('#recentprojects').animate({'top': 364+dif}, 500);
		}
	},
	/**
	 * Load in other content divs
	 */
	loadOtherContent: function(){
		if(!$('#recentprojects').get(0)){
			$.get(makeurl('/projects/recent/recent.html?nocache'), function(data){
				if(data.length)	$('#contentwrap').after($(data).hide());
					spaceVibes.bindViewProjectLinks();
					var bodyel = $('#body_welcome, #body_our_services, #body_projects, #body_quotes, #body_thankyou').get(0);
					if(bodyel){
						var h = $(bodyel).height();
						if(h>=580){
							var dif = Math.round((h - 580)/2);
							$('#recentprojects').css('top', 364+dif);
						}
					}
			});
		}else{
			spaceVibes.bindViewProjectLinks();
		}
		spaceVibes.bindSubmitQuotesForm();
		// preload other images
		var img = new Image();
		img.src = 'images/viewproject.png';
		/*$.each(spaceVibes.backgrounds, function(i, obj){
			var img = new Image();
			img.src = 'images/backgrounds/'+obj+'_75.jpg';
		});*/
	},
	/**
	 * Bind Page Nav click events
	 */
	bindPageNavEvents: function(link, index){
		link.mousedown(function(){
			var  li = $(this).parent();
			if(li.hasClass('active') && spaceVibes.currentPageIndex !=4) return false;
			spaceVibes.currentPageIndex = index;
			spaceVibes.scrollPageTo(index);
			if(window.pageTracker){
				window.pageTracker._trackPageview( $(this).attr('href') );
			}
			$('#pagenav li.active').removeClass('active').children('.dummy').fadeOut(300);
			li.addClass('fadeIn');
			$(this).next().animate({opacity:0.8}, 500).fadeIn(600, function(){ li.addClass('active').removeClass('fadeIn'); });
			return false;
		}).click(function(){return false;});;
	},
	/**
	 * Scroll page to
	 */
	scrollPageTo: function(index){
		index = typeof index != 'undefined'? index : spaceVibes.currentPageIndex;
		if(index > 1) $('#recentprojects').fadeOut(200);
		spaceVibes.tooltip.hide();
		//spaceVibes.swapBackground(index);
		$('#contentwrap').animate({
        scrollLeft : spaceVibes.scrollWidth*index
    }, 750, function(){
			if(index < 2)	$('#recentprojects').fadeIn(300);
		});
	},
	/**
	 * Swap Background image
	 */
	swapBackground: function(index){
		var bg = $('div#background img');
		var index = index >= 4? 3 : index;
		bg.load(function(){
			$(this).unbind();
			bg.fadeIn(600);
		});
		bg.fadeOut(300, function(){ bg.attr('src', makeurl('/images/backgrounds/'+spaceVibes.backgrounds[index]+'_75.jpg')); });
	},
	/**
	 * Bind project Navigation links
	 */
	bindProjectNavigationLinks: function(){
		var links = $('#project_pagination a');
		links.unbind().live('mousedown',function(){
			var link = $(this);
			if($(this).hasClass('active')) return false;
			if(window.pageTracker){
				window.pageTracker._trackPageview( $(this).attr('href') );
			}
			$.get(makeurl(this.href+'?nocache'), function(data){
				if(!link.hasClass('prev') && !link.hasClass('next')){
					$('#project_pagination a').removeClass('active');
					link.addClass('active');
				}
				var portfolio = $('div.pagecontent ul.portfolio');
				$('a', portfolio).unbind();
				data = $(data.replace(/[\r\n\t]+/g,''));
				$('#project_pagination .pagination').replaceWith( data[0] );
				portfolio.fadeOut(300, function(){
					$(this).replaceWith( $(data[1]).fadeIn(300) );
				});
			});
		}).live('click',function(){return false;});
	},
	/**
	 * Bind portfolio links that launch view project popup
	 */
	bindViewProjectLinks: function(){
		var links = $('ul.portfolio li a.projectlink, #returnbar .navlinks a');
		links.unbind().live('mousedown',function(){
			var link = this;
			if($(link).hasClass('disabled')) return false;
			if(window.pageTracker){
				window.pageTracker._trackPageview( $(this).attr('href') );
			}
			if(link.href == spaceVibes.viewingProject.href){
				spaceVibes.showProjectDetails(link);
				return;
			}
			spaceVibes.viewingProject.href = link.href
			$.get(makeurl(link.href+'?nocache'), function(data){
				if($('#projectDetails').get(0)){
					$('#projectDetails').replaceWith($(data).hide());
				}else{
					$(data).hide().insertBefore('#pagenav');
				}
				setTimeout( function(){spaceVibes.showProjectDetails(link, true);}, 300);
			});
		}).live('click',function(){return false;});
		spaceVibes.bindProjectDetailsLinks();
		spaceVibes.bindContentLinks();
	},
	/**
	 * Bind Links on the View Project Detail popup
	 */
	bindProjectDetailsLinks: function(){
		$('#projectDetails a.close').unbind().live('click',function(){
			$('#returnbar').slideUp(300);
			var lp = spaceVibes.viewingProject.lp
			var vp = $('#viewproject');
			vp.animate({width:0, height:0, left:lp.left, top:lp.top}, 600);
			return false;
		});
		$(spaceVibes.previewImg).unbind().bind('load', function(){
			var preview =	$('#projectDetails #preview img');
			preview.fadeOut(600, function(){ preview.attr('src', spaceVibes.previewImg.src).fadeIn(600); });
		});
		// Add Gallery Thumbnail Events
		$('#projectDetails ul.thumbs img').live('mousedown', function(){
			$('#projectDetails ul.thumbs li').removeClass('active');
			$(this).parent('li').addClass('active');
			$('#projectDetails #preview img').fadeOut(600);
			$(spaceVibes.previewImg).attr('src', $(this).attr('src').replace(/w=\d+/,'w=368').replace(/h=\d+/,'h=243') );
		});
	},
	/**
	 * Bind content links that link to scrollable pages
	 */
	bindContentLinks: function(){
		var navlinks = $('#pagenav li a');
		$('#contentwrap a').each(function(){
			var link = this;
			$.each(navlinks, function(i){
				if(this.href == link.href){
					$(link).bind('click', function(){
						$(navlinks[i]).trigger('mousedown');
						return false;
					});
				}
			});
		});
		spaceVibes.bindTooltipEvents();
	},
	/**
	 * Show Project Details
	 */
	showProjectDetails: function(link, bool){
		spaceVibes.tooltip.hide();
		$('#projectDetails').show();
		$('#returnbar').slideDown(300);
		var project = $('#viewproject').attr('style','').css('visibility','hidden');
		if(bool){
			spaceVibes.viewingProject.p = project.offset();
			spaceVibes.viewingProject.lp = $(link).offset();
			spaceVibes.viewingProject.w = project.outerWidth(true);
			spaceVibes.viewingProject.h = project.outerHeight(true);
		}
		var h = Math.round(($('body').height() - spaceVibes.viewingProject.h)/2) - 80;
		if(h>20) spaceVibes.viewingProject.p.top = h;
		var obj = spaceVibes.viewingProject;
		project.css({width:140, height:80, left:obj.lp.left, top:obj.lp.top, visibility:'visible'});
		project.animate({width:obj.w, height:obj.h, left:obj.p.left, top:obj.p.top}, 600);
		// preload project images
		$('#projectDetails ul.thumbs img').each(function(){
			var img = new Image();
			img.src = $(this).attr('src').replace(/w=\d+/,'w=368').replace(/h=\d+/,'h=243');
		});
	},
	/**
	 * Load CMS Forms
	 */
	loadCMSForms: function(){
		$.get(makeurl('/cms/testdrive/?nocache'), function(data){
			$(data).css('display','none').insertAfter('#cmsloginlink');
			$('#cmslogin').clone().attr('id','cmsloginb').appendTo('#page_content_management_systems div.cmsloginform').show();
			spaceVibes.bindCmsLoginForms();
		});
		$.get(makeurl('/quotes/request/cms/?nocache'), function(data){
			$('#page_content_management_systems .pagecontent').append($(data).hide());
			spaceVibes.bindSubmitQuotesForm();
		});
		$('#cmsloginlink a.loginlink').mousedown( function(){
			spaceVibes.showDemoForm();
			if(window.pageTracker){
				window.pageTracker._trackPageview( $(this).attr('href') );
			}
		}).click(function(){return false;});
		$('#cmslinks a').mousedown(function(){
			if(window.pageTracker){
				window.pageTracker._trackPageview( $(this).attr('href') );
			}
			if(this.href.match(/quote/)){
				spaceVibes.showCMSQuoteForm();
			}else if(this.href.match(/testdrive/)){
				spaceVibes.showTestDriveForm();
			}
		}).click(function(){return false;});
		
	},
	/**
	 * Submit testdrive login forms via ajax
	 */	
	bindCmsLoginForms: function(){
		$('form.cmsloginform').each(function(){
			var form = $(this).unbind();
			form.ajaxForm({
				success: function(responce, status){
					spaceVibes.updateTestDriveForm(responce, status, form);
				}
			});
		});
	},
	/**
	 * Update the testdrive form after ajax submission
	 */
	updateTestDriveForm:function(response, status, form){
		if(status != 'success'){
				alert(status);
				return false;
		}
		if(response.match(/script/)){
			form.replaceWith( response );
		}else{
			response = $(response.replace(/[\n\r\t]+/g,''));
			form.replaceWith( $('form.cmsloginform', response ) );
			spaceVibes.bindCmsLoginForms();
		}
	},
	
	/**
	 * Display the CMS Quote Form
	 */
	showCMSQuoteForm: function(){
		var form = $('#cmsquoteform'),
				h = form.height();
		$('#cmsinfo').hide(100);
		var content = $('#page_content_management_systems .pagecontent');
		content.css({position:'relative', height:h+15+'px', overflow:'hidden'})
		form.css({width:0, height:0, overflow:'hidden', position:'absolute',bottom:0, right:0}).show();
		form.animate({width:630, height:420}, 400, function(){
			form.css({position:'relative'});
			content.css({height:'auto'});
		});
	},
	
	/**
	 * Show CMS Testdrive From
	 */
	showTestDriveForm: function(){
		var form = $('div.cmsloginform'),
				h = form.height();
		form.css({height:0, overflow:'hidden'}).show();
		form.animate({height: h}, 300);
		$('#cmsloginb a.cancel',form).live('click', function(){
			form.slideUp();
			return false;
		});
	},
	
	/**
	 * Show CMS Demo Form
	 */
	showDemoForm: function(){
		$('#cmsloginlink').hide().next('.loginform').slideDown().next('#cmslogin').slideDown();
		$('#cmslogin a.cancel').live('click', function(){
			$('#cmslogin').hide().prev('.loginform').slideUp().prev('#cmsloginlink').slideDown();
			return false;
		});
	},
	
	/**
	 * Submit scrollable pages Quote form via ajx
	 */
	bindSubmitQuotesForm: function(wrapper){
		var wrapper = $('div.quoteformwrap').get(0);
		if(wrapper) $('form', $(wrapper)).unbind().ajaxForm({ success: function(response, status){spaceVibes.updateQuotesForm(response, status, $(wrapper))} });
	},
	/**
	 * Update Quote Form
	 */
	updateQuotesForm: function(response, status, wrapper){
		if(status != 'success'){
				alert(status);
				return false;
		}
		if(response.match(/^\s*\<script/)) wrapper.append( response );			
		else wrapper.replaceWith( response );
		spaceVibes.bindSubmitQuotesForm();
	},
	/**
	 * Clear form and scroll to thankyou
	 */
	 scrollToThankyou: function(){
		 $('div.quoteformwrap form').clearForm();
		 $('div.quoteformwrap .error-message').hide();
		 spaceVibes.scrollPageTo(++spaceVibes.currentPageIndex);
	 },
	 /**
	  * Bind and show tooltip links
		*/
	bindTooltipEvents: function(){
		spaceVibes.tooltip = $('<div id="tooltipwrap" />').appendTo('body');
		var tool = spaceVibes.tooltip;
		$('span.tooltip').each(function(){
			var tip = $(this);
			var link = tip.parent('a').css({'position':'relative', 'cursor':'pointer'});
			link.mouseover(function(){
				var p = link.offset();
				var w = link.outerWidth();
				tool.css({left: p.left-110+(w/2), top:p.top-120});
				tool.html(tip.html());
				tool.fadeIn();
			}).mouseout(function(){
			 	tool.hide();
			});
		});
	}
	
}


$(function(){
	/**
	 * Bind Ajax Busy
	 */
	$(window).ajaxStart(function(){
		$('#loading').show();
	}).ajaxStop(function(){
		$('#loading').hide();
	});
	/**
	 * Initialise Space Vibes Object
	 */
	spaceVibes.Init();
	/**
	 * Window Load and resize events
	 */
	$(window).load(function(){
		// Highlight Active pag nav item
		$('#pagenav li.active .dummy').fadeIn(300);
	}).resize(function(){
		// Reset content positions on window resize
		spaceVibes.initContentWidths();
		spaceVibes.centerContent();
		$('#contentwrap').scrollLeft(spaceVibes.scrollWidth*spaceVibes.currentPageIndex);
	}).unload(function(){
		$('a').unbind();
	});

});