Element.addMethods({
  store: function(element, key, value) { 
    if (Object.isUndefined(this[$(element).identify()]) || !Object.isHash(this[$(element).identify()]))
        this[$(element).identify()] = $H();
    this[$(element).identify()].set(key,value);
    return element;
  },
  retrieve: function(element,key) {
    return this[$(element).identify()].get(key);
  }  
});

var CarouselModuleProductSmallImage = {
    createItem:function(data){
        elm = new Element('img',{'src':data.small})
        .observe('click',function(event){
            //this.select(event.element().up('li').retrieve('index'));
            $('carousel-product-large-image').fire('select:item',{innerIndex:event.element().up('li').retrieve('index')});                                     
        }.bind(this)).wrap('li').store('index',data.index).store('title',data.title);
        return elm;
    }
};

var CarouselModuleProductLargeImage = {
    createItem:function(data){        
        elm = new Element('img',{'src':data.large})
        .observe('click',function(event){
            //this.select(event.element().up('li').retrieve('index'));            
        }.bind(this)).wrap('li').store('index',data.index).store('title',data.title);        
        return elm;
    }
};



var CarouselModuleImage = {    
    createItem:function(data){
        elm = new Element('img',{'src':data.image})
        .observe('click',function(event){
            this.select(event.element().up('li').retrieve('index'));            
        }.bind(this)).wrap('li').store('index',data.index).store('title',data.title);
        return elm;
    }
};

var CarouselModuleLinkSpace =
{
    createItem:function(data){        
        if (data.index)
        {               
            elm = new Element('div',{'class':'bt_header_left'});             
            span = new Element('span').update(data.title).wrap('a',{'href':'#'+data.index});            
            divDelete = new Element('div',{'class':'b-tabselector-closebutton'});                        
            
            divDelete.observe('click',function(event){                
                this.notify('onDelete',event);
            }.bind(this));                            
            elm = elm.insert(span).insert(divDelete).wrap('li').store('index',data.index);                                                  
            elm.observe('click',function(event){  
                //$('sportaltabs').fire('tab:select',{tab:event.element().up('li').retrieve('index')});                                               
                this.notify('item:onClick',event);
            }.bindAsEventListener(this));            
            Droppables.add(elm, {onHover: Controller.sportal.dragWidgetInTab.bind(Controller.sportal), overlap: 'vertical'});                 
            return elm;
        }
        else
        {                        
            elm = new Element('div',{'class':'bt_header_left'});
            span = new Element('span').update(data.title).wrap('a');                          
            elm = elm.insert(span).wrap('li');                                      
            elm.observe('click',function(event){      
                this.notify('onClickNewTab', event);        
            }.bind(this));
            return elm;
        }
    }
    ,updateItem:function(event)
    {        
        var elm = this.findItem(event.memo.innerIndex).element;
        elm.store('title',event.memo.title);        
        elm.select('a').last().innerHTML = event.memo.title; 
        elm.store('dim',elm.getWidth());
        this.calculateBlocks().checkButtons();        
    }    
};

var CarouselModuleLink = {
    createItem:function(data){
        elm = new Element('a',{'href':data.link}).update(data.title)
        .observe('click',function(event){                                    
        }.bind(this)).wrap('li').store('index',data.index).store('title',data.title);        
        return elm;
    }
    ,updateItem:function(event)
    {        
        var elm = this.findItem(event.memo.innerIndex).element;
        elm.store('title',event.memo.title);        
        elm.select('a').last().innerHTML = event.memo.title; 
        elm.store('dim',elm.getWidth());
        this.calculateBlocks().checkButtons();        
    }    
};

