/*!
 * initializer frontend
 * Version 1.0
 * Author MFE
 * Copyright (c) 2008 Denbel, www.denbel.nl
 */

var skinName = 'default';

YAHOO.util.Event.onDOMReady( function( e )
{
  _global.initMenu();
  _global.initSearch();
  _global.initCreateForm();
  _global.initEditForm();
  _global.initAddressForm();
  _global.initProductImage();
  _global.initActiveContent();
  _global.initAccount();
  _global.initProduct();
  _global.initEnlargers();
  _global.initStarBoxes();
  _global.initBuyButtons();
  _global.initSubscribeButtons();
  _global.initCheckout();
  _global.initCarousels();
  
  Denbel.Website.init();
  Denbel.ShoppingCart.init( {container:'shopping-cart-container', box:'shopping-cart'} );
  
  if( YAHOO.util.Dom.inDocument( 'submit-fProfile' ) )
  {
    YAHOO.util.Event.addListener( 'submit-fProfile', 'click', function( e )
    {
      YAHOO.util.Event.stopEvent( e );
      YAHOO.util.Dom.get( 'fProfile' ).submit();
    } );
  }

  _global.initShoppingCart();
} );
  
_global =
{
  /**
   * StarBox array
   * @var Array
   */
  starBoxes: [],
  
  /**
   * initializes all carousels
   * @return void
   */
  initCarousels: function()
  {
    var cars = YAHOO.util.Dom.getElementsByClassName( 'carousel' );
    var car = null;
    
    // we don't want focus to be set to the carousel in any way
    YAHOO.widget.Carousel.prototype.focus = function(){ return; };
    
    for( var i = 0; i < cars.length; i++ )
    {
      car = new YAHOO.widget.Carousel( cars[i],
      {
        autoPlay: 7500,
        isCircular: true,
        numVisible: 1,
        isVertical: false,
        animation:
        {
          speed: 2,
          effect: YAHOO.util.Easing.easeOut
        },
        revealAmount: 0,
        scrollIncrement: 0,
        selectedItem: null,
        selectOnScroll: false,
        navigation:
        {
          prev: null,
          next: null
        }
      } );
      
      car.render();
      car.show();
      
      car.startAutoPlay();
    }
  },
  
  /**
   * Handles the unload of the checkout process
   * @return String
   */
  _preventCheckoutCancel: function()
  {
    if( _global._preventCheckoutCancelDisabled == true )
    {
      return;
    }
    
    if( _global._preventCheckoutCancelHandled == true )
    {
      return;
    }
    
    _global._preventCheckoutCancelHandled = true;
    
    alert( 'WARNING: do not leave the page this way.' + "\n" + 'To cancel the checkout process, press the CANCEL button on the page.' );
    return 'WARNING: do not leave the page this way.' + "\n" + 'To cancel the checkout process, press the CANCEL button on the page.';
  },
  
  /**
   * initializes checkout pages
   * @return void
   */
  initCheckout: function()
  {
    var preventCancel = function( enable )
    {
      var body = null;
      
      if( document.body )
      {
        body = document.body;
      }
      else
      {
        body = document.getElementsByTagName( 'body' )[0];
      }
      
      if( enable == undefined || enable == null || enable === true )
      {
        _global._preventCheckoutCancelDisabled = false;
        body.setAttribute( 'onbeforeunload', 'return _global._preventCheckoutCancel();' );
        body.setAttribute( 'onunload', 'return _global._preventCheckoutCancel();' );
      }
      else
      {
        _global._preventCheckoutCancelDisabled = true;
        body.removeAttribute( 'onbeforeunload' );
        body.removeAttribute( 'onunload' );
      }
    };
    
    if( YAHOO.util.Dom.inDocument( 'fCheckout' ) )
    {
      preventCancel.call( this, true );
    }
    
    if( YAHOO.util.Dom.inDocument( 'iCheckoutMethod' ) )
    {
      // default box display values
      YAHOO.util.Dom.setStyle( 'payment-options', 'display', 'none' );
      YAHOO.util.Dom.setStyle( 'delivery-options', 'display', 'none' );

      var checkoutOptionClick = function( e )
      {
        //YAHOO.util.Dom.setStyle( 'payment-options', 'display', 'none' );
        //YAHOO.util.Dom.setStyle( 'delivery-options', 'display', 'none' );
        
        if( this.checked )
        {
          if( YAHOO.util.Dom.hasClass( this, 'pay' ) )
          {
            YAHOO.util.Dom.setStyle( 'payment-options', 'display', '' );
          }
          else
          {
            YAHOO.util.Dom.setStyle( 'payment-options', 'display', 'none' );
          }
          
          if( YAHOO.util.Dom.hasClass( this, 'ship' ) )
          {
            YAHOO.util.Dom.setStyle( 'delivery-options', 'display', '' );
          }
          else
          {
            YAHOO.util.Dom.setStyle( 'delivery-options', 'display', 'none' );
          }
        }
      };
      
      var options = YAHOO.util.Dom.getElementsBy( function( n )
      {
        if( n.getAttribute( 'type' ) == 'radio' )
        {
          YAHOO.util.Event.addListener( n, 'click', checkoutOptionClick );
          YAHOO.lang.later( 1, n, checkoutOptionClick, null, false );
          return true;
        }
        
        return false;
      }, 'input', 'iCheckoutMethod' );
      
    }
    
    if( YAHOO.util.Dom.inDocument( 'lCancelCheckout' ) )
    {
      YAHOO.util.Event.addListener( 'lCancelCheckout', 'click', function( e, o )
      {
        if( !confirm( 'Are you sure you wish to cancel the checkout process?' ) )
        {
          YAHOO.util.Event.stopEvent( e );
        }
        else
        {
          o.preventCancel.call( this, false );
        }
      },
      {
        preventCancel: preventCancel
      } );
    }
    
    if( YAHOO.util.Dom.inDocument( 'lDisclaimer' ) )
    {
      YAHOO.util.Event.addListener( 'lDisclaimer', 'click', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        Denbel.Website.showWaitDialog();
        
        var rpc = new Denbel.rpc.XmlRpcClient( '/proxy.php' );
        var msg = rpc.createMessage( 'getPageContents' );
        msg.createAndAddParameter( 'disclaimer' );
        
        rpc.callService( msg,
        {
          success: function( res )
          {
            Denbel.Website.showDialog( 'Disclaimer', '<div style="color:#000;height:500px;width:500px;overflow:auto;">' + res.data[0] + '</div>',
            [{
              text: 'Close',
              handler: function( e )
              {
                this.hide();
              },
              isDefault: true
            }], true );
          },
          failure: function( res )
          {
            Denbel.Website.hideWaitDialog();
          },
          argument: null
        } );
      } );
    }
  
    YAHOO.util.Event.addListener( 'fCheckout', 'submit', function( e, o )
    {
      var checkRadios = new Array();
      var names = new Array();
      var tmp = null;
      
      if( YAHOO.util.Dom.inDocument( 'iCheckoutMethod' ) )
      {
        checkRadios.push( {name:'iCheckoutId',checked:false,msg:'Please select an option.'} );
        names.push( 'iCheckoutId' );
      }

      if( YAHOO.util.Dom.getRegion( 'iPaymentOption' ) && YAHOO.util.Dom.getRegion( 'iPaymentOption' ).top > 0 )
      {
        checkRadios.push( {name:'iPaymentId' ,checked:false,msg:'Please select a payment method.'} );
        names.push( 'iPaymentId' );
      }
      
      if( YAHOO.util.Dom.getRegion( 'delivery-options' ) && YAHOO.util.Dom.getRegion( 'delivery-options' ).top > 0 )
      {
        checkRadios.push( {name:'iAddressId',checked:false,msg:'Please select a delivery address.'} );
        names.push( 'iAddressId' );
        
        if( YAHOO.util.Dom.getRegion( 'iDeliveryId' ) && YAHOO.util.Dom.getRegion( 'iDeliveryId' ).top > 0 )
        {
          checkRadios.push( {name:'iDeliveryId',checked:false,msg:'Please select a delivery method.'} );
          names.push( 'iDeliveryId' );
        }
      }

      var getValueByName = function( name, array )
      {
        for( var i = 0; i < array.length; i++ )
        {
          if( array[i].name == name )
          {
            return array[i];
          }
        }
      };

      var i = 0;
      var obj = null;

      for( i = 0; i < this.elements.length; i++ )
      {
        tmp = this.elements[i];
        
        if( !Denbel.util.inArray( tmp.getAttribute( 'name' ), names ) )
        {
          continue;
        }
        
        if( tmp.checked )
        {
          obj = getValueByName( tmp.getAttribute( 'name' ), checkRadios );
          obj.checked = true;
        }
      }
      
      for( i = 0; i < checkRadios.length; i++ )
      {
        if( !checkRadios[i].checked )
        {
          YAHOO.util.Event.stopEvent( e );
          alert( checkRadios[i].msg );
          return false;
        }
      }
      
      if( YAHOO.util.Dom.inDocument( 'iConfirm' ) && !YAHOO.util.Dom.get( 'iConfirm' ).checked )
      {
        YAHOO.util.Event.stopEvent( e );
        alert( 'Please check the box to confirm that the information on this page is correct.' );
        return false;
      }
      else if( YAHOO.util.Dom.inDocument( 'iConfirm' ) && YAHOO.util.Dom.get( 'iConfirm' ).checked )
      {
        Denbel.Website.showWaitDialog();
      }
      
      if( YAHOO.util.Dom.inDocument( 'iBanker' ) )
      {
        if( YAHOO.util.Dom.get( 'iBanker' ).value == '' || YAHOO.util.Dom.get( 'iBanker' ).value == null )
        {
          YAHOO.util.Event.stopEvent( e );
          alert( 'Please select your banker.' );
          return false;
        }
        else
        {
          Denbel.Website.showWaitDialog();
        }
      }
      
      o.preventCancel.call( this, false );
    },
    {
      preventCancel: preventCancel
    } );
  },
  
  /**
   * initializes all subscribe buttons
   * @return void
   */
  initSubscribeButtons: function()
  {
    var buttons = YAHOO.util.Dom.getElementsByClassName( 'btn-subscribe' );
    var userIn = YAHOO.util.Dom.get( 'vUserIsIn' ).innerHTML;
    var hasAddress = YAHOO.util.Dom.get( 'vUserHasAddress' ).innerHTML;
    
    userIn = ( ( userIn == 'true' ) ? true : false );
    hasAddress = ( ( hasAddress == 'true' ) ? true : false );
    
    for( var i = 0; i < buttons.length; i++ )
    {
      YAHOO.util.Event.addListener( buttons[i], 'click', function( e, o )
      {
        YAHOO.util.Event.stopEvent( e );

        if( !o.userIn )
        {
          alert( 'You must first log in or create an account to subscribe to a series.' );
          return;
        }
        
        if( !o.hasAddress )
        {
          alert( 'You must complete your account with at least one address specified before you can pre-order or re-order items.' );
          return;
        }
        
        var serieId = this.getAttribute( 'href' ).indexOf( '#' );
        serieId = this.getAttribute( 'href' ).substring( ( serieId + 1 ) );
        
        Denbel.Website.showDialog( 'Subscribe', '<div><p class="black">You can subscribe to this series. If you do, you will automatically receive the newest upcoming issues in your order list. You also get 20% discount on this title.<br />NOTE: Limited variants &amp; retailer incentives are NOT included in a subscription.<br />Regular variants you cannot choose from, they will be randomly divided.<br /><br />Do you wish to subscribe for this series?</p></div>',
        [{
          text: 'Yes, subscribe',
          handler: function( e )
          {
            Denbel.Website.showWaitDialog();
            
            var rpc = new Denbel.rpc.XmlRpcClient( '/proxy.php' );
            var msg = rpc.createMessage( 'subscribe' );
            msg.createAndAddParameter( serieId );
            
            rpc.callService( msg,
            {
              success: function( res )
              {
                res.argument.hide();
                Denbel.Website.hideWaitDialog();
                
                if( res.data[0] == 1 )
                {
                  alert( 'You have successfully subscribed for this item.' + "\n" + 'Go to "my account" to view your subscriptions.' );
                }
                else if( res.data[0] == 2 )
                {
                  alert( 'You are not logged in. Please log in and try again.' );
                }
                else
                {
                  alert( 'There was an error registering your subscription.' );
                }
              },
              failure: function( res )
              {
                Denbel.Website.hideWaitDialog();
                res.argument.hide();
                
                alert( 'There was an error registering your subscription.' );
              },
              argument: this
            } );
          },
          isDefault: true
        },
        {
          text: 'Cancel',
          handler: function( e )
          {
            this.hide();
          }
        }], true, null, 350 );
      },
      {
        hasAddress: hasAddress,
        userIn: userIn
      } );
    }
  },
  
  /**
   * initializes all buy buttons
   * @return void
   */
  initBuyButtons: function()
  {
    var buttons = null;
    var i = 0;
    var userIn = YAHOO.util.Dom.get( 'vUserIsIn' ).innerHTML;
    var hasAddress = YAHOO.util.Dom.get( 'vUserHasAddress' ).innerHTML;
    
    userIn = ( ( userIn == 'true' ) ? true : false );
    hasAddress = ( ( hasAddress == 'true' ) ? true : false );
    
    buttons = YAHOO.util.Dom.getElementsByClassName( 'btn-buy' );
    
    for( i = 0; i < buttons.length; i++ )
    {
      YAHOO.util.Event.addListener( buttons[i], 'click', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        var productId = this.getAttribute( 'href' ).indexOf( '#' );
        productId = this.getAttribute( 'href' ).substring( ( productId + 1 ) );
        
        Denbel.ShoppingCart.addItem( productId );
      } );
    }
    
    buttons = YAHOO.util.Dom.getElementsByClassName( 'btn-re' );
    
    for( i = 0; i < buttons.length; i++ )
    {
      YAHOO.util.Event.addListener( buttons[i], 'click', function( e, o )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( !o.userIn )
        {
          alert( 'You must first log in or create an account before you can pre-order or re-order an item.' );
          return;
        }
        
        if( !o.hasAddress )
        {
          alert( 'You must complete your account with at least one address specified before you can pre-order or re-order items.' );
          return;
        }
        
        var productId = this.getAttribute( 'href' ).indexOf( '#' );
        productId = this.getAttribute( 'href' ).substring( ( productId + 1 ) );
        
        Denbel.Website.showDialog( 'Re-order', '<div><p class="black">You can re-order this item today for arrival at our store in 14 - 30 days. If you do, this item will added to your re-order list and you will automatically receive a notification when this item arrives.<br /><br />Do you wish to re-order this item?</p></div>',
        [{
          text: 'Yes, re-order',
          handler: function( e )
          {
            Denbel.Website.showWaitDialog();
            
            var rpc = new Denbel.rpc.XmlRpcClient( '/proxy.php' );
            var msg = rpc.createMessage( 'addProductToWishlist' );
            msg.createAndAddParameter( productId );
            
            rpc.callService( msg,
            {
              success: function( res )
              {
                res.argument.hide();
                Denbel.Website.hideWaitDialog();
                
                if( res.data[0] == 1 )
                {
                  alert( 'You have successfully re-ordered this item.' + "\n" + 'Go to "my account" to view your re-orders.' );
                }
                else if( res.data[0] == 2 )
                {
                  alert( 'You are not logged in. Please log in and try again.' );
                }
                else if( res.data[0] == 3 )
                {
                  alert( 'You have already re-ordered this item.' );
                }
                else
                {
                  alert( 'There was an error re-ordering this item.' );
                }
              },
              failure: function( res )
              {
                Denbel.Website.hideWaitDialog();
                res.argument.hide();
                
                alert( 'There was an error re-ordering this item.' );
              },
              argument: this
            } );
          },
          isDefault: true
        },
        {
          text: 'Cancel',
          handler: function( e )
          {
            this.hide();
          }
        }], true, null, 350 );
      },
      {
        hasAddress: hasAddress,
        userIn: userIn
      } );
    }
    
    buttons = YAHOO.util.Dom.getElementsByClassName( 'btn-pre' );
    
    for( i = 0; i < buttons.length; i++ )
    {
      YAHOO.util.Event.addListener( buttons[i], 'click', function( e, o )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( !o.userIn )
        {
          alert( 'You must first log in or create an account before you can pre-order or re-order an item.' );
          return;
        }
        
        if( !o.hasAddress )
        {
          alert( 'You must complete your account with at least one address specified before you can pre-order or re-order items.' );
          return;
        }
        
        var productId = this.getAttribute( 'href' ).indexOf( '#' );
        productId = this.getAttribute( 'href' ).substring( ( productId + 1 ) );
        
        Denbel.Website.showDialog( 'Pre-order', '<div><p class="black">You can pre-order this item. If you do, this item will added to your pre-order list and you will automatically receive a notification when this item arrives.<br /><br />Do you wish to pre-order this item?</p></div>',
        [{
          text: 'Yes, pre-order',
          handler: function( e )
          {
            Denbel.Website.showWaitDialog();
            
            var rpc = new Denbel.rpc.XmlRpcClient( '/proxy.php' );
            var msg = rpc.createMessage( 'addProductToWishlist' );
            msg.createAndAddParameter( productId );
            
            rpc.callService( msg,
            {
              success: function( res )
              {
                res.argument.hide();
                Denbel.Website.hideWaitDialog();
                
                if( res.data[0] == 1 )
                {
                  alert( 'You have successfully pre-ordered this item.' + "\n" + 'Go to "my account" to view your pre-orders.' );
                }
                else if( res.data[0] == 2 )
                {
                  alert( 'You are not logged in. Please log in and try again.' );
                }
                else if( res.data[0] == 3 )
                {
                  alert( 'You have already pre-ordered this item.' );
                }
                else
                {
                  alert( 'There was an error pre-ordering this item.' );
                }
              },
              failure: function( res )
              {
                Denbel.Website.hideWaitDialog();
                res.argument.hide();
                
                alert( 'There was an error pre-ordering this item.' );
              },
              argument: this
            } );
          },
          isDefault: true
        },
        {
          text: 'Cancel',
          handler: function( e )
          {
            this.hide();
          }
        }], true, null, 350 );
      },
      {
        hasAddress: hasAddress,
        userIn: userIn
      } );
    }
  },
  
  /**
   * initializes star boxes
   * @return void
   */
  initStarBoxes: function()
  {
    _global.starBoxes = [];
    
    var boxes = YAHOO.util.Dom.getElementsByClassName( 'starbox' );
    var obj = null;
    var rnd = null;
    var id = null;
    var x = null;
    
    for( var i = 0; i < boxes.length; i++ )
    {
      x = boxes[i].getAttribute( 'id' ).split( '_' );
      id = x[1];
      
      if( x.length > 2 )
      {
        rate = x[2];
      }
      
      rnd = Denbel.util.Rand( 0, 10 ) / 2;
      
      obj = new Denbel.ui.StarBox( boxes[i],
      {
        size: 5,
        texts:
        [
          'poor',
          'nice',
          'average',
          'good',
          'excellent'
        ],
        initialValue: YAHOO.util.Dom.get( boxes[i] ).getAttribute( 'title' ),
        allowHalf: true,
        locked: ( YAHOO.util.Dom.hasClass( boxes[i], 'locked' ) ),
        postMessage: 'rateProduct',
        postParameters:
        [
          id
        ],
        callback:
        {
          success: function( res )
          {
            YAHOO.util.Dom.setStyle( 'product-rating', 'display', 'none' );
            _global.starBoxes[0].setValue( res.data[0] );
          },
          failure: function( res )
          {
            YAHOO.util.Dom.setStyle( 'product-rating', 'display', 'none' );
          },
          argument: null
        }
      } );
      
      obj.render();
      
      _global.starBoxes.push( obj );
    }
  },
  
  /**
   * initializes enlargers
   * @return void
   */
  initEnlargers: function()
  {
    var enlargers = YAHOO.util.Dom.getElementsByClassName( 'enlarger' );
    var pb = null;
    var id = null;
    
    for( var i = 0; i < enlargers.length; i++ )
    {
      if( !YAHOO.util.Dom.inDocument( enlargers[i] ) )
      {
        continue;
      }
      
      id = enlargers[i].getAttribute( 'id' ).split( '-' )[1];
      pb = new Denbel.ui.Photobox( YAHOO.util.Dom.get( 'photobox-' + id ) );
      
      YAHOO.util.Event.addListener( Denbel.util.XmlHelper.getNextChildElementByTagName( enlargers[i], 'A' ), 'click', function( e, o )
      {
        YAHOO.util.Event.stopEvent( e );
        o.show();
      }, pb );
    }
  },
  
  /**
   * initializes product page
   * @return void
   */
  initProduct: function()
  {
    if( YAHOO.util.Dom.inDocument( 'product-tabs' ) )
    {
      var tab = null;
    
      try
      {
        tab = new YAHOO.widget.TabView( 'product-tabs' );
      }
      catch( ex )
      {
      }
    }
    
    if( YAHOO.util.Dom.inDocument( 'product-reviews' ) )
    {
      var loaderContent = '<div class="vspacer"></div><div style="text-align:center;"><img alt="Loading" title="" src="/media/img/loader.gif" /><br /><span>Loading comments...</span><div class="vspacer"></div><div class="line"></div></div>';
      
      var reloadComments = function( loaderContent, fn, page, noReload )
      {
        var initPageLinks = function( res )
        {
          var i = 0;
          var links = YAHOO.util.Dom.getElementsByClassName( 'edit-comment-link', 'a' );
          
          for( i = 0; i < links.length; i++ )
          {
            YAHOO.util.Event.addListener( links[i], 'click', function( e )
            {
              YAHOO.util.Event.stopEvent( e );
              
              var id = this.getAttribute( 'href' );
              id = id.substring( id.indexOf( '#' ) + 1 );
              
              YAHOO.util.Dom.get( 'iCommentId' ).value = id;
              YAHOO.util.Dom.get( 'iComment' ).value = YAHOO.util.Dom.get( 'review-text-' + id ).innerHTML;
            } );
          }
          
          links = YAHOO.util.Dom.getElementsByClassName( 'delete-comment-link', 'a' );
          
          for( i = 0; i < links.length; i++ )
          {
            YAHOO.util.Event.addListener( links[i], 'click', function( e, o )
            {
              YAHOO.util.Event.stopEvent( e );
              
              if( confirm( 'Do you really wish to delete your comment?' ) )
              {
                res.argument.target.innerHTML = o.loaderContent;
                
                var id = this.getAttribute( 'href' );
                id = id.substring( id.indexOf( '#' ) + 1 );
                
                var rpc = new Denbel.rpc.XmlRpcClient();
                var msg = rpc.createMessage( 'deleteComment' );
                msg.createAndAddParameter( id );
                
                rpc.callService( msg,
                {
                  success: function( res )
                  {
                    res.argument.fn.call( this, res.argument.loaderContent, res.argument.fn );
                  },
                  failure: function( res )
                  {
                    res.argument.fn.call( this, res.argument.loaderContent, res.argument.fn );
                  },
                  argument:
                  {
                    fn: o.fn,
                    loaderContent: loaderContent
                  }
                } );
              }
            },
            {
              fn: fn,
              target: res.argument.target,
              loaderContent: loaderContent
            } );
          }
          
          links = YAHOO.util.Dom.getElementsByClassName( 'pagelink', 'a', 'reviews-container' );
          
          for( i = 0; i < links.length; i++ )
          {
            YAHOO.util.Event.addListener( links[i], 'click', function( e, o )
            {
              YAHOO.util.Event.stopEvent( e );
              o.fn.call( this, o.loaderContent, o.fn, this.getAttribute( 'title' ) );
            },
            {
              fn: reloadComments,
              loaderContent: loaderContent
            } );
          }
        };
        
        if( !noReload )
        {
          var rpc = new Denbel.rpc.XmlRpcClient();
          var msg = rpc.createMessage( 'getProductComments' );
          msg.createAndAddParameter( YAHOO.util.Dom.get( 'vProductId' ).getAttribute( 'title' ) );
          msg.createAndAddParameter( page );
          
          var target = YAHOO.util.Dom.get( 'reviews-container' );
          
          if( !target )
          {
            return;
          }
          
          target.innerHTML = loaderContent;
          
          rpc.callService( msg,
          {
            success: function( res )
            {
              if( res.data[0] )
              {
                res.argument.target.innerHTML = res.data[0];
                res.argument.initFn.call( this, res );
              }
              else
              {
                res.argument.target.innerHTML = '<span class="red big"><img class="top" alt="Error" title="" src="/media/img/error.gif" />&nbsp;&nbsp;An error occured while loading the comments for this product.</span><div class="vspacer"></div><div class="line"></div>';
              }
            },
            failure: function( res )
            {
              res.argument.target.innerHTML = '<span class="red big"><img class="top" alt="Error" title="" src="/media/img/error.gif" />&nbsp;&nbsp;An error occured while loading the comments for this product.</span><div class="vspacer"></div><div class="line"></div>';
            },
            argument:
            {
              target: target,
              initFn: initPageLinks
            }
          } );
        }
        else
        {
          initPageLinks.call( this,
          {
            argument:
            {
              target: YAHOO.util.Dom.get( 'reviews-container' )
            }
          } );
        }
      };
      
      reloadComments.call( this, loaderContent, reloadComments, 1, true );
      
      if( YAHOO.util.Dom.inDocument( 'fReview' ) )
      {
        YAHOO.util.Event.addListener( 'bCancelReview', 'click', function( e )
        {
          YAHOO.util.Event.stopEvent( e );
          YAHOO.util.Dom.get( 'iCommentId' ).value = '';
          YAHOO.util.Dom.get( 'fReview' ).reset();
        } );
        
        var fv = new Denbel.util.FormValidator( 'fReview', {blur:true} );
        
        if( YAHOO.util.Dom.inDocument( 'iNickName' ) )
        {
          fv.addValidation( 'iNickName', Denbel.util.FormValidator.TYPE_REQUIRED, 'You must provide a nick name' );
          
          fv.addValidation( 'iNickName', Denbel.util.FormValidator.TYPE_RPC, 'This nick name is already used',
          {
            method: 'isNickFree',
            params: YAHOO.util.Dom.get( 'iClientId' ).value
          } );
        }
        
        YAHOO.util.Event.addListener( 'fReview', 'submit', function( e, o )
        {
          YAHOO.util.Event.stopEvent( e );
          
          if( YAHOO.util.Dom.get( 'iComment' ).value == '' )
          {
            alert( 'Write a comment before posting.' );
            return false;
          }
          
          o.fv.validate(
          {
            success: function( res )
            {
              YAHOO.util.Dom.get( 'reviews-container' ).innerHTML = loaderContent;
              
              var rpc = new Denbel.rpc.XmlRpcClient();
              var msg = rpc.createMessage( 'postComment' );
              msg.createAndAddParameter( YAHOO.util.Dom.get( 'iItemId' ).value );
              msg.createAndAddParameter( YAHOO.util.Dom.get( 'iComment' ).value );
              
              if( YAHOO.util.Dom.inDocument( 'iNickName' ) )
              {
                msg.createAndAddParameter( YAHOO.util.Dom.get( 'iNickName' ).value );
              }
              else
              {
                msg.createAndAddParameter( null );
              }
              
              msg.createAndAddParameter( YAHOO.util.Dom.get( 'iCommentId' ).value );
              
              YAHOO.util.Dom.get( 'iCommentId' ).value = '';
              YAHOO.util.Dom.get( 'iComment' ).value = '';
              
              rpc.callService( msg,
              {
                success: function( res )
                {
                  YAHOO.util.Dom.setStyle( 'nickname-box', 'display', 'none' );
                  res.argument.fn.call( this, res.argument.loaderContent, res.argument.fn );
                },
                failure: function( res )
                {
                  alert( 'Something went wrong posting your comment. Please try again later.' );
                },
                argument:
                {
                  fn: reloadComments,
                  loaderContent: loaderContent
                }
              } );
            },
            failure: function( res )
            {
              alert( res.fault.get( 'faultString' ) );
            },
            argument:
            {
              frm: this
            }
          } );
        },
        {
          fv: fv
        } );
      }
    }
  },
  
  /**
   * initializes account pages
   * @return void
   */
  initAccount: function()
  {
    if( !YAHOO.util.Dom.inDocument( 'myaccount-tabs' ) )
    {
      return;
    }
    
    var tab = null;
    
    try
    {
      tab = new YAHOO.widget.TabView( 'myaccount-tabs' );
    }
    catch( ex )
    {
    }
    
    var i = 0;
    var removeLinks = YAHOO.util.Dom.getElementsByClassName( 'remove-address' );
    
    for( i = 0; i < removeLinks.length; i++ )
    {
      YAHOO.util.Event.addListener( removeLinks[i], 'click', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( confirm( 'Are you sure you wish to remove this address?' ) )
        {
          window.location = this.getAttribute( 'href' );
        }
      } );
    }
    
    var unsubscribeLinks = YAHOO.util.Dom.getElementsByClassName( 'remove-subscription' );
    
    for( i = 0; i < unsubscribeLinks.length; i++ )
    {
      YAHOO.util.Event.addListener( unsubscribeLinks[i], 'click', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( confirm( 'Are you sure you wish to unsubscribe?' ) )
        {
          window.location = this.getAttribute( 'href' );
        }
      } );
    }
  },
  
  /**
   * initializes address form
   * @return void
   */
  initAddressForm: function()
  {
    if( !YAHOO.util.Dom.inDocument( 'fAddress' ) )
    {
      return;
    }
    
    var fv = new Denbel.util.FormValidator( 'fAddress', {blur:true} );
    fv.addValidation( 'iName', 'required', 'Enter a name to identify this address' );
    
    YAHOO.util.Event.addListener( 'fAddress', 'submit', function( e, o )
    {
      YAHOO.util.Event.stopEvent( e );
      
      try
      {
        o.validate(
        {
          success: function( o )
          {
            o.argument.submit();
          },
          failure: function( o )
          {
          },
          argument: this
        } );
      }
      catch( ex )
      {
      }
    }, fv );
  },
  
  /**
   * initializes edit account form
   * @return void
   */
  initEditForm: function()
  {
    if( !YAHOO.util.Dom.inDocument( 'fAccount' ) )
    {
      return;
    }
    
    var fv = new Denbel.util.FormValidator( 'fAccount', {blur:true} );
    
    if( YAHOO.util.Dom.inDocument( 'iEmail' ) )
    {
      fv.addValidation( 'iEmail', Denbel.util.FormValidator.TYPE_EMAIL, 'Please enter a valid e-mail address' );
      fv.addValidation( 'iEmail', Denbel.util.FormValidator.TYPE_RPC, 'This e-mail address is already registered', { method: 'isEmailFree', params: YAHOO.util.Dom.get( 'iEmail' ).getAttribute( 'value' ) } );
    }
    
    if( YAHOO.util.Dom.inDocument( 'iNickName' ) )
    {
      fv.addValidation( 'iNickName', Denbel.util.FormValidator.TYPE_RPC, 'This nick name is already in use',
      {
        method: 'isNickFree',
        params: YAHOO.util.Dom.get( 'iItemId' ).value
      } );
    }
    
    if( YAHOO.util.Dom.inDocument( 'iPassword' ) )
    {
      fv.addValidation( 'iPassword', Denbel.util.FormValidator.TYPE_MINLEN, 'Minimum length is 8 characters', 8 );
      fv.addValidation( 'iPassword', Denbel.util.FormValidator.TYPE_CUSTOM, 'Password must consist of numbers and letters', function( v )
      {
        var a = new RegExp( /[a-z]/i );
        var n = new RegExp( /[0-9]/i );
        return ( a.test( v ) && n.test( v ) );
      } );
    }
    
    if( YAHOO.util.Dom.inDocument( 'iPassword2' ) )
    {
      YAHOO.util.Event.addListener( 'iPassword', 'change', function( e, o )
      {
        if( this.value != '' )
        {
          o.addValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_REQUIRED );
        }
        else
        {
          o.removeValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_REQUIRED );
        }
      }, fv );
      
      fv.addValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_MATCH, 'Must be the same value as ' + Denbel.util.FormValidator.getFieldLabel( 'iPassword' ), YAHOO.util.Dom.get( 'iPassword' ) );
    }
    
    YAHOO.util.Event.addListener( 'fAccount', 'submit', function( e, o )
    {
      YAHOO.util.Event.stopEvent( e );

      try
      {
        o.validate(
        {
          success: function( o )
          {
            o.argument.submit();
          },
          failure: function( o )
          {
          },
          argument: this
        } );
      }
      catch( ex )
      {
      }
    }, fv );
  },
  
  /**
   * initializes create account form
   * @return void
   */
  initCreateForm: function()
  {
    if( !YAHOO.util.Dom.inDocument( 'fCreate' ) )
    {
      return;
    }
    
    var fv = new Denbel.util.FormValidator( 'fCreate', {blur: true} );
    
    fv.addValidation( 'iEmail', Denbel.util.FormValidator.TYPE_REQUIRED, 'This field is required' );
    fv.addValidation( 'iEmail', Denbel.util.FormValidator.TYPE_EMAIL, 'Please enter a valid e-mail address' );
    fv.addValidation( 'iEmail', Denbel.util.FormValidator.TYPE_RPC, 'This e-mail address is already registered', { method: 'isEmailFree' } );
    
    fv.addValidation( 'iEmail2', Denbel.util.FormValidator.TYPE_REQUIRED, 'This field is required' );
    fv.addValidation( 'iEmail2', Denbel.util.FormValidator.TYPE_EMAIL, 'Please enter a valid e-mail address' );
    fv.addValidation( 'iEmail2', Denbel.util.FormValidator.TYPE_MATCH, 'Must be the same as ' + Denbel.util.FormValidator.getFieldLabel( 'iEmail' ), YAHOO.util.Dom.get( 'iEmail' ) );
    
    fv.addValidation( 'iPassword', Denbel.util.FormValidator.TYPE_REQUIRED, 'This field is required' );
    fv.addValidation( 'iPassword', Denbel.util.FormValidator.TYPE_MINLEN, 'Minimum length is 8 characters', 8 );
    fv.addValidation( 'iPassword', Denbel.util.FormValidator.TYPE_CUSTOM, 'Password must consist of numbers and letters', function( v )
    {
      var a = new RegExp( /[a-z]/i );
      var n = new RegExp( /[0-9]/i );
      return ( a.test( v ) && n.test( v ) );
    } );
    
    fv.addValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_REQUIRED, 'This field is required' );
    fv.addValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_MINLEN, 'Minimum length is 8 characters', 8 );
    fv.addValidation( 'iPassword2', Denbel.util.FormValidator.TYPE_MATCH, 'Must be the same as ' + Denbel.util.FormValidator.getFieldLabel( 'iPassword' ), YAHOO.util.Dom.get( 'iPassword' ) );
    
    YAHOO.util.Event.addListener( 'fCreate', 'submit', function( e, o )
    {
      YAHOO.util.Event.stopEvent( e );
      
      try
      {
        o.validate(
        {
          success: function( o )
          {
            o.argument.submit();
          },
          failure: function( o )
          {
          },
          argument: this
        } );
      }
      catch( ex )
      {
      }
    }, fv );
  },
  
  /**
   * initializes product image on product page
   * @return void
   */
  initProductImage: function()
  {
    if( !YAHOO.util.Dom.inDocument( 'product-image' ) )
    {
      return;
    }
    
    YAHOO.util.Event.addListener( 'product-image', 'click', function( e )
    {
      YAHOO.util.Event.stopEvent( e );  
    } );
  },
  
  /**
   * initializes active content
   * @return void
   */
  initActiveContent: function()
  {
    try
    {
      if( sIFR )
      {
        sIFR.replace( sIFRfonts.midnight, {
          selector: 'h2',
          transparent: true,
          forceSingleLine: true,
          preventWrap: true,
          css: {
            '.sIFR-root': {
              'color': '#555555',
              'text-transform': 'lowercase',
              'letter-spacing': 1
            }
          }
        } );
        
        sIFR.replace( sIFRfonts.midnight, {
          selector: 'h5',
          transparent: true,
          forceSingleLine: true,
          preventWrap: true,
          css: {
            '.sIFR-root': {
              'color': '#666666',
              'letter-spacing': 1
            }
          }
        } );
      }
    }
    catch( ex )
    {
    }
  },
  
  /**
   * initializes shopping cart
   * @return void
   */
  initShoppingCart: function()
  {
    if( YAHOO.util.Dom.inDocument( 'lEmptyCart' ) )
    {
      YAHOO.util.Event.addListener( 'lEmptyCart', 'click', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( confirm( 'Do you wish to empty your cart?' ) )
        {
          Denbel.ShoppingCart.empty();
        }
      } );
    }
  },
  
  /**
   * initializes the menu
   * @return void
   */
  initMenu: function()
  {
    var menu = null;
    var items = null;
    var i = 0;
    
    try
    {
      menu = new YAHOO.widget.MenuBar( 'menu-bar' );
      YAHOO.widget.MenuBarItem.prototype.active = false;
    }
    catch( e )
    {
      menu = null;
    }
    
    if( menu )
    {
      items = menu.getItems();
      
      for( i = 0; i < items.length; i++ )
      {
        items[i].subscribe( 'mouseover', function( e )
        {
          YAHOO.util.Event.stopEvent( e );

          var img = YAHOO.util.Dom.getChildren( YAHOO.util.Dom.getChildren( this.element )[0] )[0];
          
          if( img )
          {
            var src = img.getAttribute( 'src' );
            src = src.split( '/' );
            src = src[src.length - 1];
            
            if( src.indexOf( '_active' ) == -1 )
            {
              src = src.split( '.' )[0];
              img.setAttribute( 'src', '/media/img/menu/' + src + '_active.gif' );
              
              if( this.parent.getItem( 0 ) == this )
              {
                YAHOO.util.Dom.get( 'menu-bar-start' ).setAttribute( 'src', '/media/img/menu/menubg_start_selected.gif' );
              }
              else if( this.parent.getItem( this.parent.getItems().length - 1 ) == this )
              {
                YAHOO.util.Dom.get( 'menu-bar-end' ).setAttribute( 'src', '/media/img/menu/menubg_end_selected.gif' );
              }
            }
            else
            {
              this.active = true;
            }
          }
        } );
        
        items[i].subscribe( 'mouseout', function( e )
        {
          YAHOO.util.Event.stopEvent( e );
          
          var img = YAHOO.util.Dom.getChildren( YAHOO.util.Dom.getChildren( this.element )[0] )[0];
          
          if( img )
          {
            var src = img.getAttribute( 'src' );
            src = src.split( '/' );
            src = src[src.length - 1];
            
            if( !this.active && src.indexOf( '_active' ) > -1 )
            {
              src = src.split( '.' )[0];
              src = src.split( '_' );
              src = src[0] + '_' + src[1];
              
              img.setAttribute( 'src', '/media/img/menu/' + src + '.gif' );
              
              if( this.parent.getItem( 0 ) == this )
              {
                YAHOO.util.Dom.get( 'menu-bar-start' ).setAttribute( 'src', '/media/img/menu/menubg_start.gif' );
              }
              else if( this.parent.getItem( this.parent.getItems().length - 1 ) == this )
              {
                YAHOO.util.Dom.get( 'menu-bar-end' ).setAttribute( 'src', '/media/img/menu/menubg_end.gif' );
              }
            }
          }
        } );
      }
    
      items = null;
    }
    menu.show();
    
    if( !YAHOO.util.Dom.inDocument( 'sub-menu' ) )
    {
      return;
    }
    
    menu = new YAHOO.widget.Menu( 'sub-menu',
    {
      position: 'static',
      lazyload: true
    } );
    
    menu.render();
    
    items = menu.getItems();
  
    for( i = 0; i < items.length; i++ )
    {
      items[i].subscribe( 'mouseover', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        if( YAHOO.util.Dom.hasClass( this.element, 'yuimenuitem-active' ) )
        {
            toColor1 = '#970009';
            toColor2 = '#ffffff';
        }
        else
        {
            toColor1 = '#ffdb38';
            toColor2 = '#970009';
        }
        
        var bcAnim = new YAHOO.util.ColorAnim( this.element,
        {
            backgroundColor:
            {
                to: toColor1
            },
            color:
            {
                to: toColor2
            }
        }, 0.2 );
        
        bcAnim.animate();
      } );
    
      items[i].subscribe( 'mouseout', function( e )
      {
        YAHOO.util.Event.stopEvent( e );
        
        var bcAnim = new YAHOO.util.ColorAnim( this.element,
        {
          backgroundColor:
          {
            to: '#970009'
          },
          color:
          {
            to: '#ffffff'
          }
        }, 0.5 );
        
        bcAnim.animate();
      } );
    }
  },
  
  /**
   * initializes the search form
   * @return void
   */
  initSearch: function()
  {
      if( !YAHOO.util.Dom.inDocument( 'fSearch' ) )
      {
          return;
      }
      
      var defaultValue = 'Search...';
      
      if( YAHOO.util.Dom.get( 'iSearch' ).value == '' )
      {
          YAHOO.util.Dom.get( 'iSearch' ).value = defaultValue;
      }
      
      if( YAHOO.util.Dom.get( 'iSearch' ).value == defaultValue )
      {
          YAHOO.util.Dom.setStyle( 'iSearch', 'color', '#aaa' );
      }
      
      YAHOO.util.Event.addListener( 'iSearch', 'click', function( e, o )
      {
          YAHOO.util.Event.stopEvent( e );
          
          if( this.value == o.defaultValue )
          {
              this.value = '';
              YAHOO.util.Dom.setStyle( this, 'color', '#000' );
          }
          
          this.focus();
      }, {defaultValue:defaultValue} );
      
      YAHOO.util.Event.addListener( 'fSearch', 'submit', function( e, o )
      {
          var field = YAHOO.util.Dom.get( 'iSearch' );
          
          if( field.value == o.defaultValue )
          {
              field.value = '';
          }
      }, {defaultValue:defaultValue} );
  }
};

