// Class: lime._backend.html5.HTML5Window

var $global = typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this

$global.Object.defineProperty(exports, "__esModule", {value: true});

var __map_reserved = {};

// Imports

var $hxClasses = require("./../../../hxClasses_stub").default;
var $import = require("./../../../import_stub").default;
var $bind = require("./../../../bind_stub").default;
function js_Browser() {return require("./../../../js/Browser");}
function Std() {return require("./../../../Std");}
function lime_system_System() {return require("./../../../lime/system/System");}
function lime_system_Clipboard() {return require("./../../../lime/system/Clipboard");}
function haxe_Timer() {return require("./../../../haxe/Timer");}
function lime_ui_Joystick() {return require("./../../../lime/ui/Joystick");}
function lime_ui_Gamepad() {return require("./../../../lime/ui/Gamepad");}
function StringTools() {return require("./../../../StringTools");}
function lime_ui_Touch() {return require("./../../../lime/ui/Touch");}
function EReg() {return require("./../../../EReg");}
function lime_graphics_utils_ImageCanvasUtil() {return require("./../../../lime/graphics/utils/ImageCanvasUtil");}
function List() {return require("./../../../List");}
function haxe_ds_IntMap() {return require("./../../../haxe/ds/IntMap");}
function Reflect() {return require("./../../../Reflect");}

// Constructor

var HTML5Window = function(parent) {
	this.unusedTouchesPool = new (List().default)();
	this.scale = 1.0;
	this.currentTouches = new (haxe_ds_IntMap().default)();
	this.parent = parent;
	if(parent.config != null && (Reflect().default).hasField(parent.config,"element")) {
		this.element = parent.config.element;
	}
	if(parent.config != null && (Reflect().default).hasField(parent.config,"renderer")) {
		this.renderType = parent.config.renderer;
	}
	if(parent.config != null && (Reflect().default).hasField(parent.config,"allowHighDPI") && parent.config.allowHighDPI && this.renderType != "dom") {
		this.scale = (js_Browser().default).get_window().devicePixelRatio;
	}
	parent.__scale = this.scale;
	this.cacheMouseX = 0;
	this.cacheMouseY = 0;
}

// Meta

