var rotateSize = 4;

String.prototype.rewriteUrl = function(){
    var current = this;

    var images = $$('img');
    if((images != null) && (images.first() != null)){
        var expr = /;jsessionid\=\w+(\?)?/;

        var results = expr.exec(images.first().src);
        if((results != null)){
            var session = results[0].gsub('?', '');
            if(current.include('?')){
                current = current.sub(/\?/,session.concat('?'));
            }else{
                current = current.concat(session);
            }
        }//end if(results <> null)
    }//end if(images <> null)

return current;
}//end rewriteUrl()

var ContentRotator = Class.create({

  initialize: function(size) {
    this.count = 1;
    this.size = size;
    this.disable = false;
    this.content = new Array(this.size);
    this.images = new Array(this.size);
  },//initialize(size)

  loadAllContent: function(){
      for(i=1; i < this.size; i++){
          this.loadContent(i+1);
      }//end for(i)

      if(this.count == 1){
          this.content[1] = $('ChangeContent').innerHTML;
      }
  },//end preloadContent()

  loadAllImages: function(){
      var imageObj = new Image();

      var i = 0;
      for(i=2; i<this.size; i++){
          imageObj.src= 'Images/Pages/Home/PhotoStack/Photo'+(i)+'.jpg'.rewriteUrl();
     //          var image = new Image();//document.createElement("img");
//          image.src = 'Images/Pages/Home/PhotoStack/Photo'+(i+1)+'.jpg'.rewriteUrl();
//          this.images[i] = image;
          //image.setAttribute("src", 'Images/Pages/Home/PhotoStack/Photo'+(i+1)+'.jpg'.rewriteUrl());
      }//end for(i)
  },//end loadAllImages()

  loadContent: function(index){
      new Ajax.Request('Home/Rotation'+index+'.apt'.rewriteUrl(),{
          method: 'get',

          onSuccess: function(transport){
              this.content[index] = transport.responseText;
          }.bind(this)
      });
  },//end loadContent()

  rotate: function(){
    this.count++;
    if(this.count > this.size){
        this.count = 1;
    }

    if(this.content[this.count] != null){
        $('ChangeContent').innerHTML = this.content[this.count];
        window.setTimeout('rotator.disable = false;',200);
        
    }else{
        new Ajax.Updater({success: 'ChangeContent'},'Home/Rotation'+this.count+'.apt'.rewriteUrl(),{
            method: 'get',

            onSuccess: function(transport){
                this.content[this.count] = transport.responseText;
            }.bind(this),
            
            onComplete: function(transport){
                window.setTimeout('rotator.disable = false; = false;',200);
            }

        });
    }

    var image = $('RotatingImage');
    if(image != null){ //alert('here');
//        var newImage = this.images[this.count];
//        if(newImage == null)
//            newImage = image;
        image.setAttribute('src', 'Images/Pages/Home/PhotoStack/Photo'+this.count+'.jpg'.rewriteUrl());
        switch(this.count){
            case 1: image.setAttribute('alt','Image of a fly fisherman catching a Brown Trout');
                    break;
            case 2: image.setAttribute('alt','Image of a fly fisherman on a river in the winter');
//                    alert('here 2');
                    break;
            case 3: image.setAttribute('alt','Image of Rocky Mountain National Park');
                    break;
            case 4: image.setAttribute('alt','Image of a fly fisherman holding a Rainbow Trout');
                    break;
        }
//        $('RotatingImage') = newImage;
    }
  },//end rotate()

  reverse: function(){
    this.count--;
    if(this.count < 1){
        this.count = this.size;
    }

    if(this.content[this.count] != null){
        $('ChangeContent').innerHTML = this.content[this.count];
        window.setTimeout('rotator.disable = false;',200);
    }else{
        new Ajax.Updater({success: 'ChangeContent'},'Home/Rotation'+this.count+'.apt'.rewriteUrl(),{
            method: 'get',

            onSuccess: function(transport){
                this.content[this.count] = transport.responseText;
            }.bind(this),

            onComplete: function(transport){
                window.setTimeout('rotator.disable = false;',200);
            }
        });
    }

    var image = $('RotatingImage');
    if(image != null){
        image.setAttribute('src', 'Images/Pages/Home/PhotoStack/Photo'+this.count+'.jpg'.rewriteUrl());
        switch(this.count){
            case 1:image.setAttribute('alt','Image of a fly fisherman catching a Brown Trout');
                    break;
            case 2:image.setAttribute('alt','Image of a fly fisherman on a river in the winter');
                    break
            case 3:image.setAttribute('alt','Image of Rocky Mountain National Park');
                    break;
            case 4:image.setAttribute('alt','Image of a fly fisherman holding a Rainbow Trout');
                    break;
        }
    }
  }//end reverse()
});

