var avScroll = new Class({

    options: {
		imgWidth: 0,
		scrollRange: 0,
		leftHandle: null,
		rightHandle: null,
		container: null,
		leftClicks: 0,
		rightClicks: 0,
		speed: 500		
	},
	
	initialize: function(options){
	this.setOptions(options)
	
		this.imgWidth = options['imgWidth'];
		this.scrollRange = options['scrollRange'];
		this.leftHandle = options['leftHandle'];
		this.rightHandle = options['rightHandle'];	
		this.container = $(options['container']);

		if($(options['ff'])){
			this.ff = $(options['ff']);
			$(this.ff).addEvent('click',this.fastForward.bindWithEvent(this));
		}
		if($(options['rw'])){
			this.rw = $(options['rw']);
			$(this.rw).addEvent('click',this.speedReverse.bindWithEvent(this));
		}
		
		this.leftClicks = 0;
		this.rightClicks = 0;
		this.speed = options['speed'];		
		$(this.leftHandle).addEvent('click',this.leftClick.bindWithEvent(this));
		$(this.rightHandle).addEvent('click',this.rightClick.bindWithEvent(this));
	},
	leftClick: function(){
				if(this.leftClicks > 0){
					var start= this.leftClicks * this.imgWidth;
					var end = ( this.leftClicks - 1 ) * this.imgWidth;
					//$(this.container).effect('right',{ duration: this.speed, wait:true, transition:Fx.Transitions.Back.easeIn }).start(start,end);
					new Fx.Scroll($(this.container), {
            duration: 500,
            wait: false
          }).start(end, 0);
					this.leftClicks--;
				}
				
				
	},
		
	rightClick: function(){
				var start= this.leftClicks * this.imgWidth;
				var end = (this.leftClicks * this.imgWidth) + this.imgWidth;
				//$(this.container).effect('right',{ duration: this.speed, wait:true, transition: Fx.Transitions.Back.easeIn }).start(start,end);
				if (start < $('innerScroller').getStyle('width').toInt()) {
          new Fx.Scroll($(this.container), {
              duration: 500,
              wait: false
            }).start(end, 0);
  				this.leftClicks++;
  			}
				
	},
	
	fastForward: function(){
				// scroll 4 images to the right, calculate it on base of the clicks and the image width
				var start= (this.leftClicks) * this.imgWidth;			
				var end = (( this.leftClicks + 4 ) * this.imgWidth);
				$(this.container).effect('right',{ duration: this.speed, wait:true, transition:Fx.Transitions.Back.easeIn }).start(start,end);
				this.leftClicks = this.leftClicks +  4;
				
				
	},
	
	speedReverse: function(){
				var start= (this.leftClicks *  this.imgWidth );
				var end = ((this.leftClicks  - 4 ) * this.imgWidth);
				$(this.container).effect('right',{ duration: this.speed, wait:true, transition: Fx.Transitions.Back.easeIn }).start(start,end);
				this.leftClicks-= 4;
				
	}
				
});
avScroll.implement(new Options, new Events);




function updboxcart(t) {
  var EL_cartFly = $('cart_flyo_cont');
  EL_cartFly.setStyle('height', $('cart_flyo_wrap').getStyle('height').toInt() - 15);

  var EF_cartFly = new Fx.Slide(EL_cartFly, {
    transition: 'sine:in',
    duration: 800
  });
  
  if (t > 0) EF_cartFly.hide();
  if (t == 2) EF_cartFly.toggle();
  
  $('tgl_cart_flyo_cont').addEvent('click', function(e) {
    e.stop();
    EF_cartFly.toggle();
    //$('shoppingcart').setStyle('height', 'auto');
  });
  return 1;
}

function updboxprod(e, item) {
  e.stop();

  var chainone = new Chain;
  chainone.chain(item.getElement('.shortbuy').fade('out')).
  chain(item.getElement('.productbox-button2').fade('out')).
  chain(item.getElement('.productbox-button2').setStyle('visibility', 'hidden')).
  chain(item.getElement('.productbox-inside1').tween('height', 65)).
  chain(item.getElement('.productbox-button').setStyle('opacity', '0')).
  chain(item.getElement('.productbox-button').fade('in'));
}

function formpayment() {
  var blockTables = $$('.table-versandart');

  blockTables.each(function(item) {
    var EL_payRad = item.getElement('input[name=payment}');
    var EL_payFly = item.getElement('.table-lastschrift');
    
    var EF_payFly = new Fx.Slide(EL_payFly, {
      transition: 'sine:in',
      duration: 1000
    }).hide();
    
    EL_payRad.addEvent('click', function() {
      blockTables.each(function(item2) {
        if (item != item2) {
          new Fx.Slide(item2.getElement('.table-lastschrift'), {
            transition: 'sine:in',
            duration: 1000
            }).slideOut();
        }
      });
      EF_payFly.slideIn();
    });
  });
}

