/**
 * USAGE
 * 	ViewHistory.addHistoryEventListener('abc', function(event) {
 * 		alert(event.data);
 * 	}, false);
 * */

var ViewHistory = (function() {
	var HASH_EVENT_PRFEX = 'app-center-hash-event';
	var _iframe = null;
	var _last_value_ = null;
	
	function getLocation(iframe) {
		if (contentAPI && contentAPI.getLocation) {
			return contentAPI.getLocation(iframe);
		} else {
			return iframe.contentWindow.document.location.toString();
		}
	}
	
	function setLocation(iframe, src) {
		if (contentAPI && contentAPI.setLocation) {
			contentAPI.setLocation(iframe, src);
		} else {
			iframe.contentWindow.document.location = src;
		}
	}
	
	function _onHistoryChange(event) {
		var url = getLocation(event.target);
		var idx = url.indexOf('?');
		if (idx == -1) {
			return;
		}
		
		var hash = url.substring(idx + 1);
		
		if (_last_value_ == hash) {
			_last_value_ = null;
			return;
		}
		_last_value_ = null;
		
		idx = hash.indexOf('-');
		if (idx > -1) {
			// break hash into two parts, first is event name, and second is data
			dispatchHashEvent(hash.substring(0, idx), hash.substring(idx + 1));
		} else {
			dispatchHashEvent(hash);
		}
	}
	
	function dispatchHashEvent(eventName, data) {
		var event = document.createEvent('Event');
		event.initEvent(HASH_EVENT_PRFEX + eventName, true, true);
		event.data = !!data ? data : null;
		window.dispatchEvent(event);
	}
	
	function initHistory(hash) {
		if (_iframe) {
			return;
		}
		
		_iframe = document.createElement('iframe');
		_iframe.src = 'about:blank?' + hash;
		document.body.appendChild(_iframe);
		$(_iframe).bind("load", _onHistoryChange);
	}
	
	return {
		removeHistoryEventListener: function(eventName, callback, useCapture) {
			if (eventName.indexOf('-') > -1) {
				throw new Error('"-" is and reserved char!');
			}
			
			window.removeEventListener(HASH_EVENT_PRFEX + eventName, callback, useCapture);
		},
		
		addHistoryEventListener: function(eventName, callback, useCapture) {
			if (eventName.indexOf('-') > -1) {
				throw new Error('"-" is and reserved char!');
			}
			window.addEventListener(HASH_EVENT_PRFEX + eventName, callback, useCapture);
		},
		
		changeHistory: function(hash) {
			initHistory(hash);
			
			// change hash and skip event triggered by the hash changing
			var url = getLocation(_iframe);
			
			var idx = url.indexOf('?');
			if (idx == -1) {
				setLocation(_iframe, url + '?' + hash);
			} else {
				setLocation(_iframe, url.substring(0, idx + 1) + hash)
			}
		},
		
		muteChangeHistory: function(hash) {
			_last_value_ = hash;
			this.changeHistory(hash);
		}
	};
})();
