// com.tts.initial.html5.graphicbutton
// HTML4 / HTML5: No differences
define([
    "./button.builder",
    "./accessibility.builder",
    "jquery"
    ], function (
        ButtonBuilder,
        AccessibilityBuilder,
        jq
    ) {

	"use strict";

	/**
	 * @constructor
	 */
	return function (context, metadata) {

		var shellElement,
            button,
            buttonInitialized = false,
            instance,
			hasStageTriggerSupport = true,
            isInAuthoringMode = false,
            isStandardPlayer = context.getPlayerName() === "standard",
            accessibilityTooltip,
            accessibilityTabOrder = metadata.parameters.asNumber("tab-order", -1),
            exludeFromTabControl = metadata.parameters.asBool("exclude-from-tab-control", false),
            accessibilityKey = metadata.parameters.get("accessibility-key", "KeyNone" ),
            accessibilityLocation = metadata.parameters.asNumber( "accessibility-location", 0 ),
            accessibilityPositionX = metadata.parameters.asNumber( "accessibility-position-x", -6 ),
            accessibilityPositionY = metadata.parameters.asNumber( "accessibility-position-y", -6 ),
            pointerUpEventName, pointerDownEventName, pointerMoveEventName, pointerLeaveEventName;

		function initializeButton(shellElement) {
            if( buttonInitialized ){
                return;
            }
            buttonInitialized = true;

            var imageParams = loadImage("button", metadata.parameters.get("bg_image", null));

            initPointerEventNames();

            button = new ButtonBuilder({
                image : imageParams,
                instance: instance,
                caption: ((metadata.parameters.get("caption", false)||"").trim() === "") ? false : metadata.parameters.get("caption", false),
                ariaLabel: ((metadata.parameters.get("aria-label", false)||"").trim() === "") ? false : metadata.parameters.get("aria-label", false)
            }, context, metadata).build();

            shellElement.css({
                "width" : imageParams.width + "px",
                "height" : imageParams.height / 3 + "px"
            })

            shellElement.append( button.getElement() );

            accessibilityTooltip = new AccessibilityBuilder(accessibilityKey, accessibilityLocation, accessibilityPositionX, accessibilityPositionY, context).build();
            if (accessibilityTooltip.getElement()) {
                shellElement.append( accessibilityTooltip.getElement() );
            }

            if (isInAuthoringMode) {
                createAuthoringShield();
            }
        }

        function loadImage(key, image) {
            var result = {};

                if (image) {
                    result.fileNameURL = context.stage.getSharedPath() + image.fileName;
                    result.width = image.width;
                    result.height = image.height;
                }
                else {
                    switch(key){
                        case "button":
                            result.fileNameURL = context.getPath() + "button.png";
                            result.width = 50;
                            result.height = 150;
                            break;
                        default:
                            return null;
                    }
                }

            return result;
        }

        // create an object shield so we are able to select and drag element
		function createAuthoringShield() {
			shellElement.append(jq(document.createElement("div"))
				.css({
					"position": "absolute",
					"left": 0,
					"top": 0,
					"background-color": "#ffffff",
					"opacity": "0.4",
					"width": "100%",
					"height": "100%",
					"z-index": "9999"
				}));
		}

		function unlockNavigation() {
			if (isInAuthoringMode || !hasStageTriggerSupport) {
				return;
			}
			context.stage.trigger.unlock(metadata.getId());
        }

        function initPointerEventNames() {
            if (!pointerUpEventName) {
                var nodeName = getHotspotElementNodeName();

                pointerUpEventName = context.device.getUpEvents(nodeName);
                pointerDownEventName = context.device.getDownEvents(nodeName);
                pointerMoveEventName = context.device.getMoveEvents(nodeName);
                pointerLeaveEventName = context.device.getReleaseEvents(nodeName);
            }
        }

        function getHotspotElementNodeName() {
            return "document";
        }

        function bindEvents() {
			if (isInAuthoringMode) {
				return;
			}

			if (!button) {
				return;
            }

            context.page.interaction.provokesFeedback( button.getElement(), false );
            context.page.interaction.provokesAutosolve( button.getElement(), false );

			removeEvents();
            context.device.attachFirstSupportedEvent( button.getElement(), pointerDownEventName, button.onMouseDown );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerMoveEventName, button.onMouseOver );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerLeaveEventName, button.onMouseLeave );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerUpEventName, button.onMouseUp );
        }

		function removeEvents() {
			unlockNavigation();
			if (!button) {
				return;
			}

            initPointerEventNames();
            context.device.removeFirstSupportedEvent( button.getElement(), pointerDownEventName, button.onMouseDown );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerMoveEventName, button.onMouseOver );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerLeaveEventName, button.onMouseLeave );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerUpEventName, button.onMouseUp );
        }

		// revealing public API
		return {
            onLoading: function () {
                instance = this;

                context.page.event.bindOnEnter(instance);
                context.page.event.bindOnExit(instance);
                if (!isStandardPlayer) {
                    context.page.event.bind(instance, "onTabNavigationOff");
                    context.page.event.bind(instance, "onTabNavigationSelection");
                    context.page.event.bind(instance, "onTabNavigationFire");
                }
                context.stage.accessibility.bindOnAccessibilityModeChanged(instance );

                hasStageTriggerSupport = !!context.stage.trigger;
				isInAuthoringMode = !!context.stage.isInAuthoringMode();

                shellElement = jq(context.getElement());

                initializeButton(shellElement);
			},

			onEnterPage: function () {
                bindEvents();
                if (!isStandardPlayer && !exludeFromTabControl) {
                    accessibilityTooltip.registerTabNavigation(metadata.getId(), accessibilityTabOrder);
                }
            },

            onExitPage: function(){
                removeEvents();
            },

            onAccessibilityModeChanged: function ( dataHTML5, dataHTML4 ) {
                var params = dataHTML4 || dataHTML5;

                if ( params.isActive ) {
                    accessibilityTooltip.show();
                } else {
                    accessibilityTooltip.hide();
                }
            },

            onAccessibilityKeyPressed: function ( dataHTML5, dataHTML4 ) {
                var params = dataHTML4 || dataHTML5;

                if ( params.keyCode == accessibilityTooltip.getKeyCode() ) {
                    button.onAccessibilityKeyPressed();
                    context.stage.accessibility.turnAccessibilityModeOff();
                }
            },

            onTabNavigationSelection: function (dataHTML5, dataHTML4, data) {
                if (data && data.id && data.id == metadata.getId()) {
                    button.focusButton();
                } else {
                    button.blurButton();
                }
            },

            onTabNavigationOff: function (dataHTML5, dataHTML4) {
                button.blurButton();
            },

            onTabNavigationFire: function (dataHTML5, dataHTML4, data) {
                if (data && data.id && data.id == metadata.getId()) {
                    button.onAccessibilityKeyPressed();
                    context.stage.accessibility.turnAccessibilityModeOff();
                }
            }
		};
	};
});
