// analytics code
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

// JavaScript Document
// functions to hijack contact form if scripting is turned on
function trimNumber() {
	var myPhone = $('#phone').val();
	$('#phone').val(myPhone.replace(/ /g,''));
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { 
	  	filter = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w{2,}$/;
		p = (filter.test(val)) ? 1 : -1;
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

// global vars
var arrImages
var blogReply = false;

function hijackBlog() {
	$('#main a').each(function() {
		if ((!$(this).hasClass('comment-reply-link')) && (!$(this).hasClass('non-blog'))) {
			$(this).addClass('ajaxlink').attr('rel','blog-'+$(this).attr('href'));
	  }
	});
	
	$('.comment-reply-link').click(function() {
		blogReply = $(this).parents('.depth-1').attr('id');				
	});
	
	$('#cancel-comment-reply-link').click(function() {
		blogReply = false;			
	});
		
	$('#commentform').append('<input type="hidden" id="ajaxsubmission" name="ajaxsubmission" value="1"/>');
	if ($('#commentform .comment-form-comment span.required').length == 0) {
		$('#commentform .comment-form-comment label').after('<span class="required">*</span>');
	}
	$('#commentform').submit(function(){
	
		MM_validateForm('author','','R','email','','RisEmail','comment','','R');
	
		if (document.MM_returnValue) {
		
			var myURL = $(this).attr('action');
			
			try 
				{	
					$.ajax({
						type: 'POST',
						url: myURL,
						context: $('#mainContent'),
						data: $('#commentform').serialize(),
						beforeSend: function() { $('#mainContent').prepend('<div class="loader" style="-moz-opacity: 0.8; opacity: 0.8;"></div>'); },
						error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error posting comment, please try again later'); $('.loader').remove(); },
						success: function(data, textStatus) { $('.loader').remove(); loadPage(data.replace('location=','blog-')); }
					});
					
					// stop here so submit action doesn't complete
					return false;
				
				}
				catch(err)
				{
				// execute as normal
				return true;
				}
		} else {
			return false;	
		}
	});
	
	$('#searchform').submit(function(){
									 
		var myURL = 'blog-http://www.webpoint0.com/blog/?s=' + $('#s').val();
		
		loadPage(myURL);
		
		return false;
									 
	});
	
}

function hijackContact() {
	
	$('#frmEmail').submit(function(){
		
		if (document.MM_returnValue) {

			// if possible, hijack the href request
			var myURL = $(this).attr('action');
			
			try 
			{	
				$('.wideCol .cssbox').prepend('<div class="loader" style="-moz-opacity: 0.8; opacity: 0.8; width: 526px; height: 354px !important; height: 384px"></div>');
				$('#standard').val(0);
				$('.wideCol').load('enqproc.php', { name: $('#name').val(), email: $('#email').val(), phone: $('#phone').val(), message: $('#message').val(), recaptcha_challenge_field: $('#recaptcha_challenge_field').val(), recaptcha_response_field: $('#recaptcha_response_field').val() }, function(){
					$('.loader').remove();
				});
				
				// stop here so submit action doesn't complete
				return false;
			
			}
			catch(err)
			{
			// execute as normal
			return true;
			}
		}
		
	});

}

function layoutPortfolio() {
	// variables
	var animRunning = false;
	var rightQueue = 0;
	var leftQueue = 0;
	
	// add button click functions
	function slideLeft() {
		animSpeed = 650/leftQueue;
		if (!animRunning) {
			animRunning = true;
			$('.portfolioitem:last').css('left','-729px');
			$('.portfolioitems').prepend($('.portfolioitem:last'));
			var currIndicatorID = '#' + $('.portfolioitem:eq(1)').attr('id').replace('portfolioitem','portfolioindicator');
			var nextIndicatorID = '#' + $('.portfolioitem:first').attr('id').replace('portfolioitem','portfolioindicator');
			$('.portfolioitem:eq(1)').animate({
				left: 921							
			}, animSpeed, 'easeInOutQuad');
			$('.portfolioitem:first').animate({
				left: 96							
			}, animSpeed, 'easeInOutQuad', function(){
				$(currIndicatorID).css({
					'background-color':'#14538c',
					'border-color':'#14538c'
				});
				$(nextIndicatorID).css({
					'background-color':'#7c9900',
					'border-color':'#7c9900'
				});
				animRunning = false;
				leftQueue--;
				if (rightQueue > 0) {
					leftQueue = 0;
					slideRight();	
				}
				if (leftQueue > 0) {
					slideLeft();	
				}
			});
		}
	};
	
	function slideRight() {
		var animSpeed = 650/rightQueue;
		if (!animRunning) {
			animRunning = true;
			var currIndicatorID = '#' + $('.portfolioitem:first').attr('id').replace('portfolioitem','portfolioindicator');
			var nextIndicatorID = '#' + $('.portfolioitem:eq(1)').attr('id').replace('portfolioitem','portfolioindicator');
			$('.portfolioitem:first').animate({
				left: -729
			}, animSpeed, 'easeInOutQuad');
			$('.portfolioitem:eq(1)').animate({
				left: 96							
			}, animSpeed, 'easeInOutQuad', function(){
				$(currIndicatorID).css({
					'background-color':'#14538c',
					'border-color':'#14538c'
				});
				$(nextIndicatorID).css({
					'background-color':'#7c9900',
					'border-color':'#7c9900'
				});
				$('.portfolioitem:first')
				.css('left','921px');
				$('.portfolioitems').append($('.portfolioitem:first'));
				animRunning = false;
				rightQueue--;
				if (leftQueue > 0) {
					rightQueue = 0;
					slideLeft();	
				}
				if (rightQueue > 0) {
					slideRight();	
				}
			});
		}
	};
	
	// generate html for portfolio inidicators
	var indicatorHTML = '<div id="portfolioindicators">\n';
	$('.portfolioitem').each(function(x){
		$(this).attr('id','portfolioitem'+x);
		indicatorHTML += '<div id="portfolioindicator'+x+'" class="portfolioindicator"></div>\n';
	});
	indicatorHTML += '</div>\n';
	
	// change css styles to render buttons and layout
	$('.portfolioitems')
	.css('overflow','hidden')
	.css('height','354px')
	.after('<a href="javascript:void(0);" id="portfolioleftarrow"><span>scroll left</span></a><a href="javascript:void(0);" id="portfoliorightarrow"><span>scroll right</span></a>'+indicatorHTML);
	
	// bind to buttons
	$('#portfolioleftarrow').click(function(){	
		leftQueue++;
		slideLeft();
	});
	
	$('#portfoliorightarrow').click(function(){
		rightQueue++;
		slideRight();
	});	
	
	// initiate fancybox
	$("a.screenshotlink")
	.prepend('<img src="/images/portfolio/fancyBox-origImg.gif" alt="screenshot link" />')
	.fancybox({
		'padding': 0,
		'imageScale': false,
		'centerOnScroll': false,
		'zoomSpeedIn': 400,
		'zoomSpeedOut': 400,
		'easingIn': 'easeOutElastic'
	});
	
	// finlalise layout
	$('.portfolioindicator:first').css({
		'background-color':'#7c9900',
		'border-color':'#7c9900'
    });
	$('.portfolioitem h3')
	.css('padding-top','14px');
	$('.portfolioitem:gt(0)')
	.css('position','absolute')
	.css('left','921px');
	$('.portfolioitem:first')
	.css('position','absolute')
	.css('left','96px');
	
}

$(function () {
	$('.mainMenu li')
		.removeClass('menuLink')
		.find('a')
		.append('<span class="hover" />').each(function () {
				var $span = $('> span.hover', this).css('opacity', 0);
				$(this).hover(function () {
					// on hover
					$span.stop().fadeTo(400, 1);
				}, function () {
					// off hover
					$span.stop().fadeTo(400, 0);
				});
				$(this).click(function () {				
					// if possible, hijack the href request
					var myURL = $(this).attr('href');
					try 
					{	
						myXhr = $.ajax();
						delete myXhr;
						
						// swap tabs
						tabSwap($('body').attr('class'),$(this).attr('class'));
						
						// add history to browser and load page
						$.history.add($(this).attr('class'));
						loadPage($(this).attr('class'));
						
						// stop here so link action doesn't take place
						return false;
					
					}
					catch(err)
					{
					// execute as normal
					delete myXhr;
					}
					
				});
			});
});

function tabSwap(currTab, newTab) {
	// temporarily set the current page to hover state for fade out to work					
	var $currLink = 'a.'+currTab;
	$('>span:eq(1)', $currLink).css('opacity', 1);
	
	// change selected class of body
	$('body').removeClass();
	$('>span:eq(1)', $currLink).fadeTo(400, 0);
	$('body').addClass(newTab);
}

function loadPage(page) {
	//generate timestamp to avoid caching
	var timestamp = new Date().getTime().toString();
	
	// do page transition in ajax rather than page change
	pItem = 0;
	var myRE = /pItem|-|portfolio/g;
	
	if (page.indexOf('portfolio') != -1) {
		pItem = page.replace(myRE, '') || 0;
		page = 'portfolio';
	}
	
	if (page == 'blog') {
		blogLink = '/blog/';
		page = 'blog';
	} else if (page.indexOf('blog-') != -1) {
		blogLink = page.replace('blog-http://www.webpoint0.com','');
		page = 'blog';
	}
	
	if (page == 'home') {
		var myURL = '/index.php';
	} else if (page == 'blog') {
		var myURL = blogLink;
	} else {
		var myURL = '/' + page + '.html';
	}
	
	// cover current content with loader
	$('#mainContent').prepend('<div class="loader" style="-moz-opacity: 0.8; opacity: 0.8;"></div>');
	
	$('#mainContent').load(myURL+' #xhrHolder', 'ts='+timestamp, function(responseText, textStatus, XMLHttpRequest){
		
		// manage portfolio
		if (page == 'portfolio') {
			if (pItem > 0) {
				$('.portfolioitems').prepend($('.portfolioitem:eq('+pItem+')'));
			}
			layoutPortfolio();
		} 
		
		// hijack the blog if that's what we are looking at
		if (page == 'blog') {
			hijackBlog();	
		}
		
		// hijack the form if it's the contact page
		if (page == 'contact') {
			hijackContact();
			Recaptcha.create("6Le5fLwSAAAAAOH0kYdo3TRxBBPdWwML6Jbk6tyr",
			"recaptcha_div", {
			theme: "red"
			});
		}
		
		// add the ajax function to any in page site links we can find
		$('.ajaxlink').click(function () {			
			// if possible, hijack the href request
			var myURL = $(this).attr('href');
			try 
			{	
				myXhr = $.ajax();
				delete myXhr;
				
				// swap tabs and add history to browser
				if ($(this).attr('rel').indexOf('portfolio') != -1) {
					tabSwap($('body').attr('rel'),'portfolio');
					$.history.add('portfolio');
				} else if ($(this).attr('rel').indexOf('blog-') != -1) {
					tabSwap($('body').attr('rel'),'blog');
					$.history.add($(this).attr('rel').replace('blog-http://www.webpoint0.com','').replace('/','').replace('/','-'));
				} else {
					tabSwap($('body').attr('rel'),$(this).attr('rel'));
					$.history.add($(this).attr('rel'));
				}
				
				// load page
				loadPage($(this).attr('rel'));
				
				// stop here so link action doesn't take place
				return false;
			}
			catch(err)
			{
			// execute as normal
			delete myXhr;
			}
		});
		
		// record page view
		if (textStatus == 'success') {
			try {
				var pageTracker = _gat._getTracker("UA-9580968-1");
				pageTracker._trackPageview(myURL);
			} catch(err) {}
		}
		
		// remove loader
		$('.mainContent').animate({
			height: $('#xhrHolder').height()
		}, 600, 'easeOutBounce');
		$('.loader').remove();
	});
}

$(function() {
		   
	/**
	 * The 'history' and 'historyadd' events can be attached to window to allow for global events
	 */
	$(window).history(function(e, hash) {
		if (hash.indexOf('pItem') == -1) {
			if(hash == '') {
				hash = 'home';
			}
			if (hash.indexOf('blog-') != -1) {
				tabSwap($('body').attr('class'),'blog');
				loadPage(hash.replace('-','/').replace('blog-','blog-http://www.webpoint0.com/blog/'));
			} else {
				tabSwap($('body').attr('class'),hash);
				loadPage(hash);
			}
		}
	});
	
	/**
	 * Use getCurrent() function to get the hash for the initial load or if the user refreshes the page
	 */
	var initialHash = $.history.getCurrent();
	if(initialHash == '') {
		initialHash = window.location.pathname.replace('/','').replace('.html','').replace('.php','');
		if ((initialHash == 'index') || (initialHash == '')) {
			initialHash = 'home';
		}
		if (initialHash == 'blog/') {
			if (window.location.search != '') {
				initialHash = 'blog-'+window.location.search;
			} else {
				initialHash = 'blog';
			}
			location.hash = initialHash;
        	if ($.browser.msie) {
				var iframe = $('<iframe style="display:none" src="javascript:false;"></iframe>').prependTo('body')[0];
				var iframedoc = iframe.contentWindow.document;
				iframedoc.open();
				iframedoc.close();
				iframedoc.location.hash=initialHash;
				currentHash = iframedoc.location.hash;
			}
		}
	}
	
	// manage portfolio options
	if (initialHash.indexOf('pItem') != -1) {
		initialHash += '-portfolio';
	}
	
	$('html').css('overflow-y','scroll');
	$('body').removeClass();
	$('body').addClass(initialHash.replace(/pItem.-/,''));
	loadPage(initialHash.replace('blog-','blog-http://www.webpoint0.com/blog/'));
});

document.write('<style type="text/css" media="screen">\n');
document.write('.mainContent {\n');
document.write('height: 0;\n');
document.write('}\n');
document.write('</style>\n');