//Break from frame
breakFromFrame();

var Site = null;

var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

var mySite = new Class({

  initialize: function( ){

    this.myFX       = $H();
    this.myElements = 0;
    this.menuSearchFormActive = false;
    this.menuSearchFormHeight = 46;
    this.slideMenus = new Array();

    // When set to true, the header animation on the frontpage will stop sliding
    this.stopHeaderAnimation = false;

    //this.initSlideMenus( );   // all pages
    this.articleMouseOver();  // in shop category
    this.articleCompare();    // in shop category
    this.addToCartLinks();    // in shop category

    this.initFontSize ();    // add fontsizefuntions

    if( $('specs' ) )
      this.specsSlide( );

    if( ( oa = $('detailOtherArticles') ) && oa.getStyle('height').toInt() > 300  )
      this.horizontalSlide();

    // banner slides
    $$( '.bannerSlide' ).forEach( function( el ) {
      new ImageSlides( el, (4000) );
    }.bind(this) );
    fourSlides = new ImageSlides2('bannerSlide', 6000);

    // Header animation
    //$$( '#headerAnimation' ).forEach( function( el ) {
    //  new ImageSlides( el, (4000) );
    //}.bind(this) );


  },

  initFontSize: function () {
    this.fontSizes = new Array ( '/layout/default/style.normal.css', '/layout/default/style.bigger.css', '/layout/default/style.biggest.css' );

    // Lookup used fontsize
    if ( !( this.fontSize = Cookie.read ( 'fontSize' ) ) )
      this.fontSize = 0; // Set the default fontsize

    $('fontResizeSmall').addEvent('click', function(e) {
      new Event(e).stop();
      this.fontSize --;
      return this.setFontSize ();
    }.bind( this ) );

    $('fontResizeBig').addEvent('click', function(e) {
      new Event(e).stop();
      this.fontSize ++;
      return this.setFontSize ();
    }.bind( this ) );

    this.setFontSize ( );
  },

  setFontSize: function () {
    if ( !this.fontSizes || this.fontSizes.length == 0 )
      return false;

    if ( this.fontSize < 0 )
      this.fontSize = 0;
    else if ( this.fontSize >= this.fontSizes.length )
      this.fontSize = this.fontSizes.length - 1;

    if ( $('fontSizeCSS') )
      $('fontSizeCSS').destroy();

    if ( this.fontSizes [ this.fontSize ] && this.fontSizes [ this.fontSize ].length > 0 )
    {
      fontCSS = new Element ( 'link' );
      fontCSS.id = 'fontSizeCSS';
      fontCSS.rel = 'stylesheet';
      fontCSS.type = 'text/css';
      fontCSS.href = this.fontSizes [ this.fontSize ];

      fontCSS.injectInside ( document.head );
    }
    Cookie.write ( 'fontSize', this.fontSize, { duration: 30, path: '/' } );

    return false;
  },

  articleMouseOver: function() {
    $$( '.article' ).forEach( function( el )
    {
      if( el.getElement( '.actions' ) )
      {
        ac = el.getElement( '.actions' );
        ac.setOpacity( 0 );

        el.addEvent( 'mouseenter', function( ){

          ac = el.getElement( '.actions' );

          if( this.myFX.get( ac.id ) ) // prevent double animations on 1 element
            this.myFX.get( ac.id ).cancel();

          this.myFX.set( ac.id, new Fx.Tween( ac.id, { property: 'opacity', duration:200 } ).start( 1 ) );
        }.bind( this ) );

        el.addEvent( 'mouseleave', function( ){

          ac = el.getElement( '.actions' );

          if( this.myFX.get( ac.id ) ) // prevent double animations on 1 element
            this.myFX.get( ac.id ).cancel();

          this.myFX.set( ac.id, new Fx.Tween( ac.id, { property: 'opacity', duration:200 } ).start( 0 ) );
        }.bind( this ) );
      }
    }.bind( this ) );

  },

  addToCartLinks: function()
  {

    $$( '.actionOrder' ).forEach( function( el )
    {
      el.addEvent( 'click', function( e ){

        e = new Event(e).stop(); // stop the browser following the href
        this.addToCart( el.getProperty( 'href' ) );
      }.bind( this ) );
    }.bind( this ) );

  },

  addToCart: function( url )
  {
    if ( $('articleOrder') )
    {
      var myAjax = new Request({
                                  url: $('articleOrder').action+'&sub=ajaxRequest',
                                  method: 'post',
                                  evalScripts: true,
                                  data: $('articleOrder'),
                                  onComplete: function( res ) {
                                    $( 'cart' ).set('html', res);
                                    this.highlightElement( $( 'cart' ).getElement( '.new' ) );
                                  }.bind( this )
                              });
      myAjax.send();
    }
    else
    {
      var myAjax = new Request({
                                  url: url+'&sub=ajaxRequest',
                                  method: 'get',
                                  evalScripts: true,
                                  onComplete: function( res ) {
                                    $( 'cart' ).set('html', res);
                                    this.highlightElement( $( 'cart' ).getElement( '.new' ) );
                                  }.bind( this )
                              });
      myAjax.send();
    }
  },

  articleCompare: function( )
  {
    // compare add
    $$( '#webshopCategory .actionCompare' ).forEach( function( el )
    {
      el.addEvent( 'click', function( e ){
        e = new Event(e).stop(); // stop the browser following the href
        //this.addArticleCompare( el.getProperty( 'href' ) );

      }.bind( this ) );
    }.bind( this ) );
  },

  addArticleCompare: function( url )
  {

    var myAjax = new Request({
                                url: url+'&sub=ajaxRequest',
                                method: 'get',
                                evalScripts: true,
                                onComplete: function(response) {

                                    $('articleCompare').set('html', response )

                                    // Broken in IE7 / IE8
                                    // this.highlightElement( $( 'articleCompare' ).getElement( '.new' ) );
                                }

                            })


    myAjax.send();
    return false;
  },

  removeArticleCompare: function( url, articleId )
  {
    var myAjax = new Request({
                                url: url+'&sub=ajaxRequest',
                                method: 'get',
                                evalScripts: true,
                                update: $('articleCompare'),
                                onComplete: function( response ) {

                                    $('articleCompare').set('html', response)

                                    // Broken in IE7 / IE8
                                    // this.highlightElement( $( 'articleCompare' ) );

                                    if ( articleId ) {
                                        if ( $('articleCompareHref_' + articleId) ) {
                                            toggleArticleCompareButtonState( $('articleCompareHref_' + articleId) , false);
                                        }
                                    }

                                }.bind( this )
                             });

    myAjax.send();
    return false;
  },

  /*
   * Specs Slide in article detail
   */
  specsSlide: function( )
  {
    specsDiv = $( 'specs' );
    if ( true || specsDiv.clientHeight > 100 )
    {
      c = specsDiv.getCoordinates();
      specsDiv.setProperty( 'defaultHeight', ( c.height.toInt() - 30 ) ); // -30 is because of strange large whitespace underneath when expanding
      specsDiv.setProperty( 'colapseHeight', 46 );

      specsDiv.setStyles( {
          'overflow':'hidden',
          'height': '46px'
      } );


      // insert close button
      var specsDivClose = new Element( 'a', {
        'id': 'specActionClose',
        'class': 'specAction',
        'href': '#'
      } );

      specsDivClose.setHTML( 'sluiten' );
      specsDivClose.injectAfter( specsDiv );
      specsDivClose.setStyle( 'display', 'none');


      // insert open button
      var specsDivOpen = new Element( 'a', {
        'id': 'specActionOpen',
        'class': 'specAction',
        'href': '#'
      } );

      specsDivOpen.setHTML( 'meer specificaties' );
      specsDivOpen.injectAfter( specsDiv );
      specsDivOpen.setStyle( 'display', 'block');



      specsDiv.addEvent( 'mouseenter', function(ev)
      {
        if( this.myFX.get( 'specsSlide' ) ) // prevent double animations on 1 element
        this.myFX.get( 'specsSlide' ).stop();

        this.myFX.set( 'specsSlide', new Fx.Tween( $( specsDiv ), { property: 'height', duration:500, onComplete: function() {
        $( 'specActionOpen' ).setStyle( 'display', 'none' );
        $( 'specActionClose' ).setStyle( 'display', 'block' );
        } } ).start( specsDiv.getProperty( 'defaultHeight' ) ) );
      }.bind( this ) );

      specsDivClose.addEvent( 'click', function(ev)
      {
        new Event(ev).stop();

        if( this.myFX.get( 'specsSlide' ) ) // prevent double animations on 1 element
        this.myFX.get( 'specsSlide' ).stop();

        this.myFX.set( 'specsSlide', new Fx.Tween( $( specsDiv ), { property: 'height', duration:500, onComplete: function() {
        $( 'specActionClose' ).setStyle( 'display', 'none' );
        $( 'specActionOpen' ).setStyle( 'display', 'block' );
        specsDiv.removeEvents ('mouseenter');

        } } ).start( specsDiv.getProperty( 'colapseHeight' ) ) );
      }.bind( this ) );

      specsDivOpen.addEvent( 'click', function(ev)
      {
        new Event(ev).stop();

        if( this.myFX.get( 'specsSlide' ) ) // prevent double animations on 1 element
        this.myFX.get( 'specsSlide' ).stop();

        this.myFX.set( 'specsSlide', new Fx.Tween( $( specsDiv ), { property: 'height', duration:500, onComplete: function() {
        $( 'specActionOpen' ).setStyle( 'display', 'none' );
        $( 'specActionClose' ).setStyle( 'display', 'block' );
        } } ).start( specsDiv.getProperty( 'defaultHeight' ) ) );
      }.bind( this ) );

    }
  },

  /**
   * manual carousel by mouseclick slides the content
   */
  horizontalSlide: function()
  {
    var mainSlideDiv = $('detailOtherArticles');

    // get the content items
    var otherArt      = mainSlideDiv.getElements( '.item' );
    var theSlideWidth = otherArt.length * 150;
    mainSlideDiv.setProperty( 'itemsLength', otherArt.length );

    mainSlideDiv.setStyles( {
      'display': 'block',
      'position':'relative',
      'height': '200px',
      'overflow': 'hidden'
    } );
    mainSlideDiv.getElements( '.item' ).setStyles( 'background-color', 'green' );

    // left nav
    var leftSlideNav = new Element( 'div', {
      'id':'leftSlideNav',
      'class':'slideNav',
      'styles': {
        'left':'0px'
      }
    } );

    leftSlideNav.addEvent( 'click', function(){
      this.horizontalSlideNow( $('leftSlideNav') );
    }.bind(this) );

    // right nav
    var rightSlideNav = new Element( 'div', {
      'id':'rightSlideNav',
      'class':'slideNav',
      'styles': {
        'background-image':'url(modules/webshop/gfx/bg_rightSlideNav.gif)',
        'right':'0px'
      }
    } );

    rightSlideNav.addEvent( 'click', function(){
      this.horizontalSlideNow( $('rightSlideNav') );
    }.bind(this) );

    // trap the content inside a sliding div
    var theSlideDiv = new Element( 'div', {
      'id': 'theSlideDiv',
      'styles': {
        'width':theSlideWidth+'px'
      }
    } );

    otherArt.each( function( el ){
      el.injectInside( theSlideDiv );
    } );

    this.slideTo = 4;

    mainSlideDiv.setHTML( '' ); // clear the html
    leftSlideNav.injectInside( mainSlideDiv );
    rightSlideNav.injectInside( mainSlideDiv );
    theSlideDiv.injectInside( mainSlideDiv );
  },

  horizontalSlideNow: function( el )
  {
    var mainSlideDiv  = $('detailOtherArticles');
    var itemsLength   = mainSlideDiv.getProperty( 'itemsLength' ).toInt();
    var slideTo       = this.slideTo + ( el.id.test( 'right' ) ? 1 : -1 );

    if( slideTo >= 4 && slideTo <= itemsLength )
    {
      var leftMargin = ( slideTo - 4 ) * -140;
      leftMargin = ( leftMargin >= 0 ? 13 : leftMargin );

      this.slideTo = slideTo;

      $( 'theSlideDiv' ).setStyle( 'left', ( leftMargin + 'px' ) );
    }
  },

  /*
   * create an div as popup
   */
  popup: function()
  {
    if( !$( 'popup' ) )
    {
      // calculate start position of the popup
      t = window.getScrollTop() + 100;
      l = ( ( window.getWidth() - 100 ) / 2 ).toInt() ;

      var div = new Element( 'div' );
      div.setProperty( 'id', 'popup' );
      div.setOpacity( 0 );
      div.setStyles( {
        'top': t,
        'left': l
      } );

      var divContent = new Element( 'div' );
      divContent.setProperty( 'id', 'popupContent' );
      divContent.set( 'html', '&nbsp;' );

      var x = new Element( 'div' );
      x.setProperty( 'class', 'popupTop' );
      x.set( 'html', 'sluiten <img src="/gfx/filter_close.gif" alt="" style="vertical-align: middle;" />' );
      x.addEvent( 'click', function( ){ this.popupClose( ) }.bind( this ) );

      x.inject( div, 'bottom' );
      divContent.inject( div, 'bottom' );
      div.injectInside( document.body );
    }
    else
    {
      $( 'popupContent' ).set( 'html', '&nbsp;' );
    }
/*  commented by wytze
    if ( this.myFX.get( 'popup' ) ) {// prevent double animations on 1 element
      this.myFX.get( 'popup' ).stop();
    }
*/
    this.myFX.set( 'popup', new Fx.Tween( 'popup', { property: 'opacity', duration:500 } ).start( 0, 1 ) );

  // added by wytze
    if ( !$('tintScreen') ) {
      var tint = new Element('div', {id: 'tintScreen'});
      tint.addEvent('click', function() {
        this.popupClose();
      }.bind(this));
      tint.setStyle('opacity', 0);
      tint.inject(document.body);
    } else {
      var tint = $('tintScreen')
    }
    tint.fade(0.8);
  },

  popupClose: function( )
  {
    if( $( 'popup' ) )
    {
      if( this.myFX.get( 'popup' ) ) // prevent double animations on 1 element
        this.myFX.get( 'popup' ).cancel();

      this.myFX.set( 'popup', new Fx.Tween( 'popup', { property: 'opacity', duration:500, onComplete: function() {
        $( 'popup' ).destroy( );
      } } ).start( 1, 0 ) );

    // added by wytze
      if ($('tintScreen')) {
        $('tintScreen').fade('out');
      }
    }
  },

  viewImage: function( url )
  {
    this.popup();

    // load image
    var img = new Asset.image(  url,
                                {
                                  id: 'myImage',
                                  title:'',
                                  onload: function(){
                                    this.injectViewImage( img );
                                  }.bind(this)
                                }
                              );

    // set image as popup content
    return false;
  },

  injectViewImage: function( img )
  {
    img.setOpacity( 0 );
    img.injectInside( 'popupContent' );

    c = img.getCoordinates();
    w = c.width;
    h = c.height;

    l = ( ( window.getWidth() - w ) / 2 ).toInt();
    t = ( ( window.getHeight() - h ) / 2 ).toInt();

    sTop = 0;
    if ( window.pageYOffset )
      sTop = window.pageYOffset;
    else if ( document.documentElement.scrollTop )
      sTop = document.documentElement.scrollTop;
    else if ( document.body.scrollTop )
      sTop = document.body.scrollTop;

    if( t <= 0 )
      t = 20;
    else if( t >= 150 )
      t = 150;

    t += sTop;

    var myEffects = new Fx.Morph('popup', {duration: 800}).start( {
      'left': l,
      'top': t
    } );

    var myEffects = new Fx.Morph('popupContent', {duration: 800});
    myEffects.start( {
      'width' : w,
      'height' : h
    } ).chain(function() {
      new Fx.Tween( $( img ), { property: 'opacity', duration:250 } ).start( 1 );
    } );

  },

  /*
   * Highlights an element to highlight color and back to it's original color
   */
  highlightElement: function( el )
  {

    // This function is broken in IE7 / IE8
    return true;

    /*

    if( !( el = $( el ) ) )
      return false; // element can't be found

    if( el.getProperty( 'id' ) == '' || el.getProperty( 'id' ) == null )
      el.setProperty( 'id', 'myEl_'+(++this.myElements) );

    defaultBG = el.getStyle( 'background-color' );

    // solve the problem with transparent bg -> can't be highlighted
    realDefault = '';
    if( defaultBG == 'transparent' )
    {
      realDefaultBG = defaultBG;
      defaultBG     = '#ffffff';
      el.setStyle( 'background-color', defaultBG );
    }

    if( this.myFX.get( el.id ) ) // prevent double animations on 1 element
      this.myFX.get( el.id ).stop();

    this.myFX.set( el.id, new Fx.Tween( el.id, { property: 'background-color', duration:400, onComplete: function( el ) {
      new Fx.Tween( el.id, { property: 'background-color', duration:400 } ).start( defaultBG ).chain(
        function(realDefaultBG){
          if(realDefaultBG != '' )
            el.setStyle( 'background-color', realDefaultBG );
        }
      );
    }.bind(this) } ).start( 'a0c5eb' ) );

    return true
    */

  },

  // displays an message block with given title and message
  // both vars can contain html
  showMessage: function( title, message )
  {
    if( $( 'message' ) )
    {
      if( this.myFX.get( 'message' ) )
        this.myFX.get( 'message' ).cancel();
      $( 'message' ).destroy( );
    }

    var msg = new Element( 'div' );
    msg.setProperty( 'id', 'message' );
    msg.inject( document.body );

    msg.setOpacity( 0 );
    msg.setStyle( 'top', window.getScrollTop() + 200 );

    var x = new Element( 'div' );
    x.addClass( 'popupTop' );

    var h = new Element( 'strong' );
    h.set('html', title);
    h.inject( x, 'bottom'  );

    x.onclick = function( ){ this.clearMessage( ); }.bind(this);

    var c = new Element( 'p' );
    c.set('html', message );

    x.inject( msg, 'bottom' );

    c.inject( msg );
    msg.inject( document.body, 'bottom' );

    var left = (window.getSize().x / 2) - (msg.getSize().x / 2);
    msg.setStyle( 'left', left );


    this.myFX.set( 'message', new Fx.Tween( msg, { property: 'opacity', duration:500 } ).start( 0, 1 ) );

    $clear( this.myFX.get( 'messageDelay' ) );

    this.myFX.set( 'messageDelay' , ( function(){ this.clearMessage(); }.bind(this) ).delay( 3500 ) );

    return false;
  },

  // removes the message block
  clearMessage: function( )
  {
    if( !$('message') )
      return;

    if( this.myFX.get( 'message' ) )
      this.myFX.get( 'message' ).cancel();

    this.myFX.set( 'message', new Fx.Tween( 'message', { property: 'opacity', duration:500, onComplete: function(){ $( 'message' ).destroy( ); } } ).start( 1, 0 ) );

    msg  = null;
    h    = null;
    c    = null;
    x    = null;

    return true
  }

});

