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

	"use strict";

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

		var shellElement,
            button,
            buttonInitialized = false,
            instance,
			hasStageTriggerSupport = true,
            isInAuthoringMode = false,
            isInPreviewMode = false,
            accessibilityTooltip,
            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(shellElement);

            button = new ButtonBuilder({
                image : imageParams,
                instance: instance,
                caption: metadata.parameters.get( "caption", "" ),
            }, context, metadata).build();

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

            shellElement.append( button.getElement() );

            if ( accessibilityKey !== "KeyNone" ) {
                accessibilityTooltip = new AccessibilityBuilder( accessibilityKey, accessibilityLocation, accessibilityPositionX, accessibilityPositionY ).build();
                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(element) {
            isInPreviewMode = !!context.stage.isInPreviewMode();
            if( !pointerUpEventName ) {
                pointerUpEventName = isInPreviewMode ? "mouseup" : EventUtil.getPointerUpEvent( element );
                pointerDownEventName = isInPreviewMode ? "mousedown" : EventUtil.getPointerDownEvent( element );
                pointerMoveEventName = isInPreviewMode ? "mousemove" : "pointermove mousemove";
                pointerLeaveEventName = isInPreviewMode ? "mouseend mouseout" : "pointerout mouseout";
            }
        }

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

			if (!button) {
				return;
            }

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

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

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

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

		// revealing public API
		return {
			onLoading: function () {
                context.page.event.bindOnEnter(this);
                context.page.event.bindOnExit( this );
                if ( accessibilityKey !== "KeyNone" ) {
                    context.stage.accessibility.bindOnAccessibilityModeChanged( this );
                }

                instance = this;

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

                shellElement = jq(context.getElement());
                
                initializeButton(shellElement);
			},

			onEnterPage: function () {
                bindEvents();
            },
            
            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();
                }
            }
		};
	};
});
