
// Tests if user has changed the ajax viewstate via back/next buttons
var viewstate = location.href;
//womAdd("setInterval('stateChange()', 500)");

// content_tabs = new mootabs('content-tabs', {changeTransition: 'none', height:'inherit', width:'930px', activeTab:'fs3752li10pn1sbv133d', useLinks:true});  


stateChange = function(){
	alert('stateChange called')
	if(viewstate){
		if(viewstate != location.href){
			
			t = getViewstate();
			
			//t['control'] = t['control'].replace('_','-');
			
			//eval control id calling activate(element id, false, fragment)
			//alert(t.control + " = " + $(t.control))
			//alert(t['element'])
			var item = $(t['control'].replace('_','-'));
			
			item = $(item);
			
       		if(item && !item.hasClass('.active') && eval(t['control'])){
				eval(t['control']).activate(t['element'], false, t['fragment']);
				}
			
			//reset viewstate
			viewstate = location.href;
		}
	}else{
		viewstate = location.href;
	}
};


getViewstate = function(){
		//get hash from location 
		href = location.href;
		if(href.indexOf('#') > 0){
			var hash = href.substring(href.indexOf('#')+1);
			//parse hash into property array [control id, element id, fragment]  
			var tab = hash.split('|') 
		}else{
			return false;
		}
		
		valuetypes = ['control', 'element', 'fragment'];
		
		
		t = tab.associate(valuetypes);
		
		if (!t['element']){
			tab = hash.split('^')
			t = tab.associate(valuetypes);
		}
			
		
		return t;
}

