// com.tts.initial.html5.pausebutton
// HTML4 / HTML5: No differences
define([
    "./togglebutton.builder",
    "./locals",
    "jquery",
    "./accessibility.builder"
    ], function (
        ToggleButtonBuilder,
        uiText,
        jq,
        AccessibilityBuilder
    ) {

	"use strict";

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

		var shellElement,
            button,
            buttonInitialized = false,
            isStandardPlayer = context.getPlayerName() === "standard",
            instance,
			hasStageTriggerSupport = true,
			isInAuthoringMode = false,
            pointerUpEventNames,
            pointerDownEventNames,
            pointerMoveEventNames,
            pointerLeaveEventNames,
            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 );

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

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

            button = new ToggleButtonBuilder({
                image : imageParams,
                instance : instance,
                tooltip: uiText.get("player.navigation.button.pause", metadata.stage.getContentLanguage()),
                tooltipResume: uiText.get("player.navigation.button.resume", metadata.stage.getContentLanguage()),
                ariaLabel: ((metadata.parameters.get("aria-label", false) || "").trim() === "") ? false : metadata.parameters.get("aria-label", false),
                ariaLabelResume: ((metadata.parameters.get("aria-label-resume", false) || "").trim() === "") ? false : metadata.parameters.get("aria-label-resume", false)
            }, context, metadata).build();

            shellElement.css({
                "width" : imageParams.width / 2 + "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 "pause":
                            result.fileNameURL = context.getPath() + "pause.png";
                            result.width = 100;
                            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 getHotspotElementNodeName() {
            return button.getElement().nodeName
                ? button.getElement().nodeName
                : "document";
        }

        function initPointerEventNames() {
            if( !pointerUpEventNames ) {
                var nodeName = getHotspotElementNodeName();
                pointerDownEventNames = context.device.getDownEvents( nodeName );
                pointerUpEventNames = context.device.getUpEvents( nodeName );
                pointerMoveEventNames = context.device.getMoveEvents( nodeName );
                pointerLeaveEventNames = context.device.getReleaseEvents( nodeName );
            }
        }

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

			if (!button) {
				return;
			}

			removeEvents();
            context.device.attachFirstSupportedEvent( button.getElement(), pointerDownEventNames, button.onMouseDown );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerMoveEventNames, button.onMouseOver );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerLeaveEventNames, button.onMouseLeave );
            context.device.attachFirstSupportedEvent( button.getElement(), pointerUpEventNames, button.onMouseUp );
        }

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

            initPointerEventNames();
            context.device.removeFirstSupportedEvent( button.getElement(), pointerDownEventNames, button.onMouseDown );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerMoveEventNames, button.onMouseOver );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerLeaveEventNames, button.onMouseLeave );
            context.device.removeFirstSupportedEvent( button.getElement(), pointerUpEventNames, button.onMouseUp );
        }

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

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

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

                shellElement = jq(context.getElement());

                initializeButton(shellElement);
			},

			onEnterPage: function () {
                bindEvents();

                button.onEnterPage();

                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.pause();
                }
            },

            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.pause();
                }
            }
		};
	};
});
