// com.tts.initial.html5.sitemap2
define([
	"./sitemap.builder",
    "./locals",
    "jquery",
    "./accessibility.builder"
], function (
	SitemapBuilder,
    uiText,
    jq,
    AccessibilityBuilder
){

	"use strict";

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

        var shellElement,
            button,
            instance,
            buttonInitialized = false,
            isInAuthoringMode = false,
            isInPreviewMode = false,
            isStandardPlayer = context.getPlayerName() === "standard",
            pointerUpEventName, pointerDownEventName, pointerMoveEventName, pointerLeaveEventName,
            fonts = [
                'Arial, Helvetica, sans-serif',
                '"Times New Roman", Times, serif',
                'Verdana, Geneva, sans-serif',
                '"Courier New", Courier, monospace',
                'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
                '"Droid Serif", "Times New Roman", Times, serif'
            ],
            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(){
            if( buttonInitialized ){
                return;
            }
            buttonInitialized = true;

            initPointerEventNames();

            var scParams = metadata.parameters,
                imageArray = {
                    button: loadImage( "button", scParams.get( "bg_image", null ) ),
                    marker: loadImage( "marker", scParams.get( "marker_image", null ) ),
                    icons: loadImage( "icons", scParams.get( "icons_image", null ) ),
                    visited: loadImage( "visited", scParams.get( "visited_image", null ) )
                },
                useSVG = scParams.asBool( "use_svg" );

            button = new SitemapBuilder({
                pointerEvents : {
                    pointerUp : pointerUpEventName,
                    pointerDown : pointerDownEventName,
                    pointerMove : pointerMoveEventName,
                    pointerLeave : pointerLeaveEventName
                },
                instanceID : metadata.getId(),
                AuthoringMode : isInAuthoringMode,
                PreviewMode: isInPreviewMode,
                isStandardPlayer: isStandardPlayer,

                sitemapWidth : scParams.asNumber("sitemap_width", "300"),
                sitemapHeight : scParams.asNumber("sitemap_height", "500"),
                position : scParams.asNumber("sitemap_location", "5"),
                sitemapPositionX: scParams.asNumber("sitemapPositionX", "0"),
                sitemapPositionY: scParams.asNumber("sitemapPositionY", "0"),
                borderColor : scParams.get("border_color", "#999999"),
                borderWidth : scParams.asNumber("border_width", "2"),
                borderTransparency : (scParams.asNumber("borderTransparency", "0")),
                fillColor : scParams.get("fill_color", "#ffffff"),
                fillTransparency : (scParams.asNumber("fillColorTransparency", "0")),
                separatorColor : scParams.get("separator_color", "#d1d1d1"),
                separatorWidth : scParams.asNumber("separator_width", "2"),
                separatorTransparency : (scParams.asNumber("separatorTransparency", "0")),

                useSVG: useSVG,
                showVisited: scParams.asBool( "show_visited" ),
                image: imageArray,
                svgButtonColors: {
                    default: {
                        icon: scParams.get( "color_svg_icon_default", "#ffffff" ),
                        bg: scParams.get( "color_svg_background_default", "#707070" )
                    },
                    hover: {
                        icon: scParams.get( "color_svg_icon_hover", "#ffffff" ),
                        bg: scParams.get( "color_svg_background_hover", "#fd7e2f" )
                    },
                    pressed: {
                        icon: scParams.get( "color_svg_icon_pressed", "#ffffff" ),
                        bg: scParams.get( "color_svg_background_pressed", "#df7a3b" )
                    },
                    inactive: {
                        icon: scParams.get( "color_svg_icon_inactive", "#a9a9a9" ),
                        bg: scParams.get( "color_svg_background_inactive", "#707070" )
                    },
                    expand: scParams.get( "color_svg_expand", "#a9a9a9" ),
                    collapse: scParams.get( "color_svg_collapse", "#a9a9a9" ),
                    marker: scParams.get( "color_svg_marker", "#a9a9a9" ),
                },
                svgIconColors: {
                    default: {
                        icon: scParams.get( "color_svg_icon", "#999999" ),
                        bg: "none"
                    },
                    hover: {
                        icon: scParams.get( "color_svg_icon", "#999999" ),
                        bg: "none"
                    },
                    pressed: {
                        icon: scParams.get( "color_svg_icon", "#999999" ),
                        bg: "none"
                    },
                    inactive: {
                        icon: scParams.get( "color_svg_icon", "#999999" ),
                        bg: "none"
                    }
                },
                svgMarkerColor: scParams.get( "color_svg_marker", "#fd7326" ),
                svgVisitedColor: scParams.get( "color_svg_visited", "#ffffff" ),

                fontFamily : getFont(scParams.get("font-family","0")),
                fontSize : scParams.get("font-size", "14"),
                sectionTextColor : scParams.get("section_text_color", "#142534"),
                sectionHoverTextColor : scParams.get("section_hover_color", "#fd7326"),
                pageTextColor : scParams.get("page_text_color", "#142534"),
                pageHoverTextColor : scParams.get("page_hover_color", "#fd7326"),
                paddingLeft : scParams.asNumber("padding-left", "10"),
                paddingRight : scParams.asNumber("padding-right", "10"),
                paddingTop : scParams.asNumber("padding-top", "2"),
                paddingBottom : scParams.asNumber("padding-bottom", "2"),
                cutTitles : scParams.asBool("cut_titles"),
                caption: getText("tooltip", "player.navigation.button.sitemap.open"),
                captionClose: getText("tooltip-close", "player.navigation.button.sitemap.close"),
                ariaLabel: ((scParams.get("aria-label", false)|| "").trim() === "") ? false : scParams.get("aria-label", false),
                ariaLabelClose: ((scParams.get("aria-label-close", false)||"").trim() === "") ? false : scParams.get("aria-label-close", false),
                showSitemapInAuthoringMode : scParams.asBool("show_sitemap_in_authoring_mode")
            }, context, metadata).build();

            shellElement.append( button.getElement() );

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

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

            if (isInAuthoringMode) {
                createAuthoringShield();
            }
        }

        function getText( parameterName, defaultTextName ) {
            var paramValue = ( metadata.parameters.get(parameterName,"")||"" ).trim();
			return ( paramValue.length > 0 ) ? paramValue : uiText.get( defaultTextName, metadata.stage.getContentLanguage() );
        }

        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() + "sitemap.png";
                            result.width = 100;
                            result.height = 150;
                            break;
                        case "marker":
                            result.fileNameURL = context.getPath() + "marker.png";
                            result.width = 14;
                            result.height = 14;
                            break;
                        case "icons":
                            result.fileNameURL = context.getPath() + "icons.png";
                            result.width = 14;
                            result.height = 28;
                            break;
                        case "visited":
                            result.fileNameURL = context.getPath() + "visited.png";
                            result.width = 14;
                            result.height = 14;
                            break;
                        default:
                            return null;
                    }
                }

            return result;
        }

        function getFont( index ) {
            var fontIndex = (index > 0 && index < fonts.length) ? index-1: 0;
            return fonts[fontIndex];
        }

        function unlockNavigation() {
            if (context.stage.isInAuthoringMode() || (typeof(context.stage.trigger) === "undefined")) {
                return;
            }
            context.stage.trigger.unlock( metadata.getId() );
        }

        function initPointerEventNames() {

            if ( pointerUpEventName ) {
                return;
            }

            if ( context.stage.isInPreviewMode() ) {
                pointerUpEventName = "mouseup";
                pointerDownEventName = "mousedown";
                pointerMoveEventName = "mousemove";
                pointerLeaveEventName = "mouseend mouseout";
                return;
            }

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

        function cancelEvent( e ) {
            context.device.cancelEvent( e );
        }

        // 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": "transparent",
                    "opacity": "0.4",
                    "width": "100%",
                    "height": "100%",
                    "z-index": "9999"
                }));
        }

        function bindEvents() {

            if (context.stage.isInAuthoringMode()) {
                return;
            }

            if (!button || !buttonInitialized) {
                return;
            }

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

            jq(button.getHotSpotElement()).on("dblclick", cancelEvent );
        }

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

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

            jq(button.getHotSpotElement()).off("dblclick", cancelEvent );
        }

		// 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");
                }

                shellElement = jq(context.getElement());

                isInAuthoringMode = !!context.stage.isInAuthoringMode();
                isInPreviewMode = !!context.stage.isInPreviewMode();

                // because of some problems with loading SVG while it is hidden on page,
                // we initialize SVG button onEnterPage
                if ( !isStandardPlayer || isInAuthoringMode ) {
                    initializeButton();
                }
            },

            onEnterPage: function () {
                // because of some problems with loading SVG while it is hidden on page,
                // we initialize SVG button onEnterPage
                if ( !buttonInitialized ) {
                    initializeButton();
                }

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

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