var FormHandler = Class.create(ErrorHandler,{
    valid: function(input, target){
        if((input.hasClassName("errorfield"))){
            input.removeClassName("errorfield");
            var label = input.getAttribute('label');
            if((label != null) && ($(label) != null) && $(label).hasClassName('errorlabel')){
                $(label).removeClassName('errorlabel');
            }
        }
    },//end valid(input)

    error: function(input){
        if(!input.hasClassName("errorfield")){
            input.addClassName("errorfield");

            var label = input.getAttribute('label');
            if((label != null) && ($(label) != null) && !$(label).hasClassName('errorlabel')){
                $(label).addClassName('errorlabel');
            }

            if((input.identify() != null) && (input.identify() == 'SignUpTF')){
                $('SignUpTF').value = 'Invalid email!';
            }
        }
    }//end error(input)

});

var updater = null;

var rotator = new ContentRotator(this.rotateSize);

document.observe("dom:loaded", function() {
    if($('ManualRefresh') != null){
        document.location = '/?refresh=js'.rewriteUrl();
    }
});


document.observe("click", function(event){
    if(event.target != null){
        if((event.target.identify() == null) || (event.target.identify() != 'SignUpButton')){
            var textField = $('SignUpTF');
            if((textField != null) && ((textField.value == null) || (textField.value.strip() == '') || (textField.value == 'Invalid email!'))){
                $('SignUpTF').value = 'Enter email address';
            }
        }

    }
});

var submitValidator = new FormValidator(new RequiredValidator(), new EmailValidator(), new FormHandler());

window.onload = function(){

    rotator.loadAllContent();
    rotator.loadAllImages();

    Event.observe('LeftButton', 'click', function(event){
        if(!rotator.disable){
            rotator.disable = true;
            rotator.reverse();
        }
        Event.stop(event);
    });

    Event.observe('RightButton', 'click', function(event){
       if(!rotator.disable){
           rotator.disable = true;
           rotator.rotate();
       }
       Event.stop(event);
    });


    Event.observe('SignUpBox', 'click', function(event){
        if(event.target != null){
            if(event.target.identify() != null){
                if(event.target.identify() != 'SignUpButton'){
                    if(event.target.identify() == 'SignUpTF'){
                        var textfield = $('SignUpTF');
                        if((textfield.value == 'Enter email address') || (textfield.value == 'Invalid email!')){
                            textfield.value = '';
//                            alert('here');
                        }

                        if($('SignUpTF').hasClassName('errorfield')){
                            $('SignUpTF').removeClassName('errorfield');
                        }
                    }
                    event.stopPropagation();
                }
            }else{
                event.stopPropagation();
            }
        }else{
            event.stopPropagation();
        }


        if((event.target == null) || (event.target.identify() == null) || (event.target.identify() != 'SignUpButton')){
            event.stopPropagation();
        }
    });

    Event.observe('PauseButton', 'click', function(event){
        if(!rotator.disable){
            var span = $$('#PauseButton span');
            if((span != null) && (span.first() != null)){
                var button = span.first();
                if(button.hasClassName('pause')){
                    rotator.disable = true;
                    button.setAttribute('alt', '>');
                    button.setAttribute('class', 'play');
                    this.updater.stop();
                    window.setTimeout('rotator.disable = false;',200);
                }else{
                    rotator.disable = true;
                    button.setAttribute('alt', '||');
                    button.setAttribute('class', 'pause');
                
                    rotator.rotate();
                    this.updater = new PeriodicalExecuter(function(pe) {
                        rotator.rotate();
                    }, 10);
                    window.setTimeout('rotator.disable = false;',200);
                }

                Event.stop(event);
            }
        }else{
            Event.stop(event)
        }
    }.bind(this));

    this.updater = new PeriodicalExecuter(function(pe) {
        rotator.rotate();
    }, 10);

    if($('SignUpButton') != null){
        Event.observe('SignUpButton', 'click', function(event){
            if(!submitValidator.validateForm(event.target.form)){
                Event.stop(event);
            }
        }.bind(this));
    }//end if($CommentPostButton <> null)

};