function initSite () {

  var specsInfo = new Tips('.specsInfo', {
    className: 'specsInfo',
    onShow: function(tip) {
      this.effect = new Fx.Tween(tip, { property: 'opacity' ,duration: 500, wait: false}).start(0,1);
    },
    onHide: function(tip) {
      this.effect = new Fx.Tween(tip, { property: 'opacity' ,duration: 500, wait: false}).start(1,0);
    }
  });

  /* flash banners replaced by static images
   * 
   Due to inconsistency in handling flash among browsers.. we need to do it with javascript to remain valid
  if ( hasChat == true ) {

      var so = new SWFObject ( 'layout/default/flash/chat.swf', 'chatBanner', '150', '55', 8 );
      so.addParam ( 'wmode', 'transparent' );
      so.write ( 'chat' );

  }

  if ( hasPhone == true ) {

      domain = window.location.hostname
      domainArray = domain.split('.')
      domainArray.reverse()


      if ( domainArray[0] == 'be') {
          var so = new SWFObject ( 'layout/default_be/gfx/bel_be.swf', 'phoneBanner', '165', '55', 8 );
          so.addParam ( 'wmode', 'transparent' );
          so.write ( 'call' );
      } else {
          var so = new SWFObject ( 'layout/default/flash/bel.swf', 'phoneBanner', '165', '55', 8 );
          so.addParam ( 'wmode', 'transparent' );
          so.write ( 'call' );
      }

  }
  */

  if ( $ ( 'bannerFlip' ) )  {


    domain = window.location.hostname
    domainArray = domain.split('.')
    domainArray.reverse()

    if ( domainArray[0] == 'be') {
        var so = new SWFObject ( 'layout/default_be/gfx/bannerflip_be.swf', 'top-banner3', '180', '219', 8 );
        so.addParam ( 'wmode', 'transparent' );
        so.write ( 'bannerFlip' );
    } else {
        var so = new SWFObject ( 'layout/default/gfx/bannerflip.swf', 'top-banner3', '180', '219', 8 );
        so.addParam ( 'wmode', 'transparent' );
        so.write ( 'bannerFlip' );
    }



  }

  Site = new mySite( );
};

