String.prototype.namespace = function(){
	for(var i=0, o=window, ns = this.split('.'), l=ns.length; i<l; i++)
		o = o[ns[i]] = o[ns[i]] || {};
	return o;
};

"PIA.Modules".namespace();

PIA.Modules.TabbedControl = Class.create({
	initialize: function(parent, tabsCssRole, contentCssRole, options) {
		this.obj = $(parent);
		this.options = options || {};
		if(!this.obj) throw Error("There is no parent in DOM");
		
		this.tabs = {
			list: this.obj.select(tabsCssRole),
			
			show: function(tabName){
				for(var i=0,l=this.list.length; i<l; i++)
					if(tabName!=null && this.getTabName(this.list[i])==tabName)
						$(this.list[i].parentNode).addClassName("active");
					else $(this.list[i].parentNode).removeClassName("active");
			},
			
			getTabName: function(element){
				if(element.href.indexOf("#")==-1) throw Error("You must specify the tab in href. (ex: #tab1)");
				return element.href.replace(/(http:\/\/[^#]+)?#(.+)/g, '$2');
			}
		}
		if(this.tabs.list.length==0) return; //throw Error("There is no tabs");
		
		this.content = {
			list: this.obj.select(contentCssRole),
			
			show: function(tabName){
				for(var i=0,l=this.list.length; i<l; i++)
					if(tabName!=null && this.list[i].getAttribute("name")==tabName)
						this.list[i].show();
					else this.list[i].hide();
			}
		}		
		if(this.content.list.length==0) throw Error("There is no content for tabs");		
		//if(this.tabs.list.length != this.content.list.length) throw Error("Length of tabs and content must be the same");
		
		this.startObserveEvents();
	},
	
	startObserveEvents: function(){
		for(var i=0,l=this.tabs.list.length; i<l; i++)
			this.tabs.list[i].observe("click", this.OnClick());
		this.selectTab(this.options.defaultTab);
	},
	
	stopObserveEvents: function(){
		for(var i=0,l=this.tabs.list.length; i<l; i++)
			this.tabs.list[i].stopObserving("click", this.OnClick());
	},
	
	onClickEvent: function(ev){
		Event.stop(ev);
		this.selectTab(this.tabs.getTabName(ev.element()));
	},
	
	selectTab: function(tabName){
		this.tabs.show(tabName);
		this.content.show(tabName);
	},
	
	OnClick: function(){
		return this.onClickEvent.bind(this);
	},
	
	Error: function(errorMsg){
		return "[TabbedControl] - " + errorMsg;
	}
});

