//<script>
if(!Prototype || !Scriptaculous) {
    alert('Please include prototype and script.aculo.us libraries to use the slider!');
}


Effect.Scroll = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext = true;
      this.element.appendChild(this.element.firstChild);
    }

    this.originalLeft = this.element.scrollLeft;
    this.originalTop = this.element.scrollTop;

    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } else {

    }
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});

function moveTo(container, element){
  var container_y = Position.cumulativeOffset($(container))[1]
  var element_y = Position.cumulativeOffset($(element))[1]
  var container_x = Position.cumulativeOffset($(container))[0]
  var element_x = Position.cumulativeOffset($(element))[0]
  new Effect.Scroll(container, {
      x:(element_x - container_x), 
      y:(element_y - container_y),
      duration: 1
      //,transition: Effect.Transitions.spring
  });
  return false;
}


var Slider = {
    options : {
        slideDuration: 2,
        transitionDuration: 1,
        showLinks: true,
        linkStyle: 'dots', //- 'numbers' or 'dots'
        linkAlign: 'center' //- left right or center
    },
    imageContainerId: 'scroll_inner',
    linkContainerId: 'scroll_links',
    
    loadCount: 0,
    
    links: [],
    images: [],
    
    scroll: null,
    currentLink : null,
    currentSlide : 1,

    init : function() {
    
        //- add the slide css styles
        var link = document.createElement("LINK");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", "../slide.css");
        document.getElementsByTagName("HEAD")[0].appendChild(link);
    
        $('scroll_links').setStyle({
           textAlign:this.options.linkAlign || 'right'
        });
        /*this.scroll = new Fx.Scroll("scroll_wrapper", {
            wait: false,
            duration: 500,
            wheelStops: false,
            transition: Fx.Transitions.Quad.easeInOut
        });*/
    },

    addImage : function (options) {
        //this.imageCount++;

        var i = this.images.length;
        
        this.images[i] = new Element("IMG");
        this.images[i].setAttribute("src", options.image);
        this.images[i].setAttribute("id", "item_" + (i+1));
        this.images[i].setStyle({
            width: options.width + 'px'
            ,height: options.height + 'px'
        });

        if(i == 0) { //- adjust size of banner viewport to first image (they should all be the same size anyway)
            $('scroll_links').setStyle({width:options.width+'px'});
            $$('#scroll_bg, #scroll_wrapper').invoke('setStyle', {
                width: options.width + 'px'
                ,height: options.height + 'px'
            });
        }


        this.images[i].className = "item";
    
        $("scroll_inner").appendChild(this.images[i]);

        this.images[i] = $(this.images[i]);

        this.images[i].observe('mouseover', function(event) {
            Event.stop(event);
            this.style.cursor = "pointer";
        });

        this.images[i].observe('click', function(event) {
            if(this.timer) clearInterval(this.timer);
            Event.stop(event);
        
            if(options.target == '_blank') {
                window.open(options.url, '');
            }    
            else {
                window.location.href = options.url;
            }
        }.bindAsEventListener(this));
   
        //this.images[i].observe("load", this.checkAllLoaded.bindAsEventListener(this));
        this.checkAllLoaded();
        
        //- if we want number links and if theres somewhere to put them!
        if(this.options.showLinks && $(this.linkContainerId)) {
            i = this.links.length;
            this.links[i] = new Element('A');
            this.links[i].writeAttribute("href", "#");
            this.links[i].writeAttribute("rel", ''+(i+1));
            this.links[i].id = 'link' + (i+1);
            if(!i) {
                this.currentLink = this.links[i];
                this.links[i].className = 'active_link';
            }
            
            if(this.options.linkStyle == 'numbers') {
                this.links[i].style.margin = '0 5px';
            }

            this.links[i].update( this.options.linkStyle == 'dots' ? '&bull;' : (i+1) );
            $('scroll_links').appendChild(this.links[i]);
            this.links[i] = $(this.links[i]);
            
            this.links[i].observe("click", function(event) {
                Event.stop(event);
                var el = Event.element(event);
                this.currentLink.className = "";
                el.className = "active_link";
                el.siblings().invoke("removeClassName", "active_link");
                this.currentLink = this;

                //Slider.scroll.toElement("item_" + el.getAttribute('rel'));
                //Effect.ScrollTo("item_" + el.getAttribute('rel'));
                //moveTo($("scroll_wrapper"), $("item_" + el.getAttribute('rel')));

                this.showSlide( el.getAttribute('rel') );

                return false;
            }.bindAsEventListener(this));
            
        }
    },
    
    isLoaded: false,
    checkAllLoaded : function(event) {
        
        this.loadCount++;

        //console.log(this.loadCount + ' >= ' + this.images.length);
        //alert(this.loadCount+' >= '+this.images.length);
        if(!this.isLoaded && this.loadCount >= this.images.length) {
            this.isLoaded = true;

            // make sure we are on the first frame
            //Slider.scroll.toElement("item_1");
            //Effect.ScrollTo("item_1");
            //moveTo($("scroll_wrapper"), $("item_1"));
            this.showSlide(1);

            if(this.options.showLinks) {
                  //$(Slider.linkContainerId).setStyle("opacity", 0);
                  //$(Slider.linkContainerId).setStyle("display", "block");
                  $(this.linkContainerId).appear({duration: 1});
            }

        }
    },

    nextSlide: function() {

        this.currentSlide++;
        if(this.currentSlide > this.images.length)
        this.currentSlide = 1;

		if(this.options.showLinks) {
            this.currentLink.className = "";
            $("link" + this.currentSlide).siblings().invoke("removeClassName", "active_link");
            $("link" + this.currentSlide).className = "active_link";
            this.currentLink = $("link" + this.currentSlide);
		}

        //Slider.scroll.toElement("item_" + this.currentSlide);
        //Effect.ScrollTo("item_" + this.currentSlide);
        this.showSlide(this.currentSlide);

    },

    showSlide: function(index) {

        if(this.timer) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        
        this.currentSlide = index;

        var container = $("scroll_wrapper");
        var element = $("item_" + index);

        var container_y = Position.cumulativeOffset($(container))[1]
        var element_y = Position.cumulativeOffset($(element))[1]
        var container_x = Position.cumulativeOffset($(container))[0]
        var element_x = Position.cumulativeOffset($(element))[0]
        if(this.currentEffect && this.currentEffect.state === "running") {
            this.currentEffect.cancel();
        }
        this.currentEffect = new Effect.Scroll(container, {
          x:(element_x - container_x),
          y:(element_y - container_y),
          duration: this.options.transitionDuration,
          afterFinish: function() {
            this.timer = window.setTimeout(this.nextSlide.bind(this)
                            , (this.options.slideDuration*1000));
          }.bind(this)
          ,transition: Effect.Transitions.sinoidal
        });

    }

}


document.observe("dom:loaded", function() {
    var load_count = 1;
    var current_link = $("link1");

    Slider.init();
    
    Slider.addImage({
        image: '/uploads/images/banners/catalogue_2010.jpg',
        url:   '/register',
        width: '170',
        height:'108',
        target:'_self'        
    });
    
    //var item_1 = $('item_1');

    //item_1.observe('load', function() {

                  Slider.addImage({
                image: '/uploads/images/banners/freshideas_1.jpg',
                url:   '/promotional-merchandise/latest-promotional-gift-ideas',
                width: '170',
                height:'108',
                target:'_self'        
            });
      
      
                    Slider.addImage({
                image: '/uploads/images/banners/ipod.jpg',
                url:   '/register',
                width: '170',
                height:'108',
                target:'_self'        
            });
      
      
                    Slider.addImage({
                image: '/uploads/images/banners/onlinecatalogue.jpg',
                url:   'http://bourneinternational.clickpromo.com/products',
                width: '170',
                height:'108',
                target:'_blank'        
            });
      
      
              $("scroll_inner").appear({duration: 1});
        //Slider.checkAllLoaded();
    
    //});


});
// </script>
