	currentState = -1;
	stateHistory = new Array();
	state_prefix = 'mobile_state';
	
	function resetWindowName() {
		if (parent && parent.name) {
			parent.name = '';
		} else {
			window.name = '';
		}
	}
	
	function setWindowName(dataString) {
		if (parent && parent.name) {
			parent.name = dataString;
		} else {
			window.name = dataString;
		}
	}
	
	function changeWindowLocation(currentState){
		if (parent && parent.name) {
			parent.location.replace( parent.location.search + '#' + currentState );
		} else {
			window.location.replace( window.location.search + '#' + currentState );
		}
	}
	
	function loadState() {
		
		var stateData = null;
		var name = (parent && parent.name)? parent.name : window.name;

		if (name.indexOf(state_prefix) != 0) {
			resetWindowName();
			currentState = currentState + 1;
		} else {
		    name = name.substr(state_prefix.length);
			var parts = name.split(' ');
			if (parts.length > 0) {
				currentState = parseInt(parts[0]);
				if (parts.length > 1) {
					stateHistory = parts.slice(1);
				}
			}

			var hash = (parent && parent.name)? parent.location.hash : window.location.hash;
			if (hash != '') {
				var idx = parseInt(hash.substr(1));
				if (idx < stateHistory.length) {
					stateData = stateHistory[idx];
					currentState = idx;
				} else if (idx >= stateHistory.length) {
					currentState = 0;
					stateHistory = new Array();
				}
			} else {
			// new state
				currentState = currentState + 1;
				while (stateHistory.length > currentState) {
					stateHistory.pop();
				}
			}
		}
		// save state
		changeWindowLocation(currentState);

		return stateData;
	}
	
	function saveState(stateData) {
		if (stateHistory.length == 0) {
			stateHistory.push(currentState);
			stateHistory.push(stateData);
			// store data
			setWindowName(state_prefix + stateHistory.join(' '));
		} else {
			if (stateHistory.length <= currentState) {
				stateHistory.push(stateData);
			} else {
				stateHistory[currentState] = stateData;
			}
			// store data
			setWindowName(state_prefix + currentState + ' ' + stateHistory.join(' '));
		}
	}