function reloadcart() { $('cart_flyo_wrap').destroy();
  var req = new Request.HTML({
    url: 'unit_ajax.php?fid=2',
    onComplete: function(html) { $('shoppingcart').empty(); $('shoppingcart').adopt(html); updboxcart(2); } 
  }).send();
}  

window.addEvent('domready', function() {

  if (self != top) {
    if (document.images) {
      top.location.replace(window.location.href);
    }
    else {
      top.location.href = window.location.href;
    }
  }

  $try(function() {
    updboxcart(1)
  });

  if (!$('cart_flyo_cont')) $('shoppingcart').setStyle('visibility', 'hidden');
  
  var p = $try(function() {
    new avScroll({container:'product-bar-container', imgWidth:112, scrollRange:3, leftHandle:'pd-btn-left-scroll',rightHandle:'pd-btn-right-scroll',  speed:700});
    
    var setfirstslide = false;
    var iscroll = $('innerScroller');
    iscroll.setStyle('width', 0);
    var sliderElements = iscroll.getElements('img');
    sliderElements.each(function(item) {
      if (setfirstslide == false && typeof(picLinks) === 'undefined') {
        $('product-detail-view').getElement('img').set('src', item.getParent().href);
        item.set('src', item.alt);
        setfirstslide = true;
      }
      else if ((setfirstslide == false) && (typeof(picLinks[0]) === 'undefined' || (typeof(picLinks[0]) === 'string' && picLinks[0].length < 1))) {
        $('product-detail-view').getElement('img').set('src', item.getParent().href);
        item.set('src', item.alt);
        setfirstslide = true;
      }
      item.addEvent('click', function(e) {
        e.stop();

        var detailpiccont = $('product-detail-view').getElement('img');
        var chgdetailpic = new Fx.Tween(detailpiccont);
        chgdetailpic.start('opacity', 0).chain(function() {
          detailpiccont.set('src', item.getParent().href);

          sliderElements.each(function(item2) {
            item2.set('src', item2.title);
          });
          item.set('src', item.alt);
          this.start('opacity', 1);
        });
      });
      iscroll.setStyle('width', iscroll.getStyle('width').toInt() + 112);
    });
  });

  function loadteaser(el, teasereffect) {
    var teasertarget = 'teaser';
    var teasereff = new Fx.Morph($(teasertarget));
    var teasereffParam = {'opacity': 1};
    
    if (teasereffect == 'left') {
      var teasertarget = 'teaser-product-fly';
      var teasereff = new Fx.Morph($(teasertarget));
      teasereffParam = {'left': [180, 90], 'opacity': [0, 1]};
      teasereff.start({'left': 0, 'opacity': 0});
    }
    else if (teasereffect == 'right') {
      var teasertarget = 'teaser-product-fly';
      var teasereff = new Fx.Morph($(teasertarget));
      teasereffParam = {'left': [0, 90], 'opacity': [0, 1]};
      teasereff.start({'left': 180, 'opacity': 0});
    }


    teasereff.start({'opacity': 0}).chain(function() {
      if (el) var req_url =  el.replace('index.php?', 'unit_ajax.php?fid=4&');
      else var req_url = 'unit_ajax.php?fid=4';
  
      var req = new Request.HTML({
        url: req_url,
        onComplete: function(html) {
          $('teaser').empty();
          $('teaser').adopt(html);
          $(teasertarget).morph(teasereffParam);
          updteaserlr();
          if (!teasereffect) $('teaser-product-fly').setStyle('opacity', 1);
        }
      }).send();
    })
  }
  
  function updteaserlr() {
    var btns = $$('#btn-left', '#btn-right');
    btns.each(function(item) {
      var btn = item.addEvent('click', function(e) {
        e.stop();
        if (item == $('btn-left')) var teasereffect = 'left'; 
        else var teasereffect = 'right';
        loadteaser(item.getElement('a').href, teasereffect);
      });
    });
  }
  
  $try(function() {
    $('teaser').setStyle('opacity', 0);
    loadteaser();
  });

  $try(function() {
    formpayment();
  });
  
  $try(function() {
    chk_matrix_avail(1, 2, $('cart_quantity').getElement('input[name=products_id]').value);
  });  

  function recnew() {
    var btnRecNew = $('rec_new');
    var btnRecSend = $('rec_send');
    var txtRecStart = $('rec_text_start');
    
    btnRecNew.setStyle('visibility', 'hidden');
    
    btnRecNew.addEvent('click', function(e) {
      e.stop();
      btnRecNew.setStyle('visibility', 'hidden');
      txtRecStart.set('text', 'Sie können dieses Produkt einem Freund empfehlen. Füllen Sie hierzu die Formularfelder aus.');
      $$('.recomment-fields').each(function(item) {
        item.setStyle('visibility', 'visible');
      });
    });
    
    btnRecSend.addEvent('click', function(e) {
      e.stop();
      var recformvalid = true;

      $$('.recomment-fields').each(function(item) {
        if (item.getElement('input').value.length > 2) {
          item.getElement('input').setStyle('border-color', '#dddddd');
        }
        else {
          item.getElement('input').setStyle('border-color', '#800204');
          recformvalid = false;
        }
      });
      
      if (recformvalid == true) {
        $$('.recomment-fields').each(function(item) {
          item.setStyle('visibility', 'hidden');
        });
        
        $('rec_prod_url').set('value', location.href);
        
        var req = new Request.HTML({
          method: 'post',
          url: $('rec_form').get('action'),
          onComplete: function() { btnRecNew.setStyle('visibility', 'visible'); txtRecStart.set('text', 'Vielen Dank für Ihre Empfehlung.'); }
        }).post($('rec_form'));
      }
    });
  }
  
  $try(function() {
    recnew();
  });
  
  $try(function() {
    $('btn_avail_notify').addEvent('click', function(e) {
      e.stop();
      if ($('in_avail_notify').value.length < 5) {
        alert("Bitte Mail-Adresse eintragen");
      }
      else {
        var req = new Request.HTML({
          method: 'post',
          url: $('avail_notify_form').get('action'),
          onComplete: function() { alert('Ihre Mail-Adresse wurde eingetragen!'); }
        }).post($('avail_notify_form'));
      }
    });
  });

  $try(function() {
    $('cr_acc_subm').addEvent('click', function(e) {
      e.stop();
      if (check_form($($('parse_form').value)) == true) $($('parse_form').value).submit();
    });
  });
  
  $try(function() {
    $('pg_res_jump_inp').addEvent('click', function(e) {
      e.stop();
      if (location.href.substr(location.href.length - 4, 4) == '.php') {
        var xsep = '?';
      }
      else {
        var xsep = '&';
      }
      location.href = location.href + xsep + 'page=' + $('jump-to').value;
    });
  });

  var xer = $$('.productbox');
 
  xer.each(function(item) {
    $try(function() {
      item.getElement('.productbox-button').getElement('a').addEvent('click', function(e) {
        e.stop();
        var chainone = new Chain;
        chainone.chain(item.getElement('.productbox-button').fade('out')).
        chain(item.getElement('.productbox-button').setStyle('visibility', 'hidden')).
        chain(item.getElement('.productbox-inside1').tween('height', 110));

        var req_url = item.getElement('.productbox-button').getElement('a').href.replace('product_info.php?', 'unit_ajax.php?fid=1&');
        var req = new Request.HTML({  
            method: 'get',  
            url: req_url,
            data: 'fl',  
            onComplete: function() { chainone.chain(item.getElement('.productbox-button2').setStyle('opacity', '0')).chain(item.getElement('.productbox-button2').fade('in')); $try(function() { chk_matrix_avail(1, 2, $('cart_quantity').getElement('input[name=products_id]').value); }); },  
            update: item.getElement('.shortbuy')
        }).send();
        chainone.chain(item.getElement('.shortbuy').fade('in'));
      });
      
      var firstLink = item.getElement('.productbox-button2').getElement('a');
      var lastLink  = item.getElement('.productbox-button2').getElement('a:last-child');
      firstLink.addEvent('click', updboxprod.bindWithEvent(firstLink, item));
      lastLink.addEvent('click', updboxprod.bindWithEvent(lastLink, item));
      firstLink.addEvent('click', function(e) {
        e.stop();

        var req = new Request.HTML({  
          method: 'post',  
          url: item.getElement('.shortbuy').getElement('.cart_quantity').get('action'),
          data: item.getElement('.shortbuy').getElement('.cart_quantity').toQueryString(),  
          update: item.getElement('.shortbuy'),
          onComplete: function() { reloadcart(); item.getElement('.shortbuy').empty(); item.getElement('.produktinfo').tween('opacity', 0, 1); (function() { item.getElement('.produktinfo').fade('out'); }).delay(2000); }  
        }).post(item.getElement('.shortbuy'));

      });
    });
  });


});