var _LAST = "";

$.ajaxSetup ({  
	cache: false  
});

var isValidEmailAddress = function(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

var convertHRefToID = function( href ) {
	var id = href;
	if( id.indexOf("://") > 0 ) {
		id = id.substring( id.indexOf("/", id.indexOf("://") + 3) );
	}
	if( id.match("^/") == "/" ) { id = id.substr(1); }
	if( id.match(".html$") == ".html" ) { id = id.substr(0, id.lastIndexOf(".html") ) }
	return id.replace(/^\s+|\s+$/g,"");
}

var convertIDToHRef = function( id ) {
	var href = id.replace(/^\s+|\s+$/g,"");
	if(href.length > 0) { href = href + ".html" }
	href = "/" + href;
	return href;
}

var setMenuItemSelected = function( id ) {
	$('ul.menu li a').removeClass('selected');
	$('ul.menu li a').data('selected','false');
	$('ul.menu li a#' + id + '-menu-item').addClass('selected');
	$('ul.menu li a#' + id + '-menu-item').data('selected','true');
}

var loadTab = function( href, id , bAnimate, bForce) {
	bAnimate = typeof(bAnimate) != 'undefined' ? bAnimate : true;
	bForce = typeof(bForce) != 'undefined' ? bForce : true;
	if(href == null) { href = convertIDToHRef(id); }
	if(id == null) { id = convertHRefToID(href); }
	if(_LAST != id || bForce) {
		$.ajax({  
			url: href,  
			type: "GET",  
			dataType: "html",
			data: "",
			complete: function(res, status) {
				if ( status === "success" || status === "notmodified" ) {
					try { _gat._getTracker("UA-13116384-1")._trackPageview(convertIDToHRef(id)); } catch(err) { }
					if(id.replace(/^\s+|\s+$/g,"").length == 0) { window.location.hash = ""; _LAST = ""; }
					else { window.location.hash = id; _LAST = id; }
					setMenuItemSelected(id);
					if(bAnimate) {
						$('#inner-panel').html(jQuery("<div>").append(res.responseText.replace(/<script(.|\s)*?\/script>/gi, "")).find('div.container'));
						$('#inner-panel').findReplaceLinks();
					} else {
						$('#inner-panel').html(jQuery("<div>").append(res.responseText.replace(/<script(.|\s)*?\/script>/gi, "")).find('div.container'));
						$('#inner-panel').findReplaceLinks();
					}
					return false;
				}
			}
		});
	}
}

var loadTabFromHRef = function( href ) {
	loadTab(href, null, true, false);
}

var loadTabFromID = function( id ) {
	loadTab(null, id, true, false);
}

$.fn.exists = function(){return $(this).length>0;}

$.fn.convertLinkForAJAX = function() {
	var href = $(this).attr('href');
//	$(this).attr('href', '');
	$(this).removeClass('internal');
	$(this).addClass('ajax');
	$(this).click( function(){
		loadTabFromHRef(href);
		$('a.ajax').blur();
		return false;
	});
}

$.fn.setupContactForm = function() {
	$('form#contact-form').attr('action', '');
	
	$('form#contact-form .button').click(function() {
		$('form#contact-form label.error').hide();
		
		var name = $('form#contact-form input#name').val().replace(/^\s+|\s+$/g,"");  
		if (name == "") {
			$('form#contact-form label#name_error').stop().fadeIn(500);  
			$('form#contact-form input#name').focus();  
			return false;  
		}

		var email = $('form#contact-form input#email').val().replace(/^\s+|\s+$/g,"");  
		if (email == "" || !isValidEmailAddress(email)) {  
			$('form#contact-form label#email_error').stop().fadeIn(500);  
			$('form#contact-form input#email').focus();  
			return false;  
		}

		var subject = $('form#contact-form input#subject').val().replace(/^\s+|\s+$/g,"");  
		var message = $('form#contact-form textarea#message').val().replace(/^\s+|\s+$/g,"");  
		var verify = $('form#contact-form input#verify').val().replace(/^\s+|\s+$/g,"");  
		if (verify == "") {
			$('form#contact-form label#verify_error').stop().fadeIn(500);  
			$('form#contact-form input#verify').focus();  
			return false;  
		} 
		
		$('div#contact').stop().fadeOut(1000, function() {
			var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message + '&verify=' + verify;
			$.ajax({  
				type: "POST",  
				url: "/contact-bradley-it.html",  
				data: dataString,
				success: function(msg){
					$('div#contact').hide();
					$('#contact').html($(msg).find("#contact").html());
					if ($('form#contact-form').exists()) {
						$('div#contact').setupContactForm();
					}
					$('div#contact').stop().fadeIn(1000);
				}
			});
		});
		return false;  
	});
}

$.fn.blurLink = function() {
	if (!$(this).hasClass('selected')) {
		$(this).find('span.blur').stop().fadeTo(750, 1);
		$(this).find('span.focus').stop().fadeTo(750, 0);
	} else {
		$(this).find('span.blur').stop().fadeTo(0, 1);
		$(this).find('span.focus').stop().fadeTo(0, 0);
	}
}

$.fn.focusLink = function() {
	if (!$(this).hasClass('selected')) {
		$(this).find('span.blur').stop().fadeTo(250, 0);
		$(this).find('span.focus').stop().fadeTo(250, 1);
	} else {
		$(this).find('span.blur').stop().fadeTo(0, 0);
		$(this).find('span.focus').stop().fadeTo(0, 1);
	}
}

$.fn.setupFadingImageLink = function () {
	$(this).css('background-image', 'none');
	$(this).html('<span class="blur"></span><span class="focus"></span>');
	$(this).hover(
		function() {
			$(this).data('hover','true');
			if($(this).data('focus')!='true') { $(this).focusLink(); }
		},
		function() {
			$(this).data('hover','false');
			if($(this).data('focus')!='true') { $(this).blurLink(); }
		}
	);
	$(this).focusout(
		function() {
			$(this).data('focus','false');
			if($(this).data('hover')!='true') { $(this).blurLink(); }
		}
	);
	$(this).focusin(
		function() {
			$(this).data('focus','true');
			if($(this).data('hover')!='true') { $(this).focusLink(); }
		}
	);
	$(this).click(function(){
		$(this).find('span.blur').stop().fadeTo(0, 0);
		$(this).find('span.focus').stop().fadeTo(0, 1);
	});
}

$.fn.findReplaceLinks = function() {
    $('a.internal', this).each( function() {
		$(this).convertLinkForAJAX();
	});
	$('a.image-link', this).each( function() {
		$(this).removeClass('image-link');
		$(this).setupFadingImageLink();
	});
	$('div#contact').setupContactForm();
}

$(document).ready(function() {
						   
	var id = convertHRefToID(window.location.pathname);

	if(id != "") {
		window.location = window.location.protocol + "//" + window.location.host + "/#" + id;
		return false;
	}
	
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(loadTabFromID);
	
	// set onlick event for buttons
	$("a[rel='history']").click(function(){
		// 
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		// hash don't contain "#", "?"
		$.historyLoad(hash);
		return false;
	});
	
	$(this).findReplaceLinks();
	
	var initialTab = window.location.hash.replace('#','').replace(/^\s+|\s+$/g,"");
	loadTab(null, initialTab, false, true);
});
