define(['scripts/knockout-3.3.0','scripts/ACTComponent.js'], function(ko, ACTComponent) {

	function ScrollButtonComponentViewModel(params, element) {
		var self = this;

		self.base = new ACTComponent($(element), params);
		self.element = element;

		self.$element = $(element);
		self.$scrollBtn = self.$element.find(".scrollBtn");

		self.$scrollBtn.on("click", function() {
			var $e = self.$targetElement;

			var ox = self.speed[0];
			var oy = self.speed[1];
			if (ox == -1) ox = $e.outerWidth();
			if (oy == -1) oy = $e.outerHeight();
			if (!self.forward) { ox = -ox; oy = -oy; }

			var currScrollLeft = $e.scrollLeft();
			$e.scrollLeft(currScrollLeft + ox);
			if ($e.scrollLeft == currScrollLeft) {
				var currScrollTop = $e.scrollTop();
				$e.scrollTop(currScrollTop + oy);
			}

			return false;
		});


		self.updateColor = function() {
			var colorRight = self.forward ? "transparent" : self.color;
			var colorLeft  = self.forward ? self.color    : "transparent";
			var ew = self.$element.outerWidth();
			var eh = self.$element.outerHeight();

			var h = eh;
			var w = ew;
			if (h > w)
				h = w;

			self.$scrollBtn.css({
				"border-top"   : h + "px solid transparent",
				"border-bottom": h + "px solid transparent",
				"border-left"  : w + "px solid " + colorLeft,
				"border-right" : w + "px solid " + colorRight,
				"position"     : "absolute",
				"left"         : Math.floor((ew - w) * 0.5) + "px",
				"top"          : Math.floor((eh - h*2) * 0.5) + "px",
			});

			if (!self.forward) self.$scrollBtn.parent().first().scrollLeft(w);
		};

		self.$scrollBtn.on("mouseenter", function() {
			self.color = self.arrowHoverColor;
			self.updateColor();
		});

		self.$scrollBtn.on("mouseleave", function() {
			self.color = self.arrowColor;
			self.updateColor();
		});

		self.base.onRefresh = function(obj) {
			params.ready(false);

			self.forward = obj.Forward;
			self.speed = [obj.VerticalSpeed, obj.HorizontalSpeed];
			self.arrowColor = obj.ArrowColor;
			self.arrowHoverColor = obj.ArrowHoverColor;
			self.color = self.arrowColor;

			var targetCompName = obj.TargetCompName;
			self.target = params.baseModel.definition().gridPanel.componentModels[targetCompName];
			if (!self.target) console.error("scroll button: invalid target");
			self.$targetElement = self.target.$realElement.find(".content").first();
			self.$targetElement.css("overflow", "hidden");

			params.ready(true);
		}

		params.baseModel.resizeFunctions.push(function(h, w) {
			if (!self.$targetElement.hasXScrollBar())
				self.$scrollBtn.hide();
			else
				self.$scrollBtn.show();

			self.updateColor();
		});

		self.base.initialize();
	}

	return {
		createViewModel: function(params, componentInfo) {
			return new ScrollButtonComponentViewModel(params, componentInfo.element);
		}
	};

});