var SCarousel = Class.create({
    initialize:function(container)
    {
        if (!$(container))
            return;
            
        this.container = $(container);        
        this.container.insert(new Element('ul'));        
        this.current;
        this.locked = false;        
        this.block = {list: $A(),current:null}; 
        this.observers = $A();       
        this.options = Object.extend(
        {
            'buttonShowStyle' : 'inline'
            ,'slideDuration' : 1 
            ,'kicker' : 0
            ,highLight : null
            ,direction:'horizontal'            
        },arguments[1] || {});
        this.containerSize = this.getContainerDimension();
                  
        this.container.observe('insert:item',this.insertItemEvent.bindAsEventListener(this));        
        this.container.observe('select:item',this.selectEvent.bindAsEventListener(this));        
        this.container.observe('update:item',this.updateItemEvent.bindAsEventListener(this));
        this.container.observe('delete:item',this.deleteItemEvent.bindAsEventListener(this));        
        this.container.observe('previous:block',this.previous.bindAsEventListener(this));
        this.container.observe('next:block',this.next.bindAsEventListener(this));                                
    }
    ,addObserver:function(observer)
    {
        this.observers.push(observer);     
        this._cacheObserverCallbacks();
    }
    ,removeObserver:function(element)
    {        
        this.observers = this.observers.reject( function(o) { return o.element==element });
		this._cacheObserverCallbacks();
    }
    ,_cacheObserverCallbacks: function() {    
		['item:onClick','onDelete','onClickNewTab'].each(function(eventName) {		   
			this[eventName+'Count'] = this.observers.select(
				function(o){
				    return o[eventName];
                }                 
			).length;
		}.bind(this));
		
	}
    ,notify: function(eventName, event) {                               
		if(this[eventName+'Count'] > 0)
			this.observers.each( function(o) {
				if(o[eventName])
				{
				    o[eventName](eventName, event);
				}
			});		
	}     
    ,calculateBlocks:function()
    {   
        this.block.list.clear().push(0);        
        var blockWidth = 0;       
        this.container.select('li').each(function(data){            
            if ((blockWidth + data.retrieve('dim')) > this.containerSize)
            {                
                this.block.list.push(this.block.list[this.block.list.size()-1] + blockWidth);                
                blockWidth = 0;
            }
            blockWidth+=this.getDimension(data);
        }.bind(this));
        return this;                
    }
    ,getDimension:function(elm)
    {        
        if ('horizontal' == this.options.direction) return (elm.getWidth() + this.options.kicker);
        else return (elm.getHeight() + this.options.kicker);        
    }
    ,getContainerDimension:function() { return (this.getDimension(this.container) - this.options.kicker);}    
    ,insertItemEvent:function(event)
    {                                           
        item = this.add(event.memo);                 
        this.calculateBlocks().checkButtons();                          
        return item;
    }
    ,deleteItemEvent:function(event) {this.deleteItem(event.memo);}
    ,updateItemEvent:function(event) {this.updateItem(event);}
    ,selectEvent:function(event) {this.select(event.memo.innerIndex);}    
    ,add : function(data)
    {        
        var item = this.createItem(data);
                
        if(!data.insert)            
            this.container.select('ul').last().insert(item);                                    
        else
        {             
            if (data.insert.position.after)                        
                Element.insert(this.container.down('li',data.insert.location),{'after':item});                         
            else                            
                Element.insert(this.container.down('li',data.insert.location),{'before':item});                         
        }        
        return item.store('dim',this.getDimension(item));        
    }
    ,setData:function(json,innerIndex)
    {
        if(this.options.loading && $(this.options.loading))
            $(this.options.loading).remove();              
            
        json.each(function(data){
            this.add(data);
        }.bind(this));
        
        this.calculateBlocks();
        if(!innerIndex)
            {this.block.current = 0;this.checkButtons();}
        else
            {this.select(innerIndex);}
    }    
    ,deleteItem:function(json)
    {           
        var elm;
        if (Object.isElement(json.item))
            elm = json.item;
        else
            elm = this.findItem(json.item).element;
        
        if (elm) {elm.remove();this.calculateBlocks().checkButtons();}
        return this;                
    }
    ,highLight:function(elm,newBlock)
    {     
        if (!this.options.highLight || !elm) return this;  
        
        if (this.current) this.current.removeClassName(this.options.highLight);
            
        elm.addClassName(this.options.highLight);
        this.current = elm;
        if (Object.isNumber(newBlock))
            this.block.current = newBlock;
        return this;                    
    }    
    ,select:function(innerIndex)
    {   
        var elm = this.findItem(innerIndex);                        
        var block = this.findBlock(elm.position);        
        
        if (Object.isNumber(this.block.current) && (this.block.current == block))
            return this.highLight(elm.element,block);
        else        
            return this.move(this.block.list[block],block,elm.element);        
    }
    ,findItem:function(innerIndex)
    {                
        var position = 0;
        var element = this.container.select('li').find(function(s){                 
            position+= s.retrieve('dim');            
            if (innerIndex == s.retrieve('index'))
                return true;
            return false;
        });        
        return {position:position,element:element}
    }
    ,findBlock:function(position) 
    {
        var blockValue = this.block.list.reverse(false).find(function(block){
            if (position > block)
                return true;
            else return false;
        });
        return this.block.list.indexOf(blockValue);        
     }        
    ,createItem:function(data) {return new Element('li').update(data);}       
    ,checkButtons:function()
    {
        if (!this.options.previous && !this.options.next) return this;        
        
        if((this.block.current + 1) == this.block.list.size())            
            $(this.options.next).hide();
        else            
            $(this.options.next).setStyle({'display':this.options.buttonShowStyle});

        if (this.block.current < 1)            
            $(this.options.previous).hide();
        else            
            $(this.options.previous).setStyle({'display':this.options.buttonShowStyle});
        
        return this;
    }
    ,move:function(position,newBlock,newElement)
    {        
        if (this.locked)                                 
             return this;        
        else                    
            this.locked = true;
        
        this.block.current = newBlock;        
        
        if ('horizontal' == this.options.direction)    
            new Effect.Move(this.container.select('ul').last(),{'x':-position,mode:'absolute','duration':this.options.slideDuration,'afterFinish':this.afterMove.bind(this,newElement)});
        else
            new Effect.Move(this.container.select('ul').last(),{'y':-position,mode:'absolute','duration':this.options.slideDuration,'afterFinish':this.afterMove.bind(this,newElement)});                
    }
    ,afterMove:function(newElement) 
    {
        this.checkButtons().highLight(newElement).locked = false;        
    }     
    ,next:function()
    {          
       if (this.block.list.size() > this.block.current)       
            this.move(this.block.list[this.block.current+1],this.block.current+1);       
    }
    ,previous:function()
    {           
        if(this.block.current > 0)        
            this.move(this.block.list[this.block.current-1],this.block.current-1);        
    }    
});

