document.observe("dom:loaded", function() {
  __pageStyles._init();
  __roundCorners._init();
  __toolTipImages._init();
  __newsSlider._init();
});

var __newsSlider = {
  delaytime : 5,
  _init : function()
  {
    if($$('.blog-content').length > 0)
    {
      $$('.blog-content').each(function(el,i){
        if(el.getElementsByClassName('postWrapper'))
        { 
          items = el.getElementsByClassName('postWrapper');

          if(items.length >1)
          {
            el.slider = {
              items : items,
              current : 0,
              next : 1,
              hide : function()
              {
                if(this.current >= this.items.length-1) this.next = 0;
                else this.next++;
                
                new Effect.Fade(this.items[this.current], {
                  duration:1,
                  to:0,
                  afterFinish : function()
                  {
                    this.items[this.current].setStyle({'display':'none'});
                    this.items[this.next].setStyle({'display':'block'}).setOpacity(0);

                    new Effect.Fade(this.items[this.next], {
                      duration:1,
                      from: 0, to:1,
                      afterFinish : function()
                      {
                        this.current = this.next;
                        this.hide.bind(this).delay(__newsSlider.delaytime);
                      }.bind(this)
                    });
                  }.bind(this)
                });
              }
            };
            
            el.slider.hide.bind(el.slider).delay(__newsSlider.delaytime);
          }
        }
      })
    }
  } 
}


var __toolTipImages = {
  items : null,
  
  _init : function()
  {
    if($$('#product_addtocart_form .products-grid li').length > 0)
    {
      this.items = $$('#product_addtocart_form .products-grid li');
      this.items.each(function(el,i){
        el.observe('mouseover',function(e){
          __toolTipImages._show(this,e);
        });
        el.observe('mouseout',function(e){
          __toolTipImages._hide(this,e);
        });
      })
    }
  },
  
  _show : function(item,e)
  {
    if($('product_addtocart_form').hasClassName('multiple-add') && !this.tip)
    {
      this._hide();
      if(item.getElementsByTagName('img')[0])
      {
        this.tip = new Element('div',{
          'id'    : 'imageToolTip'
        })
        .setStyle({
          'position' : 'absolute',
          'height'   : parseInt(item.getElementsByTagName('img')[0].style.height)+'px',
          'width'    : parseInt(item.getElementsByTagName('img')[0].style.width)+'px',
          'top'      : (e.pointer().y+20)+'px',
          'left'     : (e.pointer().x+20)+'px',
          'background' : '#fff',
          'border'   : '.5em solid #fff'
        });
        
        img =  item.getElementsByTagName('img')[0].cloneNode(true); 
        Element.insert(this.tip, img);
        $$('body')[0].insert(this.tip);        

        item.observe('mousemove',function(e){
          if($('imageToolTip'))
          {
            posx = e.pointer().x - Math.round($('imageToolTip').getWidth()/5) + 20;
            if((minus = $$('body')[0].getWidth()+$$('body')[0].scrollLeft - (posx + $('imageToolTip').getWidth() + 20)) < 0)
              posx+=minus;
            else if(posx<10)
              posx = 10;               

            $('imageToolTip').setStyle({
              top: (e.pointer().y - $('imageToolTip').getHeight() - 10)+'px',
              left: (posx-$('imageToolTip').getWidth()/2)+'px'
            });
          }
        });

      }
    }
  },
  
  _hide : function(item,e)
  {
    if($('imageToolTip'))
    {
      $('imageToolTip').remove();
      this.tip = null;
    }
  },
  
  _move : function(e)
  {
  }
}


