// com.tts.initial.html5.slidertrigger
// HTML4 / HTML5: No differences
define([
	"jquery"
	], function (
		jq
	) {

	"use strict";

	/**
	 * @constructor
	 */
	return function (context, metadata) {
		var shellElement,
			instance = null,
			id = metadata.parameters.asNumber("id", 1),
			allAcceptedValues = new Array(),
			isInAuthoringMode = false;

		function createSliderTrigger() {
			getAllAcceptedValues();

			if (isInAuthoringMode) {
				createAuthoringShield();
            }
		}

		function getAllAcceptedValues() {
			var acceptedValues = (metadata.parameters.get("value_range", "50")||"").trim();

			acceptedValues = acceptedValues.split(";");

			for (var i = 0; i < acceptedValues.length; i++) {
				if (acceptedValues[i].toString().indexOf('-') == -1) {
					allAcceptedValues.push(parseFloat(acceptedValues[i]));
				} else {
					allAcceptedValues.push(acceptedValues[i]);
				}
			}
		}

		function isCorrect(value) {
			for (var i = 0; i < allAcceptedValues.length; i++) {
				if (typeof allAcceptedValues[i] != "number") {
					var range = allAcceptedValues[i].split("-");

					if (parseFloat(range[0]) <= value && value <= parseFloat(range[1])) {
						return true;
					}
				} else {
					if (parseFloat(allAcceptedValues[i]) == value) {
						return true;
					}
				}
			}

			return false;
		}

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

		// revealing public API
		return {
			onLoading: function () {
				instance = this;
				shellElement = jq(context.getElement());

				context.page.event.bindOnEnter(this);
				context.page.event.bindOnExit(this);
				context.page.event.bind(instance, "onSliderValueChange");

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

				createSliderTrigger();
			},
			onEnterPage: function () {

			},

			onExitPage: function () {

			},
			onSliderValueChange: function (dataHTML5, dataHTML4, data) {
				if (data && data.id == id && isCorrect(data.value)) {
					setTimeout(function () {
						context.page.event.trigger(instance, "sliderchangehit");
					}, 10);
				}
				if (data && data.id == id && !isCorrect(data.value)) {
					setTimeout(function () {
						context.page.event.trigger(instance, "sliderchangenothit");
					}, 10);
                }
			}
		};
	};
});
