<?php

if ( 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] ) && 'true' == $_POST['__do_ajax'] ) {
	header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
	header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
	header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
	header( 'Pragma: no-cache' );

	$action = empty( $_POST['action'] ) ? false : $_POST['action'];

	echo output( $action );
	echo "<pre>";
	var_dump( $_POST );
	echo "</pre>";
	exit;
}

function output( $action = false ) {
	switch ( $action ) {
	case false :
		return 'Original';
	case 'one' :
		return 'The loneliest number';
	case 'two' :
		return 'Can be as bad as one';
	case 'three' :
		return 'Not the mama';
	default :
		return '????';
	}
}

?>
<html>
<head>
<title>pushState()</title>
<script type="text/javascript" src="/wordpress/wp-includes/js/jquery/jquery.js"></script>
<script type="text/javascript">
(function($) {

if ( !window.history.pushState ) {
	return;
}

var baseHref = document.location.href.split( '?' )[0],
    originalHref = document.location.href,
    doAJAX, getState, response;

doAJAX = function( state ) {
	response.load( 'pushstate.php', $.extend( { '__do_ajax' : 'true', '__random' : Math.random() }, state  ) );
};

getState = function( url ) {
	var href, state, queryParams, queryParam;

	href = url.replace( /https?:\/\/.*?(\/.*$)/, '$1' ).split( '?' );

	if ( 'undefined' == typeof href[1] ) {
		href[1] = '__do_ajax=true';
	}

	queryParams = href[1].split( '&' );

	state = { __path: href[0] }; // state object holds the URL's path ...

	// ... and the query parameters
	$.each( queryParams, function( i ) {
		queryParam = queryParams[i].split( '=' );
		state[decodeURIComponent( queryParam[0] )] = decodeURIComponent( queryParam[1] );
	} );

	// state object, query string
	return [ state, '?' + href[1] ];
};


$( function() {
	// Define after onReady so we don't capture original popState event (Is this necessary?  Is there any such event?)
	window.onpopstate = function( event ) {
		var state = event.state ? event.state : getState( document.location.href )[0];

		// do AJAX
		doAJAX( state );
	};

	response = $('#response');
    
	$('ul a').click( function() {
		// This is not the URL you are looking for
		if ( 0 != this.href.indexOf( baseHref ) ) {
			return;
		}

		var state, queryString;

		state = getState( this.href );
		queryString = state[1];
		state = state[0];

		// Update the address
		window.history.pushState( state, $(this).text(), queryString );

		// do AJAX
		doAJAX( state );

		return false;
	} );
} );

})(jQuery);
</script>
</head>
<body>
<ul>
	<li><a href="?action=one&amp;foo=bar">One</a></li>
	<li><a href="?action=two&amp;foo=pub">Two</a></li>
	<li><a href="?action=three&amp;foo=boozeria">Three</a></li>
	<li><a href="http://example.com/">Other</a></li>
</ul>

<p id="response"><?php echo htmlspecialchars( output( empty( $_GET['action'] ) ? false : $_GET['action'] ), ENT_NOQUOTES ); ?></p>
</body>
</html>
