﻿Type.registerNamespace("CyberCoders");
CyberCoders.Tab = function(element) {
	CyberCoders.Tab.initializeBase(this, [element]);
			
	this._tabClickDelegate = null;
	this._selectedIndex = -1;
	this._tabs = null;
	this._ie6 = (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7);
	this._initialized = false;
}
CyberCoders.Tab.prototype = {
	get_selectedIndex : function() {
		return this._selectedIndex;
	},
	
	set_selectedIndex : function(value) {
		if (this._selectedIndex != value) {
			this._selectedIndex = value;
			
			if (this._initialized)
				this._update();
				
				var handler = this.get_events().getHandler('selectedTabChanged');
				if (handler)
					handler(this, Sys.EventArgs.Empty);
		}
	},
	
	get_tabs : function() {
		return this._tabs;
	},
	
	set_tabs : function(value) {
		this._removeHandlers();
		
		this._tabs = value;
		
		if (this._initialized) {
			this._initializeHandlers();
			this.set_selectedIndex(this._tabs ? 0 : -1);
		}
	},
	
	add_selectedTabChanged : function(handler) {
		this.get_events().addHandler('selectedTabChanged', handler);
	},
	
	remove_selectedTabChanged : function(handler) {
		this.get_events().removeHandler('selectedTabChanged', handler);
	},
	
	initialize : function() {
		CyberCoders.Tab.callBaseMethod(this, 'initialize');
				
		if (this._tabClickDelegate == null) {
			this._tabClickDelegate = Function.createDelegate(this, this._tabClickHandler);
		}		
		
		this._initialized = true;
		this._initializeHandlers();
		this._update();
	},
	
	dispose : function() {
		this._removeHandlers();
		
		delete this._tabClickDelegate;
	
		CyberCoders.Tab.callBaseMethod(this, 'dispose');	
	},
	
	_initializeHandlers : function() {
		if (this._tabs) {
			for (var i = 0; i < this._tabs.length; i++) {
				this._tabs[i].element.__tabIndex = i;
				$addHandler(this._tabs[i].element, 'click', this._tabClickDelegate);
			}
		}
	},
	
	_removeHandlers : function() {
		if (this._tabs) {
			for (var i = 0; i < this._tabs.length; i++) {
				$removeHandler(this._tabs[i].element, 'click', this._tabClickDelegate);
			}
		}
	},
	
	_tabClickHandler : function(e) {
		var i = e.target.__tabIndex;		
		this.set_selectedIndex(i);
	},
	
	_update : function() {
		if (this._tabs) {
			for (var i = 0; i < this._tabs.length; i++) {
				if (!this._ie6)
					this._tabs[i].element.src = this._selectedIndex == i ? this._tabs[i].selectedImageUrl : this._tabs[i].deselectedImageUrl;
				else {
					this._tabs[i].element.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + (this._selectedIndex == i ? this._tabs[i].selectedImageUrl : this._tabs[i].deselectedImageUrl)  + '", sizingMethod="scale")';
					this._tabs[i].element.style.position = 'relative';
				}
			}
		}
	}
}

CyberCoders.Tab.registerClass("CyberCoders.Tab", Sys.UI.Behavior);