var mootabs = new Class({
                Implements: [Options, Events],
                options: {
                        width:                  '100%',
                        height:                 '100%',
                        changeTransition:       Fx.Transitions.Bounce.easeOut,
                        duration:               1000,
                        hoverClass:       		'active',
                        activeTab:       		'first',
		                useAjax:                false,
                        ajaxUrl:                '/soap/as.php',
                        ajaxOptions:            { method:'get', 
                        						  onSuccess: function(responseText) {
                        						  		var enableAjax = new ajaxLinks(this, this.options)					                
  													}
												},
                        ajaxLoadingText:        '<div class="loading">Loading</div>',
                        ajaxCache:				false,
                        fixoverflow:			false,
                        useLinks:				false
                },
               
                initialize: function(element, options) {
						                
                        this.setOptions(options);
                        this.el = $(element);
                        this.elid = element;
                        /*this.el.setStyles({
                                width: this.options.width,
                                height: this.options.height
                        });    */                    
                        // fix overflow error in IE7
                        // $$('#' + this.elid + ' .content')[0].setStyle('position', 'relative');
                        
                   		this.titles = $$('#' + this.elid + ' ul.buttons li');
               			if(this.options.useLinks){
                       		this.links = $$('#' + this.elid + ' ul.buttons li a');
	                        this.links.each(function(item) {
	                        	var li = item.getParent();
	                        	var title = null;
                        		item.addEvents({
	                    			'click': function(event){
	                               		if(event) event.preventDefault(); 
		                        		item.setProperty('title', title);
		                        		if (item != this.activeTitle){
	                                    	li.removeClass(this.options.hoverClass);
	                                    	this.activate(item, false, title);
											viewstate = null;
	                                    }
	                                    item.blur();
	                            	}.bind(this),
	                            
	                            
			                        'mouseover': function() {
                        				title = item.getProperty('title');
		                        		item.setProperty('title', '');
		                        		if(item != this.activeTitle){
	                                        li.addClass(this.options.hoverClass);
		                                }
			                        }.bind(this),
			                        
			                       
			                        'mouseout': function() {
		                        		item.setProperty('title', title);
		                        		if(item != this.activeTitle){
	                                        li.removeClass(this.options.hoverClass);
		                                }
			                        }.bind(this)
		                        });
			                }.bind(this));
                       	}else{
                       		this.titles.each(function(item) {
	                        	var title = null;
                        		item.addEvents({
	                			
	                    			'click': function(){
		                        		item.setProperty('title', title);
	                                    item.removeClass(this.options.hoverClass);
	                                    this.activate(item);
	                            	}.bind(this),
	                            
	                            
			                        'mouseover': function() {
	                        				title = item.getProperty('title');
			                        		item.setProperty('title', '');
			                                if(item != this.activeTitle){
			                                        item.addClass(this.options.hoverClass);
			                                }
			                        }.bind(this),
			                        
			                       
			                        'mouseout': function() {
			                        		item.setProperty('title', title);
			                                if(item != this.activeTitle){
			                                        item.removeClass(this.options.hoverClass);
			                                }
			                        }.bind(this)
		                        })
		                	}.bind(this));	
                       	}                   
                                       
                        
                        
                        this.panelHeight = this.el.getSize().y - (this.titles[0].getSize().y + 4);
                        this.panels = $$('#' + this.elid + ' .tab');
               			
               			if (this.options.changeTransition != 'none') this.panels.setStyle('height', this.panelHeight);
               			if (this.options.fixoverflow) {
               			
               				this.fixoverflow = true;
               				this.more = $$('#' + this.elid + ' .vmore')[0];
               				
               				this.more.addEvent('click', function(){
	                                if(this.more.getStyle('visibility') != 'hidden'){this.el.toggleClass('open')}
                            }.bind(this));
               			}
                if(this.options.activeTab != 'none'){                		
                		
						
						// Catch href (disabled)
						/*
						t = getViewstate();
						
						if(t['element']){
							var trigger = null;
							//var flag = t['element'].substring()
							//var trigger = flag.substring(flag.indexOf('fs'))
							if (this.options.useLinks){
								var frag = t['element']//'ot1157-1158fs3752pi360li10pn1sbv133d'
								trigger = $$('a[href*="'+frag+'"]')
							}
							
							if(trigger){
								trigger[0].fireEvent('click');
								return
								}
							
						}*/
						
						/*
                		if(t['element']) { 
                			//alert(t['element']+" match "+ this.options.activeTab)
	                		eval(t['control']+'.activate(t[\'element\'], false, t[\'fragment\'])'));          		
                			return
                		}*/
                		
                        if(this.options.activeTab == 'first'){
                        	this.activate(this.titles[0], true);
                        }else{
                            this.activate(this.options.activeTab, true);
                           // alert(this.options.activeTab)
                            /*
                            trigger = $$('a[href*="'+this.options.activeTab+'"]')
							if(trigger){
								trigger[0].fireEvent('click');
								//alert('triggered')
								return
							}else{
								alert(this.options.activeTab+' has no trigger')
							}
							*/

                        }
                }
        },
       
        activate: function(tab, skipAnim, altAjaxId){
        		// temp fix to overcome display issue.

        		
        		if (this.fixoverflow) {this.el.removeClass('open');}
               
				if(!$defined(skipAnim)){
                        skipAnim = false;
                }
                if($type(tab) == 'string'){
                	findTab = $$('#' + this.elid + ' ul li').filter('[title='+tab+']')[0];
                	if(!findTab){
                		findTab = $$('#' + this.elid + ' ul li a').filter('[title='+tab+']')[0];
                	}
                	tab = findTab;
                }
                
        		if ($(tab).hasClass('active')){
        			this.activePanel = $(tab).getProperty('title');
        			this.getContent();
        			//alert(this.activePanel)
        			return;
        		}
                
                if($type(tab) == 'element'){
                        var newTab = tab.getProperty('title');
                        this.panels.removeClass('active');
                        this.titles.removeClass('active');
                        this.activePanel = $(newTab);
                        //alert(newTab + ' '+tab.getProperty('title'))
                      
                        this.activePanel.addClass('active');
                        if(this.options.changeTransition != 'none' && skipAnim==false){
                                this.activePanel.setStyle('height', 0);
                                var changeEffect = new Fx.Elements(this.activePanel, {duration: this.options.duration, transition: this.options.changeTransition});
                                changeEffect.start({
                                        '0': {
                                                'height': [0, this.panelHeight]
                                        }
                                });
                        }else if(this.fixoverflow){
                        	fix = (this.activePanel.getSize().y < this.panelHeight)?'hidden':'visible';
                        	this.more.setStyle('visibility', fix);
                        }
                      	
                		
                        this.activeTitle = tab;
                        this.altAjaxId = (altAjaxId)? altAjaxId:this.activeTitle.getProperty('title');
                        
                        if(tab.get('tag') == 'a'){
                        	tab.getParent('li').addClass('active')
							tabhref = tab.get('href');
							frag = (altAjaxId)?altAjaxId:tabhref.substring(tabhref.lastIndexOf('/')+1);
							href = '#' + this.elid.replace('-','_')+'|'+newTab+'|'+frag.replace('#','');
                        }else{
                        	tab.addClass('active');
                        	href = '#' + this.elid.replace('-','_');
                		}
					
                        if(tab.getProperty('rel') == 'ajax'){
                        	if(!this.options.ajaxCache || !this.activePanel.getChildren()[0]){
                                	this.getContent();
                                }
                        }
						
						location.href = href;
                	
				}
				
                // script excecution case
                switch(newTab){
                	
                	case 'comments':
                		if(!this.commentsLoad) this.commentsLoad = instantiate_comment_slide();
						break;
					default:
						break;
				}
				
				
        },
        getContent: function(fr){
                this.activePanel.set('html', this.options.ajaxLoadingText);
                var newOptions = { url: this.options.ajaxUrl + '?fr=' + this.altAjaxId, ajaxLoadingText: this.options.ajaxLoadingText, urlBase:this.options.ajaxUrl, update: this.activePanel.get('id')} ;
                var options = $extend(this.options.ajaxOptions, newOptions);
                var req = new Request.HTML(
                        options
                ).send();
                
        },
       
        addTab: function(title, label, content){
                var newTitle = new Element('li', {
                        'title': title
                });
                newTitle.appendText(label);
                this.titles.include(newTitle);
                $$('#' + this.elid + ' ul').adopt(newTitle);
                newTitle.addEvent('click', function() {
                        this.activate(newTitle);
                }.bind(this));
               
                newTitle.addEvent('mouseover', function() {
                        if(newTitle != this.activeTitle){
                                newTitle.addClass(this.options.hoverClass);
                        }
                }.bind(this));
                newTitle.addEvent('mouseout', function() {
                        if(newTitle != this.activeTitle){
                                newTitle.removeClass(this.options.hoverClass);
                        }
                }.bind(this));

                var newPanel = new Element('div', {
                        'style': {'height': this.options.panelHeight},
                        'id': title,
                        'class': 'tab'
                });
                if(!this.options.useAjax){
                        newPanel.setHTML(content);
                }
                this.panels.include(newPanel);
                this.el.adopt(newPanel);
        },
       
        removeTab: function(title){
                if(this.activeTitle.title == title){
                        this.activate(this.titles[0]);
                }

                $$('#' + this.elid + ' ul li').filter('[title='+title+']')[0].dispose();
                $$('#' + this.elid + ' .tab').filter('[id='+title+']')[0].dispose();
        },
       
        next: function(){
                var nextTab = this.activeTitle.getNext();
                if(!nextTab) {
                        nextTab = this.titles[0];
                }
                this.activate(nextTab);
        },
       
        previous: function(){
                var previousTab = this.activeTitle.getPrevious();
                if(!previousTab) {
                        previousTab = this.titles[this.titles.length - 1];
                }
                this.activate(previousTab);
        }
		/**/
});

