// -----------------------------------------------------------------------------
// one2edit External - JavaScript
// -----------------------------------------------------------------------------

// one2edit specific
var one2edit = (function() {
	var _application = document.getElementById('one2edit');
	
	if (!_application) {
		throw new Error('`#one2edit` was not found!');
	}
	
	var _getClipboardDataSupported = 1;
	var _promptOnWindowClose = 0;
	var _mouseWheelNotifier = 1;
	var _browser = {
		mz: /Gecko\/?\d+/.test(navigator.userAgent),
		ie: (/MSIE/.test(navigator.userAgent) && window.clipboardData),
		sf: /AppleWebKit/.test(navigator.userAgent),
		op: window.opera ? true : false
	};
	
	// browser that doesn't support any clipboard functions
	if (_browser.sf || _browser.op || _browser.mz) {
		_getClipboardDataSupported = 0;
	}
	
	// -----------------------------------------------------------------------------
	// Window Event Handler
	// -----------------------------------------------------------------------------
	
	/**
	 * window.onbefore event-handler
	 * could overwritten in the html file
	 */
	window.onbeforeunload = function() {
		if (one2edit.promptOnWindowClose()) {
			// ::bug:: firefox fires this event twice if it closed trough tab
			//one2edit.promptOnWindowClose(0);
			return 'There is an active on2edit-Session. \n'
				+ 'If you close this window, unsaved changes in one2edit are lost.';
		}
	};
	
	
	// -----------------------------------------------------------------------------
	// Windows Firefox Hotfix
	// -----------------------------------------------------------------------------
	// If the Tabbar shown the first time in Firefox, the Flash-Content resizes not
	// to the correct height. This 2 Event-Handler should fix this problem, but one
	// bug remain - if the Tabbar hidden again trough closing all other Tabs, the
	// Flash-Content resizes not correctly - again :(
	
	if (_browser.mz) {
		/**
		 * window.onfocus event-handler
		 */
		window.addEventListener('focus', function() {
			if (window.innerHeight < _application.offsetHeight) {
				_application.height = window.innerHeight;
			}
		}, true);
		
		/**
		 * window.onresize event-handler
		 */
		window.addEventListener('resize', function() {
			_application.height = '100%';
		}, true);
	}
	// -----------------------------------------------------------------------------	
	
	
	return {
		
		/**
		 * trigger flash to logout
		 */
		doLogout: function() {
			_application.onLogout();
		},
		
		/**
		 * user logout handler
		 */
		logout: function() {
			// ::todo:: handler user logout
		},
        
        /**
		 * simple editor help button handler
		 */
        help: function() {
           // ::todo:: handler user logout 
        },
        
		/**
		 * get/set window close confirmation
		 */
		promptOnWindowClose: function(value) {
			//console.info('one2edit/promptOnWindowClose', value);
			if (typeof value == 'undefined') {
				return _promptOnWindowClose;
			}
			else _promptOnWindowClose = value;
		},
		
		/**
		 * OSX-Fix for mousewheel-handling
		 */
		mouseWheelNotifier: (function()
		{
			if (!(/Mac(intosh)?/i.test(navigator.userAgent)) && _mouseWheelNotifier) {
				return;
			}
			
			var eventName = (window.onmousewheel === null || window.opera)
				? 'mousewheel'
				: 'DOMMouseScroll';
			
			var eventHandler = function(event)
			{
				var deltaX = 0;
				var deltaY = 0;
				
				event = event || window.event;
				
				//var asd = [];
				//for(var name in event) {
				//	asd.push('[' + name + ': ' + event[name] + ']');
				//}
				//_application.trace('wheel', event.wheelDelta, asd.join(', '));
				
				// Safari/Opera
				if ('wheelDelta' in event || 'wheelDeltaY' in event)
				{
					
					if('wheelDeltaY' in event) {
						deltaY = event.wheelDeltaY/12;
					}
					else if('wheelDelta' in event) {
						deltaY = event.wheelDelta/12;
					}
					
					if('wheelDeltaX' in event) {
						deltaX = event.wheelDeltaX/12;
					}
					
					if(window.opera) {
						deltaY = -deltaY;
						deltaX = -deltaX;
					}
				}
				// Mozilla
				else if ('detail' in event) {
					//_application.trace('event.detail:', event.detail, event.axis, event.VERTICAL_AXIS, event.HORIZONTAL_AXIS);
					switch('axis' in event ? event.axis : false) {
						default:
						case event.VERTICAL_AXIS:
							deltaY = -event.detail;
							break;
						case event.HORIZONTAL_AXIS:
							deltaX = -event.detail;
							break;
					}
				}
				
				// send to application
				if ((deltaY != 0 || deltaX != 0) && typeof _application.onMouseWheel != 'undefined')
					_application.onMouseWheel(deltaY, deltaX);
				
				//console.info('Event:' + eventName + '.delta', delta);
			};
			
			window.addEventListener(eventName, eventHandler, false);
			
			/**
			 * get/set mouse wheel notifier
			 */
			return function(value) {
				//console.info('one2edit/mouseWheelNotifier', value);
				if (typeof value == 'undefined') {
					return _mouseWheelNotifier;
				}
				else _mouseWheelNotifier = value;
			};
		})(),
		
		/**
		 * get the content of the clipboard (ie & moz only)
		 */
		getClipboardData: function()
		{
			var result = '';
			
			if (!_getClipboardDataSupported) {
				return;
			}
			
			if (_browser.ie) {
				result = window.clipboardData.getData('Text');
			}
			/*
			// Mozilla
			else if (_browser.mz) {
				try {
					netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
					var clipboardId = Components.interfaces.nsIClipboard;
					var clipboard = Components.classes['@mozilla.org/widget/clipboard;1'].getService(clipboardId);
					var clipboardString = Components.classes['@mozilla.org/supports-string;1'].createInstance(Components.interfaces.nsISupportsString);
					
					netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
					var transfer = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
					transfer.addDataFlavor('text/unicode');
					clipboard.getData(transfer, clipboardId.kGlobalClipboard);
					
					var str = new Object();
					var strLength = new Object();
					transfer.getTransferData('text/unicode', str, strLength);
					str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
					
					result = str.data.substring(0, strLength.value / 2);
				}
				catch (e) {
					if (typeof console != 'undefined')
						console.error(e.message);
					
					var confirmation = confirm('Your current Internet Security settings do not allow data pasting '
						+ 'to clipboard. Do you want to learn more about enabling data pasting '
						+ 'to clipboard in your browser?'
					);
					
					if (confirmation) {
						window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html');
					}
					
					// -more info: http://www.mozilla.org/editor/midasdemo/securityprefs.html
					// Ihre aktuellen Sicherheitseinstellungen erlauben es nicht den Inhalt 
					// Ihrer Zwischenablage auszulesen. Möchten Sie mehr darüber erfahren wie 
					// Sie das Auslesen Ihrer Zwischenablage in Ihrem Browser aktivieren?'
				}
			}
			*/
			return result;
		}
	};
})();