var __pageStyles = {
  _init : function()
  {
    // place the footer at the absolute bottom of the page
    this._placeFooter();
    window.onresize = function() { this._placeFooter(); }.bind(this);
    
    // scrollize product-grids
    $$('.products-grid.scrollme').each(function(el,i){
      this._scrollize(el);
    }.bind(this));
    
    // add hover effect in ie6
    if(Prototype.Browser.IE && typeof window.XMLHttpRequest == "undefined")
    {
      $$('button').each(function(el,i){
        el.observe('mouseover',function(){ this.addClassName('highlight'); });
        el.observe('mouseout',function(){ this.removeClassName('highlight'); });
      });
    }
    
    // add cellpadding/-spacing in ie
    if(Prototype.Browser.IE)
    {
      for(i=0; i<$$('table').length; i++)
      {
        $$('table')[i].writeAttribute('cellpadding', '0');
        $$('table')[i].writeAttribute('cellspacing', '0');
      }
    }
    // restyle all selectboxes
    
    // switch hero images
    
    if($('hero-image'))
    {
      if(span = $('hero-image').getElementsByTagName('span')[0])
      {
        if($(span).getAttribute('rel'))
        {
          files = $(span).getAttribute('rel').split('::');

          // if flash is found, try to insert it...
          if(files[1]!='' && swfobject && swfobject.hasFlashPlayerVersion("8"))
          {
            $(span).setAttribute('id','hero-swf');
            $(span).setStyle({'backgroundImage':'none','display':'block'});
            swfobject.embedSWF(files[1], 'hero-swf', "505", "900", "7", false, false, {'menu':false,'wmode':'transparent','salign':'tl'}, false);
          }
          else if((bg = $(span).getStyle('backgroundImage')) && files[0]!='' && !(Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined")))
          {
            if(bg = bg.replace("url(", "").replace(")", "").replace(/"/g, ''))
            {
              if(bg!=files[0])
              {
                $(span).setStyle({'backgroundImage':'url("'+files[0]+'")'});
              }
            }
            $(span).setStyle({'display':'block'});
          }
          else
          {
            $(span).setStyle({'display':'block'});
          }
        }
      }
    }
/*
    $$('select').each(function(el,index){
      if(tmp = new this._styleSelectboxes(el))
      {
        el.mySelect = tmp.init();
        delete tmp;
      }
    });
*/
  },
  
  _placeFooter : function()
  {
    cntheight = $('header').getHeight() + $$('.page')[0].getHeight() + $('footer').getHeight();
/*
    if(typeof(this.debug)=='undefined')
    {
      this.debug = new Element('div',{'style':'position:absolute;top:50%;left:50%;margin-top:-100px;margin-left:-200px;width:400px;height:200px;background:#ff0000;'});
      Element.insert($$('body')[0], { 'bottom' : this.debug});
    }
    this.debug.update(cntheight+" / "+document.viewport.getHeight());
*/
    if(document.viewport.getHeight()>=cntheight) $('footer').setStyle({'margin-bottom':0,'bottom':0});
    else $('footer').setStyle({'margin-bottom':0,'bottom':'auto'});
  },
  
  _scrollize : function(grid)
  {
    space = 20;
    
    elements = grid.getElementsByClassName('item');
    if((number = elements.length)>0)
    {
      ml = elements[0].getStyle('marginLeft'); if(ml && ml.indexOf('em')>-1) ml = parseFloat(ml)*10; else ml = parseInt(ml); 
      mr = elements[0].getStyle('marginRight'); if(mr && mr.indexOf('em')>-1) mr = parseFloat(mr)*10; else mr = parseInt(mr);

      li_width = elements[0].getWidth()+ml+mr;
      maxitems = Math.floor(grid.getWidth()/li_width);
  
      if(number > maxitems)
      {
        mt = elements[0].getStyle('marginTop'); if(mt.indexOf('em')>-1) mt = parseFloat(mt)*10; else mt = parseInt(mt);
        mb = elements[0].getStyle('marginBottom'); if(mb.indexOf('em')>-1) mb = parseFloat(mb)*10; else mb = parseInt(mb);
        li_height = elements[0].getHeight()+mt+mb;
        
        grid_width = (li_width * number);
        
        for(i=maxitems; i<number; i=i+maxitems)
        {
          elements[i].setStyle({'marginLeft':(ml+space)+'px'});
          grid_width+=space;
        }
        
        grid.setStyle({
          height : li_height+'px',
          overflow : 'hidden'
        });
    
        wrapper = new Element('div',{
          'class' : 'products-grid-wrapper'
        })
        .setStyle({
          height   : grid.getHeight()+'px',
          width    : grid.getWidth()+'px',
          overflow : 'hidden'
        });
        grid.wrap(wrapper);

        grid.setStyle({width : grid_width+'px'});
        
        pages = new Element('div',{'class':'pages'});
        
        Element.insert(wrapper,{ 'before' : pages});

        pages.pager = {
          container : pages,
          pages : Math.ceil(number/maxitems),
          cur_page : 0,
          wrapper : wrapper,
          stage : grid,
          li_width : li_width,
          maxitems : maxitems,
          space : space,
          is_moving : false,
          init : function()
          {
            this.prevButton = new Element('a',{'class':'previous current','href':'javascript:void(0)'}).update('&lt;').observe('click', function(){ this.previous() }.bind(this));
            this.nextButton = new Element('a',{'class':'next','href':'javascript:void(0)'}).update('&gt;').observe('click', function(){ this.next() }.bind(this));

            Element.insert(this.container,{ 'top' : this.prevButton } );

            for(i=0; i<this.pages; i++)
              Element.insert(this.container,{ 'bottom' : new Element('a',{'class':'page'+(i==0 ? ' current' : ''),'rel':i,'href':'javascript:void(0)'}).update(i+1).observe('click', function(){ pager.show(this.rel); }.curry(pager=this)) } );

            Element.insert(this.container,{ 'bottom' : this.nextButton } );
          },
          previous : function()
          {
            if(this.cur_page-1>=0) this.show(this.cur_page-1);
          },
          next : function()
          {
            if(this.cur_page+1<=this.pages) this.show(this.cur_page+1);
          },
          show : function(num)
          {
            num = parseInt(num);
            if(num>=0 && num<=this.pages-1 && num!=this.cur_page && !this.is_moving)
            {
              this.is_moving = true;
              t = this.container.select('a').each(function(el,i){el.removeClassName('current');});
              this.container.getElementsByClassName('page')[num].addClassName('current');
              
              tox = num>0 ? (this.li_width * maxitems) * num + (this.space*(num)) : 0;

              new Effect.Morph(this.stage, { 
                style: 'left:'+(tox*-1)+'px', 
                duration: .5,
                transition: Effect.Transitions.sinoidal,

                afterFinish:function(){ this.is_moving = false; }.bind(this)  
              });

              if(num<=0) this.prevButton.addClassName('current');
              else if(num>=this.pages) this.nextButton.addClassName('current');
              this.cur_page = num;
            }
          }
        };
        
        pages.pager.init();
      }
    }
  },
  
  _decorateCheckoutButtons : function(msg)
  {
    if(typeof(msg)=='string')
    {
      $$('.no-checkout').each(function(el,i){
        el.disabled = false;
        el.onclick = false;
        $(el).observe("click", function(){
          alert(msg);
          return false;
        }.curry(msg))
      });
    }
  },

  _styleSelectboxes : function(el)
  {
    if(el.getElementsBySelector('option').length>0)
    {
      returnObj = {
        object : el,
        options : el.getElementsBySelector('option'),
        init : function()
        {
          list = new Element('div',{
            'class' : 'selectbox'
          })
          .observe('mouseover', function(){
            this.addClassName('selected');
          })
          .observe('mouseout', function(){
            this.removeClassName('selected');
          });
          
          for(i=0; i<this.options.length; i++)
          {
            option = this.options[i];
            
            if(!option.readAttribute('selected'))
            {
              li = new Element('p',{
                'class' : 'option prior-'+(i+1),
                'rel' : i
              })
              .observe('click', function(){
                if(!this.hasClassName('selected'))
                {
                  $A(arguments)[0].mySelect.options.each(function(el,i){ el.selected = false; });
                  $A(arguments)[0].mySelect.options[this.readAttribute('rel')].selected = true;
                  if($A(arguments)[0].onchange) $A(arguments)[0].onchange();
                }
              }.curry(this.object))
              .observe('mouseover', function(){
                this.addClassName('selected');
              })
              .observe('mouseout', function(){
                this.removeClassName('selected');
              })
              .update(option.text);
              
              Element.insert(list,li);
            }
            else
            {
              li = new Element('p',{
                'class' : 'header'
              })
              .update('<span>'+option.text+'</span>');
              
              Element.insert(list,{ 'top': li });
            }
          }
          Element.insert(this.object, { 'before': list} );
  //        this.object.setStyle('display','none');
  
  
  
          return this;
        }
      }
      return returnObj;
    }
    return null;
  }
}

__roundCorners = {
  elements_with_borders : new Array(
                            // {id:'.products-grid .item',c:['tl','tr','bl','br'],b:false},
                            {id:'#submenu',c:['tl','tr','t','bl','br','b'],b:false},
                            {id:'.page-title',c:['tl','tr','t','bl','br','b'],b:false},
                            {id:'.sidebar .block-account',c:['tl','tr','t','bl','br','b'],b:false}                            
                          ),
  _init : function(){
    if(Prototype.Browser.IE && typeof window.XMLHttpRequest != "undefined")
    {
      for(i=0; i<this.elements_with_borders.length; i++)
      {
        if($$(this.elements_with_borders[i].id).length>0)
        {
          for(j=0; j<$$(this.elements_with_borders[i].id).length; j++)
          {
            for(k=0; k<this.elements_with_borders[i].c.length; k++)
            { 
              Element.insert($$(this.elements_with_borders[i].id)[j],{ 'bottom' : new Element('span', {'class':'rc'+(this.elements_with_borders[i].b ? ' wb' : '')+' '+this.elements_with_borders[i].c[k]}) } );
            }
          }
        }
      }      
    }    
  }
}


var switch_optionImages = {
  changeOptionimage : function(attribute_id,option_id)
  {
    
    if(typeof($$('.product-large-image img')[0]) != 'undefined')
    { 
      if(typeof(switch_optionImages.originalImage)=='undefined')
        switch_optionImages.originalImage = $$('.product-large-image img')[0].src;
      
      if(typeof($$('.a'+attribute_id+'_o'+option_id)[0])!='undefined')
        $$('.product-large-image img')[0].src = $$('.a'+attribute_id+'_o'+option_id)[0].rev;
      else
        $$('.product-large-image img')[0].src = switch_optionImages.originalImage;
    }
    
    options = spConfig.getAttributeOptions(attribute_id);
    
    if(typeof(options)!='undefined')
    {
      for(i=0; i<spConfig.getAttributeOptions(attribute_id).length; i++)
      {
        if(spConfig.getAttributeOptions(attribute_id)[i].id == option_id)
        {
    
          if(typeof($$('.not-deliverable')[0])!='undefined')
          {
            if(parseInt(spConfig.getAttributeOptions(attribute_id)[i].qty)<=0)
              $$('.not-deliverable')[0].setStyle({display:'inline'});
            else
              $$('.not-deliverable')[0].setStyle({display:'none'});
          }
  
          break;
        }
      }
    }
  }
}
