
registerType('Core.UI', (function () { function SegmentedControl() {} var __super = setSupertypeFromDomain(SegmentedControl, 'View', 'Core.UI');

	var defaultLabelColor = 'hsl(0,0%,50%)', 
		defaultLabelColorSelected = 'hsl(0,0%,0%)', 
		delegateValidationMethod = 'segmentedControlValidateSegmentAtIndex',
		delegateValueDidChangeMethod = 'segmentedControlDidChangeValue';


// role BasicObject (Core) 


SegmentedControl.prototype.initFromData = function SegmentedControl_initFromData(data, holdBindings) {
	
		if (!data.size.height)
			data.size.height = 22;
		
		if (!__super.prototype.initFromData.call(this, data, null, true))
			return;

		this.initBackgroundCanvas();
				
		this.drawsBackground = data.drawsBackground;
		this.invertSelectedImage = (data.drawsBackground !== undefined ? data.drawsBackground : true);
		this.itemSprite = data.itemSprite;
		this.itemSpriteContentInset = data.itemSpriteContentInset;
		this.localizeLabels = data.localizeLabels;
		this.displaysText = data.displaysText !== false;

		this.segments = data.segments;
		if (data.segments !== undefined) {

			var delegateCanValidate = this.delegateRespondsTo(delegateValidationMethod),
				c = data.segments.length,
				cellWidth = Math.floor(this.size.width / c),
				cellHeight = this.size.height;
				remainder = this.size.width - cellWidth * c;

			for (var i = 0; i != c; i++) {
			
				if (this.segments[i].enabled !== undefined && this.segments[i].enabled == false)
					continue;

				var toolTip = this.segments[i].toolTip;
				if (this.segments[i].localizeToolTip) toolTip = LocalizedString(toolTip);
				
				var cell = createComponentFromDomain(
					'View', 'Core.UI',
					this.context,
					{
						size: { width: cellWidth + ((i + 1 === c) ?remainder : 0),
								height: cellHeight },
						position: { left: i * cellWidth, top: 0 },
						toolTip: toolTip,
						disabled: delegateCanValidate ? !this.callDelegate(delegateValidationMethod, [this, i]) : false,
					});
				
				var l = this.segments[i].label;
				
				if (l) {

					if (this.segments[i].localizeLabel === true || this.localizeLabels === true)
						l = LocalizedString(l);
						
					var fontSize = (data.fontSize||11);
				
					var label = createComponentFromDomain("UILabel", "appdoo.iOS", this.context, {
						text: l,
						size: cell.sizeCopy,
						position: {top:0},
						autoresizingMask: 42,
						hidden: !this.displaysText,
						fontSize: fontSize,
						textAlignment: 'center',
						style: {
							fontFamily: data.fontFamily,
							color: this.labelColor,
							pointerEvents: 'none'
						}})
					;
					cell.label = label;
					cell.addSubview(label);
				}

				if (this.segments[i].imageSrc !== undefined) {
					var imageSize = clone(this.segments[i].imageSize) || { width: cellWidth, height: cellHeight };
					if (i > 0) imageSize.width -= 1;
					cell.image = createComponentFromDomain(
						'ImageView', 'Core.UI',
						this.context,
						{
							imageSrc: this.segments[i].imageSrc,
							size: imageSize,
							position: {
								left: Math.round(cellWidth/2 - imageSize.width/2 ),
								top: Math.round(cellHeight/2 - imageSize.height/2 )
							},
							autoresizingMask: 45,
							style: { pointerEvents: 'none', filter: 'invert(0)' },
							contentMode: 'center'
						}
					);
				}
				else if (this.segments[i].image !== undefined) {
					cell.image = this.context.decodeObjectTree(this.segments[i].image);
					cell.image.position.left = Math.floor(cellWidth/2 - cell.image.size.width/2);
					cell.image.autoresizingMask = 5;
					cell.image.style.filter = 'invert(0)';
				}
				
				
				if (this.drawsBackground === true) {
					cell.addSubview(cell.backgroundView);
				}
				
				if (cell.image)
					cell.addSubview(cell.image);
				cell.DOMNode.tag = i;
	
				this.addSubview(cell);
				
				var selectionEvent = data.selectionEvent ? 'on'+data.selectionEvent : 'onmousedown';
				cell.DOMNode[selectionEvent] = this.onMouseDownInSegment.bind(this);
				
			}
		}

		this.setSelectedIndex(data.selectedIndex);
		
		if (data.delegate !== undefined)
			this.delegate = data.delegate;
		
		this.repaintBackground();
		this.layoutSubviews();
		
		if (holdBindings !== true) this.applyBindings(true);


		this._onWindowBlurEventHandler = function () {
			this.repaintBackground();
		}.bind(this);
		this._onWindowFocusEventHandler = function () {
			this.repaintBackground();
		}.bind(this);
		window.addEventListener('didBecomeMain', this._onWindowBlurEventHandler);
		window.addEventListener('didResignMain', this._onWindowFocusEventHandler);
		
		Object.defineProperty(this, "isInitialized", {
			value: true});
		

		return this;};
	
	
SegmentedControl.prototype.destroy = function SegmentedControl_destroy() {
		this.DOMNode.onclick = null;

		window.removeEventListener('didBecomeMain', this._onWindowBlurEventHandler);
		window.removeEventListener('didResignMain', this._onWindowFocusEventHandler);
		
		__super.prototype.destroy.call(this);};
	
	
	
SegmentedControl.prototype.initBackgroundCanvas = function SegmentedControl__initBackgroundCanvas() {
	
		var w = this._size.width,
			h = this._size.height,
			canvas = document.createElement('canvas');
		
		canvas.width = w * this.pixelDensity;
		canvas.height = h * this.pixelDensity;
		canvas.style.width = w + 'px';
		canvas.style.height = h + 'px';

		this.DOMNode.appendChild(canvas);
		this.backgroundCanvas = canvas;
		};
	
		

	

SegmentedControl.prototype.onMouseDownInSegment = function SegmentedControl__onMouseDownInSegment(e) {

		e.preventDefault();
		e.stopPropagation();

		if (this._disabled === true) return;

		var index = e.target.tag,
			value = this.segments[index].value;

		if (this.segments[index].enabled !== undefined && this.segments[index].enabled == false)
			return;

		this.selectedIndex = index;
		this._value = value;

		this.context.broadcastValueChangeForKeyPathInObject('value', this, this);};
	


	

SegmentedControl.prototype.valueShouldChangeForKeyPath = function SegmentedControl_valueShouldChangeForKeyPath(value, keyPath) {

		if (keyPath === 'value') {
			this.value = value;
			return true;
		}

		return false;
	};
	


	

SegmentedControl.prototype.layoutSubviews = function SegmentedControl_layoutSubviews() {
		
		var i = 0,
			c = this.subviews.length,
			remainingWidth = this.size.width,
			x = 0;
			
		if (Array.isArray(this.subviews)) this.subviews.every(function (subview) {
			var w;
			if (i === c-1) w = remainingWidth;
			else w = Math.round(remainingWidth/(c-i));
			
			subview.size.width = w;
			subview.size.height = this._size.height;
			subview.position.left = x;
			x += w;
			remainingWidth -= w;
			
			if (this.drawsBackground === true) {
				subview.backgroundView.size = subview.size;
			}

			i++;return true; }, this);
		
		
		this.updateBackground();
		
};
	
	


	
	
SegmentedControl.prototype.updateBackground = function SegmentedControl__updateBackground() {

		this.backgroundCanvas.width = (this.size.width+2) * this.pixelDensity;
		this.backgroundCanvas.style.width = (this.size.width+2)+'px';
		this.repaintBackground();
	};
	

SegmentedControl.prototype.repaintBackground = function SegmentedControl__repaintBackground() {
		
		if (this.drawsBackground === false) return;

		var itemSprite = this.context.pathForOptimizedImage(this.itemSprite || this.context.pathForResource('SegmentedControlEC.png'));


		this.context.whenImageIsReady(itemSprite, function (img) {
		
			var contentInset = this.itemSpriteContentInset || [
				6, 
				0, 
				0, 
				0, 
			];
		
			var canvas = this.backgroundCanvas,
				width = canvas.width-2,
				height = canvas.height,
				pd = this.pixelDensity,
				ctx = canvas.getContext('2d'),
				dy = 0, 
				sh = img.height/3, 
				sw = img.width, 
				sy = 0, 
				sys = window.hasFocus ? sh : sh*2, 
				bw = contentInset[0]*pd, 
				mw = 10*pd, 
				segmentsCount = this.segments.length,
				segmentWidth = Math.round(width / segmentsCount),
				lastSegmentWidth = width - segmentWidth*(segmentsCount-1),
				selectedIndex = this.selectedIndex,
				y;

			ctx.clearRect(0, 0, width, height);
			
			
			
			y = (selectedIndex === 0 ? sys : sy);
			ctx.drawImage(img,
						  0, y, bw, sh,
						  0, dy, bw, sh);
			
			ctx.drawImage(img,
						  bw, y, mw, sh,
						  bw, dy, segmentWidth-bw-1, sh);


			
			for (var i = 1, c = segmentsCount-1; i < c; i++) {
				y = (selectedIndex === i ? sys : sy);
				ctx.drawImage(img,
							  bw, y, mw, sh,
							  segmentWidth*i, dy, segmentWidth-1, sh);
			}
			

			
			
			y = (selectedIndex === segmentsCount-1 ? sys : sy);
			ctx.drawImage(img,
						  sw-bw-mw, y, mw, sh,
						  width-lastSegmentWidth, dy, lastSegmentWidth-bw, sh);

			
			ctx.drawImage(img,
						  sw-bw, y, bw, sh,
						  width-bw, dy, bw, sh);
			
			
			
			for (var i = 0, c = segmentsCount-1; i < c; i++) {
				y = ((selectedIndex === i || selectedIndex === i+1) ? sys : sy);
				ctx.drawImage(img,
							  21*pd, y, 1, sh,
							  segmentWidth*(i+1)-1, dy, 1, sh);
			}
				
		}.bind(this));
};
	


	

	function isNumber(x) {
		return typeof x === 'number';
	}
	
	Object.defineProperty(SegmentedControl.prototype, "labelColor", {
	outlet: true, 
	enumerable: true, 
		set: function (v) {if (!Object.hasOwnProperty(this, "_labelColor")) Object.defineProperty(this, "_labelColor", { writable: true, configurable: true }); var isUpdating = this._labelColor !== undefined; this._labelColor = v; if (isUpdating) {
		
			if (Array.isArray(this.subviews)) this.subviews.every(function (cell) {
				if (cell.label) cell.label.style({ color: this.labelColor });return true; }, this);
			
			if (this.subviews[this._selectedIndex] && this.subviews[this._selectedIndex].label)
				this.subviews[this._selectedIndex].label.style({ color: this.labelColorSelected });
				
		
		} }, 
		get: function () { return this._labelColor || defaultLabelColor; }});
	

	Object.defineProperty(SegmentedControl.prototype, "labelColorSelected", {
	outlet: true, 
	enumerable: true, 
		get: function () { return this._labelColorSelected || defaultLabelColorSelected; }, set:function (v) {if (!Object.hasOwnProperty(this, "_labelColorSelected")) Object.defineProperty(this, "_labelColorSelected", { writable: true, configurable: true }); this._labelColorSelected = v; }});
	
	
SegmentedControl.prototype.setSelectedIndex = function SegmentedControl__setSelectedIndex(v) {
	
		var isUpdating = isNumber(this._selectedIndex);
		var segment = this.segments[v];
		if(segment !== undefined) {
			if(segment.enabled === false) {
				return;
			}
		}

		if (isUpdating === true) {
			if (this._selectedIndex === v) return;
			
			var cell = this.subviews[this._selectedIndex];
			if (cell) {
				if (this.drawsBackground === true) {
					cell.backgroundView.src = this.context.pathForResource('SegmentedControl.png');
				}
				if (cell.image) {
					cell.image.highlighted = false;
					if(this.invertSelectedImage === true) {
						cell.image.DOMNode.style.filter = 'invert(0)';
					}
				}
				if (cell.label) cell.label.style({ color: this.labelColor });
			}

		}
		
		Object.defineProperty(this, '_selectedIndex', {
			value: v, writable: true
		});
		
		this.repaintBackground();


		if (isNumber(v)) {
			var cell = this.subviews[v];
			if (cell) {
				if (cell.image) {
					cell.image.highlighted = true;
					if(this.invertSelectedImage === true) {
						cell.image.DOMNode.style.filter = 'invert(1)';
					}
				}
				if (cell.label) cell.label.style({ color: this.labelColorSelected });
			}
		}



		
		if (this.isInitialized) {
			this.callDelegate(delegateValueDidChangeMethod, [this]);
		}

};
	

	Object.defineProperty(SegmentedControl.prototype, "selectedIndex", {
		set: function SegmentedControl_selectedIndex_set(v) {
			this.setSelectedIndex(v);
		}, 
		get: function () {
			return this._selectedIndex;
		}});
	
	
	Object.defineProperty(SegmentedControl.prototype, "value", {
		set: function (v) {
			var segmentIndexToSelect, i = 0;
			if (Array.isArray(this.segments)) this.segments.every(function (segment) {
				if (segment.value === v) {
					segmentIndexToSelect = i;
					return false;
				}
				i++;return true; }, this);
			
			this.selectedIndex = segmentIndexToSelect;
		}, 
		get: function () {
			return this._value;
		}});
	

	Object.defineProperty(SegmentedControl.prototype, "disabled", {
	enumerable: true, 
		set: function (v) {
			if (v === true) this.style({ opacity: .5 });
			else this.style({ opacity: 1 });
			
			Object.defineProperty(this, "_disabled", {
			writable: true, 
				value: v});
			
		}, 
		get: function () {
			return this._disabled;
		}});
	
	
	Object.defineProperty(SegmentedControl.prototype, "pixelDensity", {
		get: function () {
			return this.context.highResolutionEnabled ? 2 : 1;
		}});
	
	
SegmentedControl.prototype.initPropertiesFromData = function SegmentedControl_initPropertiesFromData(data) {
try { __super.prototype.initPropertiesFromData.call(this, data); } catch (err) {}
if (data.hasOwnProperty("labelColor")) this.labelColor = data.labelColor;
if (data.hasOwnProperty("labelColorSelected")) this.labelColorSelected = data.labelColorSelected;
};

SegmentedControl.prototype.decodeData = function SegmentedControl_decodeData(data) { var decoded;
try { decoded = __super.prototype.decodeData.call(this, data); } catch (err) { console.warn(err); decoded = clone(data); }
return decoded; };

SegmentedControl.prototype.encode = function SegmentedControl_encode() { var encoded;
try { encoded = __super.prototype.encode.call(this); } catch (err) { console.warn(err); encoded = this.context.encodeObject(this); }
return encoded; };

SegmentedControl.prototype.encodeCloned = function SegmentedControl_encodeCloned() { var encoded;
try { encoded = __super.prototype.encodeCloned.call(this); } catch (err) { console.warn(err); encoded = {}; }
return encoded; };

SegmentedControl.prototype.expectedTypeForProperty = function SegmentedControl_expectedTypeForProperty(key) {
	if (key === "isInitialized") return "";
	if (key === "labelColor") return "String";
	if (key === "labelColorSelected") return "String";
	if (key === "selectedIndex") return "";
	if (key === "value") return "";
	if (key === "disabled") return "";
	if (key === "pixelDensity") return "";
	if (__super) return __super.prototype.expectedTypeForProperty(key);
};

return SegmentedControl; }()));