var ajaxLinks = new Class({
        Implements: [Options, Events],
		options: {
		},
		
		initialize: function(view, options) {
            this.setOptions(options);
            
			// Find the ajax links within the freshly loaded tab
			links = $$("#"+options.update+" a[rel=ajax]");
                        								
			links.each(function(item){
				var li = item.getParent('li');
				item.addEvents({
					'click': function(event){
						if(event) event.preventDefault(); 
                        item.blur();		
                   		
                        
                        tab = item.getParent('.tab').get('id')
                        
                        elid = item.getParent('.content').getParent().get('id')                        
                        
						href = item.get('href');
						frag = href.substring(href.lastIndexOf('/')+1);
						location.href = '#' + elid.replace('-','_')+'^'+tab+'^'+frag.replace('#','');
						viewstate = null;
                   		
                   		/*
						href = item.get('href');
						frag = href.substring(href.lastIndexOf('/')+1)
						location.href = '#' + frag;
                   		*/
                   		if(!item.hasClass('.active')){
                   			if(li && !li.hasClass('active')){
                   				li.getParent('ul').getChildren('li').removeClass('active');
                   			}
                   			activePanel = $(this.options.update);
               				activePanel.set('html', this.options.ajaxLoadingText);
			                this.options.url = this.options.urlBase + '?fr=' + item.href;
			                this.options = $extend(this.options,{onSuccess: function(responseText){
			                	var enableAjax = new ajaxLinks(this, this.options);
			                }});
			                var req = new Request.HTML(
			                	this.options
			                ).send();
                   		}
					}.bind(this)
				})
			}.bind(view))
		}

})