HTML5Window.__name__ = ["lime","_backend","html5","HTML5Window"];
HTML5Window.prototype = {
	alert: function(message,title) {
		if(message != null) {
			(js_Browser().default).alert(message);
		}
	},
	close: function() {
		this.parent.application.removeWindow(this.parent);
	},
	create: function(application) {
		this.setWidth = this.parent.get_width();
		this.setHeight = this.parent.get_height();
		this.parent.id = HTML5Window.windowID++;
		if((Std().default)["is"](this.element,HTMLCanvasElement)) {
			this.canvas = this.element;
		} else if(this.renderType == "dom") {
			this.div = (js_Browser().default).get_document().createElement("div");
		} else {
			this.canvas = (js_Browser().default).get_document().createElement("canvas");
		}
		if(this.canvas != null) {
			var style = this.canvas.style;
			style.setProperty("-webkit-transform","translateZ(0)",null);
			style.setProperty("transform","translateZ(0)",null);
		} else if(this.div != null) {
			var style1 = this.div.style;
			style1.setProperty("-webkit-transform","translate3D(0,0,0)",null);
			style1.setProperty("transform","translate3D(0,0,0)",null);
			style1.position = "relative";
			style1.overflow = "hidden";
			style1.setProperty("-webkit-user-select","none",null);
			style1.setProperty("-moz-user-select","none",null);
			style1.setProperty("-ms-user-select","none",null);
			style1.setProperty("-o-user-select","none",null);
		}
		if(this.parent.get_width() == 0 && this.parent.get_height() == 0) {
			if(this.element != null) {
				this.parent.set_width(this.element.clientWidth);
				this.parent.set_height(this.element.clientHeight);
			} else {
				this.parent.set_width((js_Browser().default).get_window().innerWidth);
				this.parent.set_height((js_Browser().default).get_window().innerHeight);
			}
			this.cacheElementWidth = this.parent.get_width();
			this.cacheElementHeight = this.parent.get_height();
			this.resizeElement = true;
		}
		if(this.canvas != null) {
			var tmp = this.parent.get_width() * this.scale;
			this.canvas.width = Math.round(tmp);
			var tmp1 = this.parent.get_height() * this.scale;
			this.canvas.height = Math.round(tmp1);
			var tmp2 = this.parent.get_width();
			this.canvas.style.width = tmp2 + "px";
			var tmp3 = this.parent.get_height();
			this.canvas.style.height = tmp3 + "px";
		} else {
			var tmp4 = this.parent.get_width();
			this.div.style.width = tmp4 + "px";
			var tmp5 = this.parent.get_height();
			this.div.style.height = tmp5 + "px";
		}
		this.updateSize();
		if(this.element != null) {
			if(this.canvas != null) {
				if(this.element != this.canvas) {
					this.element.appendChild(this.canvas);
				}
			} else {
				this.element.appendChild(this.div);
			}
			var events = ["mousedown","mouseenter","mouseleave","mousemove","mouseup","wheel"];
			var _g = 0;
			while(_g < events.length) {
				var event = events[_g];
				++_g;
				this.element.addEventListener(event,$bind(this,this.handleMouseEvent),true);
			}
			(js_Browser().default).get_document().addEventListener("dragstart",function(e) {
				if(e.target.nodeName.toLowerCase() == "img") {
					e.preventDefault();
					return false;
				}
				return true;
			},false);
			this.element.addEventListener("contextmenu",$bind(this,this.handleContextMenuEvent),true);
			this.element.addEventListener("touchstart",$bind(this,this.handleTouchEvent),true);
			this.element.addEventListener("touchmove",$bind(this,this.handleTouchEvent),true);
			this.element.addEventListener("touchend",$bind(this,this.handleTouchEvent),true);
			this.element.addEventListener("touchcancel",$bind(this,this.handleTouchEvent),true);
			this.element.addEventListener("gamepadconnected",$bind(this,this.handleGamepadEvent),true);
			this.element.addEventListener("gamepaddisconnected",$bind(this,this.handleGamepadEvent),true);
		}
	},
	focus: function() {
	},
	getDisplay: function() {
		return (lime_system_System().default).getDisplay(0);
	},
	getDisplayMode: function() {
		return (lime_system_System().default).getDisplay(0).currentMode;
	},
	setDisplayMode: function(value) {
		return value;
	},
	getEnableTextEvents: function() {
		return this.enableTextEvents;
	},
	handleContextMenuEvent: function(event) {
		if(this.parent.onMouseUp.canceled) {
			event.preventDefault();
		}
	},
	handleCutOrCopyEvent: function(event) {
		event.clipboardData.setData("text/plain",(lime_system_Clipboard().default).get_text());
		event.preventDefault();
	},
	handleFocusEvent: function(event) {
		var _gthis = this;
		if(this.enableTextEvents) {
			if(event.relatedTarget == null || this.isDescendent(event.relatedTarget)) {
				(haxe_Timer().default).delay(function() {
					if(_gthis.enableTextEvents) {
						HTML5Window.textInput.focus();
					}
				},20);
			}
		}
	},
	handleFullscreenEvent: function(event) {
		var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement;
		if(fullscreenElement != null) {
			this.isFullscreen = true;
			this.parent.__fullscreen = true;
			if(this.requestedFullscreen) {
				this.requestedFullscreen = false;
				this.parent.onFullscreen.dispatch();
			}
		} else {
			this.isFullscreen = false;
			this.parent.__fullscreen = false;
			var changeEvents = ["fullscreenchange","mozfullscreenchange","webkitfullscreenchange","MSFullscreenChange"];
			var errorEvents = ["fullscreenerror","mozfullscreenerror","webkitfullscreenerror","MSFullscreenError"];
			var _g1 = 0;
			var _g = changeEvents.length;
			while(_g1 < _g) {
				var i = _g1++;
				(js_Browser().default).get_document().removeEventListener(changeEvents[i],$bind(this,this.handleFullscreenEvent),false);
				(js_Browser().default).get_document().removeEventListener(errorEvents[i],$bind(this,this.handleFullscreenEvent),false);
			}
		}
	},
	handleGamepadEvent: function(event) {
		var _g = event.type;
		switch(_g) {
		case "gamepadconnected":
			(lime_ui_Joystick().default).__connect(event.gamepad.index);
			if(event.gamepad.mapping == "standard") {
				(lime_ui_Gamepad().default).__connect(event.gamepad.index);
			}
			break;
		case "gamepaddisconnected":
			(lime_ui_Joystick().default).__disconnect(event.gamepad.index);
			(lime_ui_Gamepad().default).__disconnect(event.gamepad.index);
			break;
		default:
		}
	},
	handleInputEvent: function(event) {
		if(HTML5Window.textInput.value != HTML5Window.dummyCharacter) {
			var value = (StringTools().default).replace(HTML5Window.textInput.value,HTML5Window.dummyCharacter,"");
			if(value.length > 0) {
				this.parent.onTextInput.dispatch(value);
			}
			HTML5Window.textInput.value = HTML5Window.dummyCharacter;
		}
	},
	handleMouseEvent: function(event) {
		var x = 0.0;
		var y = 0.0;
		if(event.type != "wheel") {
			if(this.element != null) {
				if(this.canvas != null) {
					var rect = this.canvas.getBoundingClientRect();
					x = (event.clientX - rect.left) * (this.parent.get_width() / rect.width);
					y = (event.clientY - rect.top) * (this.parent.get_height() / rect.height);
				} else if(this.div != null) {
					var rect1 = this.div.getBoundingClientRect();
					x = event.clientX - rect1.left;
					y = event.clientY - rect1.top;
				} else {
					var rect2 = this.element.getBoundingClientRect();
					x = (event.clientX - rect2.left) * (this.parent.get_width() / rect2.width);
					y = (event.clientY - rect2.top) * (this.parent.get_height() / rect2.height);
				}
			} else {
				x = event.clientX;
				y = event.clientY;
			}
			var _g = event.type;
			switch(_g) {
			case "mousedown":
				this.parent.onMouseDown.dispatch(x,y,event.button);
				if(this.parent.onMouseDown.canceled) {
					event.preventDefault();
				}
				break;
			case "mouseenter":
				if(event.target == this.element) {
					this.parent.onEnter.dispatch();
					if(this.parent.onEnter.canceled) {
						event.preventDefault();
					}
				}
				break;
			case "mouseleave":
				if(event.target == this.element) {
					this.parent.onLeave.dispatch();
					if(this.parent.onLeave.canceled) {
						event.preventDefault();
					}
				}
				break;
			case "mousemove":
				if(x != this.cacheMouseX || y != this.cacheMouseY) {
					this.parent.onMouseMove.dispatch(x,y);
					this.parent.onMouseMoveRelative.dispatch(x - this.cacheMouseX,y - this.cacheMouseY);
					if(this.parent.onMouseMove.canceled || this.parent.onMouseMoveRelative.canceled) {
						event.preventDefault();
					}
				}
				break;
			case "mouseup":
				this.parent.onMouseUp.dispatch(x,y,event.button);
				if(this.parent.onMouseUp.canceled) {
					event.preventDefault();
				}
				break;
			default:
			}
			this.cacheMouseX = x;
			this.cacheMouseY = y;
		} else {
			this.parent.onMouseWheel.dispatch(event.deltaX,-event.deltaY);
			if(this.parent.onMouseWheel.canceled) {
				event.preventDefault();
			}
		}
	},
	handlePasteEvent: function(event) {
		if(event.clipboardData.types.indexOf("text/plain") > -1) {
			var text = event.clipboardData.getData("text/plain");
			(lime_system_Clipboard().default).set_text(text);
			if(this.enableTextEvents) {
				this.parent.onTextInput.dispatch(text);
			}
			event.preventDefault();
		}
	},
	handleResizeEvent: function(event) {
		this.primaryTouch = null;
		this.updateSize();
	},
	handleTouchEvent: function(event) {
		event.preventDefault();
		var rect = null;
		if(this.element != null) {
			if(this.canvas != null) {
				rect = this.canvas.getBoundingClientRect();
			} else if(this.div != null) {
				rect = this.div.getBoundingClientRect();
			} else {
				rect = this.element.getBoundingClientRect();
			}
		}
		var windowWidth = this.setWidth;
		var windowHeight = this.setHeight;
		if(windowWidth == 0 || windowHeight == 0) {
			if(rect != null) {
				windowWidth = rect.width;
				windowHeight = rect.height;
			} else {
				windowWidth = 1;
				windowHeight = 1;
			}
		}
		var touch;
		var x;
		var y;
		var cacheX;
		var cacheY;
		var _g = 0;
		var _g1 = event.changedTouches;
		while(_g < _g1.length) {
			var data = _g1[_g];
			++_g;
			x = 0.0;
			y = 0.0;
			if(rect != null) {
				x = (data.clientX - rect.left) * (windowWidth / rect.width);
				y = (data.clientY - rect.top) * (windowHeight / rect.height);
			} else {
				x = data.clientX;
				y = data.clientY;
			}
			if(event.type == "touchstart") {
				touch = this.unusedTouchesPool.pop();
				if(touch == null) {
					touch = new (lime_ui_Touch().default)(x / windowWidth,y / windowHeight,data.identifier,0,0,data.force,this.parent.id);
				} else {
					touch.x = x / windowWidth;
					touch.y = y / windowHeight;
					touch.id = data.identifier;
					touch.dx = 0;
					touch.dy = 0;
					touch.pressure = data.force;
					touch.device = this.parent.id;
				}
				this.currentTouches.set(data.identifier,touch);
				(lime_ui_Touch().default).onStart.dispatch(touch);
				if(this.primaryTouch == null) {
					this.primaryTouch = touch;
				}
				if(touch == this.primaryTouch) {
					this.parent.onMouseDown.dispatch(x,y,0);
				}
			} else {
				touch = this.currentTouches.get(data.identifier);
				if(touch != null) {
					cacheX = touch.x;
					cacheY = touch.y;
					touch.x = x / windowWidth;
					touch.y = y / windowHeight;
					touch.dx = touch.x - cacheX;
					touch.dy = touch.y - cacheY;
					touch.pressure = data.force;
					var _g2 = event.type;
					switch(_g2) {
					case "touchcancel":
						(lime_ui_Touch().default).onCancel.dispatch(touch);
						this.currentTouches.remove(data.identifier);
						this.unusedTouchesPool.add(touch);
						if(touch == this.primaryTouch) {
							this.primaryTouch = null;
						}
						break;
					case "touchend":
						(lime_ui_Touch().default).onEnd.dispatch(touch);
						this.currentTouches.remove(data.identifier);
						this.unusedTouchesPool.add(touch);
						if(touch == this.primaryTouch) {
							this.parent.onMouseUp.dispatch(x,y,0);
							this.primaryTouch = null;
						}
						break;
					case "touchmove":
						(lime_ui_Touch().default).onMove.dispatch(touch);
						if(touch == this.primaryTouch) {
							this.parent.onMouseMove.dispatch(x,y);
						}
						break;
					default:
					}
				}
			}
		}
	},
	isDescendent: function(node) {
		if(node == this.element) {
			return true;
		}
		while(node != null) {
			if(node.parentNode == this.element) {
				return true;
			}
			node = node.parentNode;
		}
		return false;
	},
	move: function(x,y) {
	},
	resize: function(width,height) {
	},
	setBorderless: function(value) {
		return value;
	},
	setClipboard: function(value) {
		var inputEnabled = this.enableTextEvents;
		this.setEnableTextEvents(true);
		var cacheText = HTML5Window.textInput.value;
		HTML5Window.textInput.value = value;
		HTML5Window.textInput.select();
		if((js_Browser().default).get_document().queryCommandEnabled("copy")) {
			(js_Browser().default).get_document().execCommand("copy");
		}
		HTML5Window.textInput.value = cacheText;
		this.setEnableTextEvents(inputEnabled);
	},
	setEnableTextEvents: function(value) {
		if(value) {
			if(HTML5Window.textInput == null) {
				HTML5Window.textInput = (js_Browser().default).get_document().createElement("input");
				HTML5Window.textInput.type = "text";
				HTML5Window.textInput.style.position = "absolute";
				HTML5Window.textInput.style.opacity = "0";
				HTML5Window.textInput.style.color = "transparent";
				HTML5Window.textInput.value = HTML5Window.dummyCharacter;
				HTML5Window.textInput.autocapitalize = "off";
				HTML5Window.textInput.autocorrect = "off";
				HTML5Window.textInput.autocomplete = "off";
				HTML5Window.textInput.style.left = "0px";
				HTML5Window.textInput.style.top = "50%";
				if(new (EReg().default)("(iPad|iPhone|iPod).*OS 8_","gi").match((js_Browser().default).get_window().navigator.userAgent)) {
					HTML5Window.textInput.style.fontSize = "0px";
					HTML5Window.textInput.style.width = "0px";
					HTML5Window.textInput.style.height = "0px";
				} else {
					HTML5Window.textInput.style.width = "1px";
					HTML5Window.textInput.style.height = "1px";
				}
				HTML5Window.textInput.style.pointerEvents = "none";
				HTML5Window.textInput.style.zIndex = "-10000000";
			}
			if(HTML5Window.textInput.parentNode == null) {
				this.element.appendChild(HTML5Window.textInput);
			}
			if(!this.enableTextEvents) {
				HTML5Window.textInput.addEventListener("input",$bind(this,this.handleInputEvent),true);
				HTML5Window.textInput.addEventListener("blur",$bind(this,this.handleFocusEvent),true);
				HTML5Window.textInput.addEventListener("cut",$bind(this,this.handleCutOrCopyEvent),true);
				HTML5Window.textInput.addEventListener("copy",$bind(this,this.handleCutOrCopyEvent),true);
				HTML5Window.textInput.addEventListener("paste",$bind(this,this.handlePasteEvent),true);
			}
			HTML5Window.textInput.focus();
			HTML5Window.textInput.select();
		} else if(HTML5Window.textInput != null) {
			HTML5Window.textInput.removeEventListener("input",$bind(this,this.handleInputEvent),true);
			HTML5Window.textInput.removeEventListener("blur",$bind(this,this.handleFocusEvent),true);
			HTML5Window.textInput.removeEventListener("cut",$bind(this,this.handleCutOrCopyEvent),true);
			HTML5Window.textInput.removeEventListener("copy",$bind(this,this.handleCutOrCopyEvent),true);
			HTML5Window.textInput.removeEventListener("paste",$bind(this,this.handlePasteEvent),true);
			HTML5Window.textInput.blur();
		}
		return this.enableTextEvents = value;
	},
	setFullscreen: function(value) {
		if(value) {
			if(!this.requestedFullscreen && !this.isFullscreen) {
				this.requestedFullscreen = true;
				if(($_=this.element,$bind($_,$_.requestFullscreen))) {
					document.addEventListener("fullscreenchange",$bind(this,this.handleFullscreenEvent),false);
					document.addEventListener("fullscreenerror",$bind(this,this.handleFullscreenEvent),false);
					this.element.requestFullscreen();
				} else if(this.element.mozRequestFullScreen) {
					document.addEventListener("mozfullscreenchange",$bind(this,this.handleFullscreenEvent),false);
					document.addEventListener("mozfullscreenerror",$bind(this,this.handleFullscreenEvent),false);
					this.element.mozRequestFullScreen();
				} else if(this.element.webkitRequestFullscreen) {
					document.addEventListener("webkitfullscreenchange",$bind(this,this.handleFullscreenEvent),false);
					document.addEventListener("webkitfullscreenerror",$bind(this,this.handleFullscreenEvent),false);
					this.element.webkitRequestFullscreen();
				} else if(this.element.msRequestFullscreen) {
					document.addEventListener("MSFullscreenChange",$bind(this,this.handleFullscreenEvent),false);
					document.addEventListener("MSFullscreenError",$bind(this,this.handleFullscreenEvent),false);
					this.element.msRequestFullscreen();
				}
			}
		} else if(this.isFullscreen) {
			this.requestedFullscreen = false;
			if(document.exitFullscreen) {
				document.exitFullscreen();
			} else if(document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			} else if(document.webkitExitFullscreen) {
				document.webkitExitFullscreen();
			} else if(document.msExitFullscreen) {
				document.msExitFullscreen();
			}
		}
		return value;
	},
	setIcon: function(image) {
		(lime_graphics_utils_ImageCanvasUtil().default).convertToCanvas(image);
		var link = (js_Browser().default).get_document().querySelector("link[rel*='icon']");
		if(link == null) {
			link = (js_Browser().default).get_document().createElement("link");
		}
		link.type = "image/x-icon";
		link.rel = "shortcut icon";
		link.href = image.buffer.get_src().toDataURL("image/x-icon");
		(js_Browser().default).get_document().getElementsByTagName("head")[0].appendChild(link);
	},
	setMaximized: function(value) {
		return false;
	},
	setMinimized: function(value) {
		return false;
	},
	setResizable: function(value) {
		return value;
	},
	setTitle: function(value) {
		if(value != null) {
			(js_Browser().default).get_document().title = value;
		}
		return value;
	},
	updateSize: function() {
		if(!this.parent.__resizable) {
			return;
		}
		var elementWidth;
		var elementHeight;
		if(this.element != null) {
			elementWidth = this.element.clientWidth;
			elementHeight = this.element.clientHeight;
		} else {
			elementWidth = (js_Browser().default).get_window().innerWidth;
			elementHeight = (js_Browser().default).get_window().innerHeight;
		}
		if(elementWidth != this.cacheElementWidth || elementHeight != this.cacheElementHeight) {
			this.cacheElementWidth = elementWidth;
			this.cacheElementHeight = elementHeight;
			var stretch = this.resizeElement || this.setWidth == 0 && this.setHeight == 0;
			if(this.element != null && (this.div == null || this.div != null && stretch)) {
				if(stretch) {
					if(this.parent.get_width() != elementWidth || this.parent.get_height() != elementHeight) {
						this.parent.set_width(elementWidth);
						this.parent.set_height(elementHeight);
						if(this.canvas != null) {
							if(this.element != this.canvas) {
								this.canvas.width = Math.round(elementWidth * this.scale);
								this.canvas.height = Math.round(elementHeight * this.scale);
								this.canvas.style.width = elementWidth + "px";
								this.canvas.style.height = elementHeight + "px";
							}
						} else {
							this.div.style.width = elementWidth + "px";
							this.div.style.height = elementHeight + "px";
						}
						this.parent.onResize.dispatch(elementWidth,elementHeight);
					}
				} else {
					var scaleX = this.setWidth != 0 ? elementWidth / this.setWidth : 1;
					var scaleY = this.setHeight != 0 ? elementHeight / this.setHeight : 1;
					var targetWidth = elementWidth;
					var targetHeight = elementHeight;
					var marginLeft = 0;
					var marginTop = 0;
					if(scaleX < scaleY) {
						targetHeight = Math.floor(this.setHeight * scaleX);
						marginTop = Math.floor((elementHeight - targetHeight) / 2);
					} else {
						targetWidth = Math.floor(this.setWidth * scaleY);
						marginLeft = Math.floor((elementWidth - targetWidth) / 2);
					}
					if(this.canvas != null) {
						if(this.element != this.canvas) {
							this.canvas.style.width = targetWidth + "px";
							this.canvas.style.height = targetHeight + "px";
							this.canvas.style.marginLeft = marginLeft + "px";
							this.canvas.style.marginTop = marginTop + "px";
						}
					} else {
						this.div.style.width = targetWidth + "px";
						this.div.style.height = targetHeight + "px";
						this.div.style.marginLeft = marginLeft + "px";
						this.div.style.marginTop = marginTop + "px";
					}
				}
			}
		}
	}
};
HTML5Window.prototype.__class__ = $hxClasses["lime._backend.html5.HTML5Window"] = HTML5Window;

// Init



// Statics


HTML5Window.dummyCharacter = ""
HTML5Window.windowID = 0

// Export

exports.default = HTML5Window;