var lemur_tabs = new Hash();
Event.observe(window,'load',function(){
  $$(".tabs_container").each(function(el){
    // lemur_tabs.push(new LemurTabs(el));
    lemur_tabs.set(el.id, new LemurTabs(el));
  });
});

var LemurTabs = Class.create();
LemurTabs.prototype = {
  initialize:function(container){
    this.container = container;
    this.loading_icon = new Element('div', {'class': 'loading','style':'display:none'}).update('One moment...');
    this.container.insert(this.loading_icon);
    
    this.id = container.id;
    this.tabs = new Hash();
    this.tab = null;

    // binds click observer to each tab
    container.select('.tab').each((function(el){
      el.observe('click',(function(evt){
        this.show_or_load_new(el, el.href, {name:el.readAttribute('alt')});
        // this.show_or_load(el, el.href, {name:el.readAttribute('alt')});
        // this.show_tab(el);  //right now for handleing the styles .. should prob merge into above someway

        Event.stop(evt || window.event);  // $(evt).stop; ... a return false for the href
      }).bindAsEventListener(this))
      
      this.tabs.set(el.readAttribute('alt'), new LemurTab(el));
    }).bind(this));
    this.tab = this.tabs.get(container.down('.content_box_lgrey_tabs_selected a').readAttribute('alt'));
    
    // PROB SHOULD DEFINE THIS ELSEWHERE ... maybe merge with above tabs for more of a click/cache overall observer
    $(this.id).select('.your_office_connect_jumps').each((function(el_group){
      el_group.select('a').each((function(el){
        // el.href = 'javascript://';
        el.observe('click',(function(evt){
          //this.search_lead(el.innerHTML);
          this.show_or_load(el, el.href, {page:1, sort:el.innerHTML})          
          Event.stop(evt || window.event);  // $(evt).stop; ... a return false for the href
        }).bindAsEventListener(this));
      }).bind(this));
    }).bind(this));
        
  },
    
  show_or_load_new:function(el, url, options){
    options.name = (options.name || this.tab.name);
    options.page = (options.page || this.tabs.get(options.name).page);
    options.sort = (options.sort || this.tabs.get(options.name).sort);
    options.refresh = (options.refresh || false);        
    
    var cache = $(this.id).down('.tab_cache');
    var tab_cache = cache.down('.tab_' + options.name);
    var lkup = this.id + "_" + options.name + "_page_" + options.page + "_sort_" + options.sort;    
    
    if(el.readAttribute('alt') == this.tab.name && !options.refresh){
      // if clicking on a tab that is already open ... show the 'first' page of that view    
      this.show_tab_cache(options.name);
      
    } else if($(lkup) && !options.refresh){
      // if last cached attribute is set ... and cached element id does exist ... just show it      
      this.show_tab_cache(options.name, lkup, options);
      
    } else if(!url.blank() && url != "javascript://" && url != "#"){
      // if there is a url ... go get it
      this.load_tab_cache(tab_cache, url, options);
    } else {
      this.switch_to_tab(options.name);
      this.switch_to_tab_content(options.name);
    }
    
    this.tab = this.tabs.get(options.name);
  },
  show_tab_cache_default:function(name, lkup){
    name = name || this.tab.name;
    lkup = lkup || $(this.id).down('.tab_' + name).down();

    this.tabs.get(name).page = 1;
    this.tabs.get(name).sort = lkup.id.match(/sort_(\w+?)(_.*)*$/)[1]; 
    
    Element.addClassName(lkup, 'tab_cache_displayed'); 
    Effect.Appear(lkup, {duration:0.5});
  },
  show_tab_cache:function(name, lkup){    
    this.size_tab_contents($(this.id).down('.tab_cache').up('.content'), $(this.id).down('.tab_cache'));
        
    // if moving to a new tab area  
    if(name != this.tab.name) {
      this.switch_to_tab(name)
      this.switch_to_tab_content(name)     
      // lkup = $(this.id).down('.tab_cache .tab_'+name+' .tab_cache_displayed') || lkup; 
    }
            
    // if(refresh == true) 
    //   this.clear_tab_cache();
    // else 
    this.hide_displayed();
    
    if(lkup) {
      this.tabs.get(name).page = lkup.match(/page_(\d+?)(_.*)*$/)[1];
      this.tabs.get(name).sort = lkup.match(/sort_(\w+?)(_.*)*$/)[1]; 
      
      Element.addClassName($(lkup), 'tab_cache_displayed');
      Effect.Appear($(lkup), {duration:0.5});       
    } else {
      lkup = $(this.id).down('.tab_' + name).down();
      this.show_tab_cache_default(name, lkup);
    }
    
    this.resize_tab_contents($(this.id).down('.tab_cache').up('.content'), lkup); 
  },
  load_tab_cache:function(tab_cache, url, options){
    this.size_tab_contents(tab_cache.up('.content'), tab_cache.up('.tab_cache'));
    // this.size_tab_contents(tab_cache.up('.content'), tab_cache.up('.content'));

    // if moving to a new tab area  
    if(options.name != this.tab.name) {
      this.switch_to_tab(options.name)
      this.switch_to_tab_content(options.name)      
    }

    if(options.refresh) 
      this.clear_tab_cache();
    else 
      this.hide_displayed(options.name);      
        
    this.show_loader();
    new Ajax.Updater(tab_cache, url, {
      method:'get', asynchronous:true, evalScripts:true,  
      parameters: {
        tab:  options.name,
        page: options.page,
        sort: options.sort
      },
      insertion: Insertion.Bottom,   //will stack oldest at top for easy cache.down() clear later if need be    
      onComplete: (function(request){
        this.hide_loader();
        //$(this.id).down('.tab_cache').up('.content').morph('height:' + $(this.id).down('.tab_cache').getDimensions().height.toString()+'px');
        tab_cache.hide();
        Effect.Appear(tab_cache, {duration:0.5})
        this.resize_tab_contents(tab_cache.up('.content'), tab_cache);        
      }).bind(this)
    }); 
    
    this.tabs.get(options.name).page = options.page;
    this.tabs.get(options.name).sort = options.sort;         
  },  
  switch_to_tab:function(name){
    // this.tab = this.tabs.get(name);
    var tab = this.tabs.get(name);
    
    this.container.select('.tab .grey_corner').invoke('hide');    
    this.container.select('li').invoke('removeClassName', 'content_box_lgrey_tabs_selected');

    $(tab.id).select('.grey_corner').invoke('show');
    $(tab.id).up('li').addClassName('content_box_lgrey_tabs_selected');    
  },
  switch_to_tab_content:function(name){
    $(this.id).down('.tab_cache .tab_' + this.tab.name).hide(); // old content
    $(this.id).down('.tab_cache .tab_' + name).show();          // new content
  },  
  hide_displayed:function(name){
    // prep area for newly displyed content by hiding old content in 
    $(this.id).down('.tab_cache .tab_' + (name || this.tab.name)).select('.tab_cache_displayed').invoke('hide').invoke('removeClassName', 'tab_cache_displayed');
  },
  clear_tab_cache:function(name){
    if(name){  // clear this one cache
      this.tabs.get(name).page = 1;
      $(this.id).down('.tab_cache .tab_'+name).update();
    } else {      // clear all caches for this tab group      
      this.tabs.each((function(el){el.page = 1}));
      $(this.id).down('.tab_cache').select('.tab_cache_group').invoke('update');
    }
  },
  refresh_tab:function(name){
    var cache = $(this.id).down('.tab_cache');
    var el = $(this.tabs.get(name).id);
    // this.show_or_load(cache, el.href, {name:name, page:1, refresh:true});
    this.show_or_load_new(cache, el.href, {name:name, page:1, refresh:true});
  },
  size_tab_contents:function(target, source){
    var height = $(source).getDimensions().height;

    if($(this.id).down('.tab_contents'))    
      height = Math.max(parseInt($(this.id).down('.tab_contents').getStyle('min-height') || 0), height)
    
    $(target).setStyle({height: height.toString()+'px'});
  },
  resize_tab_contents:function(target, source){
    var height = $(source).getDimensions().height;

    if($(this.id).down('.tab_contents'))
      height = Math.max(parseInt($(this.id).down('.tab_contents').getStyle('min-height') || 0), height)

    new Effect.Morph($(target), {
      style: {
        height: height.toString()+'px'
      },
      afterFinish: (function(){ 
        $(target).setStyle({height:'auto'}) 
      }).bind(this)
    })
  },

  
    
  
  show_tab:function(el){
    this.tab = this.tabs.get(el.readAttribute('alt'));
    var name = this.tab.name
        
    // update el's css to show selected tab and deselect old tab
    this.container.select('.tab .grey_corner').invoke('hide');    
    this.container.select('li').invoke('removeClassName', 'content_box_lgrey_tabs_selected');
    el.select('.grey_corner').invoke('show');
    el.up('li').addClassName('content_box_lgrey_tabs_selected');    
  },
  show_or_load:function(el, url, options){
        
    var name = (options.name || this.tab.name);
    var page = (options.page || this.tabs.get(name).page);
    var sort = (options.sort || this.tabs.get(name).sort);
    var refresh = (options.refresh || false);
    var lkup = this.id + "_" + name + "_page_" + page + "_sort_" + sort;
    var cache = $(this.id).down('.tab_cache');
    var tab_cache = cache.down('.tab_' + name);

    cache.up('.content').setStyle({
      height:cache.getDimensions().height.toString()+'px'}
    );    
    if(refresh) cache.select('.tab_cache_group').invoke('update');    

    // if moving to a new tab area 
    if(name != this.tab.name){
      cache.down('.tab_' + this.tab.name).hide();
      tab_cache.show();
      lkup = tab_cache.down('.tab_cache_displayed') || lkup;
      
      // switches to proper tab_cache if not called directly from tab
      if(!el.hasClassName('tab') && this.container.down('.content_box_lgrey_tabs_selected a'))
        this.show_tab($(this.tabs.get(name).id));
    } 
    tab_cache.select('.tab_cache_displayed').invoke('hide');
    tab_cache.select('.tab_cache_displayed').invoke('removeClassName', 'tab_cache_displayed');        
    

    if(el.readAttribute('alt') == this.tab.name && !refresh){
      // if clicking on a tab that is already open ... show the 'first' page of that view
      // console.log("default: " + tab_cache.down().id)
      tab_cache.up('.content').morph('height:' + tab_cache.down().getDimensions().height.toString()+'px');
      Effect.Appear(tab_cache.down(), {duration:.5});
      Element.addClassName(tab_cache.down(), ('tab_cache_displayed')); 
      page = 1;
      sort = tab_cache.down().id.split('_sort_')[1];
    } else if( $(lkup) ){
      // if last cached attribute is set ... and cached element id does exist ... just show it
      // console.log("cached: " + $(lkup).id)
      tab_cache.up('.content').morph('height:' + $(lkup).getDimensions().height.toString()+'px');
      Effect.Appear($(lkup), {duration:.5});
      Element.addClassName($(lkup), ('tab_cache_displayed'));      
    } else {
      // otherwise query for it    
      // console.log("fetched")
      if(url != "javascript://" && url != ""){
        this.show_loader();
        new Ajax.Updater(tab_cache, url, {
          method:'get', asynchronous:true, evalScripts:true,  
          parameters: {
            tab:  name,
            page: page,
            sort: sort
          },
          insertion: Insertion.Bottom,   //will stack oldest at top for easy cache.down() clear later if need be    
          onComplete: (function(request){
            this.hide_loader();
            cache.up('.content').morph('height:' + cache.getDimensions().height.toString()+'px');                   
            tab_cache.hide();
            Effect.Appear(tab_cache, {duration:.3});            
          }).bind(this)
        });      
        
      }
    }
          
    this.tabs.get(name).page = page;
    this.tabs.get(name).sort = sort;  

  },
  
  
  
  show_loader:function(){this.loading_icon.show()},
  hide_loader:function(){this.loading_icon.hide()}
}

var LemurTab = Class.create();
LemurTab.prototype = {
  initialize:function(el){
    this.name = el.readAttribute("alt");
    this.id = el.identify();
    this.cache_list = [];
    this.page = 1;
    
    current = el.up('.tabs_container').down('.tab_cache .tab_'+this.name+' .tab_cache_displayed');
    this.sort = current ? current.id.split('_sort_')[1] : 'updated';
  }
}
