/**
 *  ImageFlow 0.9 - Protorized, Lightboxed & Object Oriented
 *
 *  This is the prototype & lightbox v204 compatible,
 *  object oriented version of ImageFlow.
 *  Added a feature to prevent images from being scaled larger than the source file is.
 *  Updated by Fabian Lange 2. May 2008 - http://blog.hma-info.de
 *  I WILL NOT PROVIDE SUPPORT FOR THIS,
 *  thus might update the script as soon as the original author provides updates
 *
 *  You WILL need to adjust the Lightbox Integration. See blow at:
 *  // ** PATCH YOUR LIGHTBOX HERE ** //
 *
 *  I consider all my work in this as free for any use. 
 *  Do what you want, but give credit. (CC-BY)
 *
 *  ----------------------------------------------------------------------------
 *  Finn Rudolph said in his version:
 *  This code is based on Michael L. Perrys Cover flow in Javascript.
 *  For he wrote that "You can take this code and use it as your own" [1]
 *  this is my attempt to improve some things. Feel free to use it! If
 *  you have any questions on it leave me a message in my shoutbox [2].
 *
 *  The reflection is generated server-sided by a slightly hacked
 *  version of Richard Daveys easyreflections [3] written in PHP.
 *
 *  The mouse wheel support is an implementation of Adomas Paltanavicius
 *  JavaScript mouse wheel code [4].
 *
 * Thanks to Stephan Droste ImageFlow is now compatible with Safari 1.x.
 *
 *
 *  [1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
 *  [2] http://shoutbox.finnrudolph.de/
 *  [3] http://reflection.corephp.co.uk/v2.php
 *  [4] http://adomas.org/javascript-mouse-wheel/
 */

var ImageFlow = Class.create();

ImageFlow.prototype = {
    image_id: 0,      //center picture id
    current: 0,       //current pixel offset
    target: 0,        //target pixel offset
    xstep: 150,
    timer: false,     // if true stepping will occur
    array_images: [], // holds all image objects
    max: 0,  //number of images
    /* some more variables for drag handling of the slider, can be improved for sure later */
    new_slider_pos: 0,
    dragging: false,
    dragobject: null,
    dragx: 0,
    posx: 0,
    new_posx: 0,


    initialize: function(options) {

        this.options = Object.extend({
              max_original:   true,           // do not scale images bigger than they are.
              reflection_p:   0.4,            // Sets the height of the reflection in % of the source image 
              focus:          3,              // Sets the numbers of images on each side of the focussed one
              slider_width:   14,             // Sets the px width of the slider div
              images_cursor:  'pointer',      // Sets the cursor type for all images default is 'default'
              slider_cursor:  'e-resize',     // Sets the slider cursor type: try "e-resize" default is 'default'
              imageflow:      'imageflow',    // Default is 'imageflow'
              loading:        'flowloading',  // Default is 'loading'
              images:         'images',       // Default is 'images'
              captions:       'captions',     // Default is 'captions'
              scrollbar:      'scrollbar',    // Default is 'scrollbar'
              slider:         'slider'        // Default is 'slider'
        }, options || {});
       
        /* Cache document objects in global variables */
        this.imageflow_div = $(this.options.imageflow);
        this.img_div = $(this.options.images);
        this.scrollbar_div = $(this.options.scrollbar);
        this.slider_div = $(this.options.slider);
        this.caption_div = $(this.options.captions);
       
        /* Calculate width and height of various objects */
        this.resize()

        this.slider_div.style.cursor = this.options.slider_cursor;

        //i think a foreach could go here as well
        var nodecount = this.img_div.childNodes.length;
        for (var index = 0; index < nodecount; index++) {
            /* skip whitespace nodes */
            var image = this.img_div.childNodes.item(index);
            if (image.nodeType == 1) {
                this.array_images[this.max] = image;

                /* Store image index */
                image.i = this.max;

                /* Store original dimensions */
                image.w = image.width;
                image.h = image.height;

                /* Check source image format. Get image height minus reflection height! */
                if ((image.w + 1) > (image.h / (this.options.reflection_p + 1))) {
                    /* Landscape format */
                    image.pc = 118;
                } else {
                    /* Portrait and square format */
                    image.pc = 90;
                }

                /* Set image cursor type */
                image.style.cursor = this.options.images_cursor;
                this.max++;
            }
        }

        this.handleKeyAction = this.handleKeyAction.bindAsEventListener(this);
        document.observe('keydown', this.handleKeyAction);

        this.handleMouseAction = this.handleMouseAction.bindAsEventListener(this);
        this.imageflow_div.observe('DOMMouseScroll', this.handleMouseAction);

        this.dragstart = this.dragstart.bindAsEventListener(this);
        this.slider_div.observe('mousedown', this.dragstart);
        this.handleDrag = this.handleDrag.bindAsEventListener(this);
        document.observe('mousemove', this.handleDrag);
        this.dragstop = this.dragstop.bindAsEventListener(this);
        document.observe('mouseup', this.dragstop);
        /* Avoid text and image selection while dragging  */
        document.onselectstart = function() {return ! dragging;}
        
        Event.observe(window, 'resize',function() { this.resize(); this.moveCurrent()}.bind(this));
        
        //init done - start this imageflow
        $(this.options.loading).hide();
        $(this.options.images).style.visibility = 'visible';
        $(this.options.scrollbar).style.visibility = 'visible';
        this.center();
    },

    resize: function() {
        this.images_width = this.img_div.offsetWidth;
        this.images_top = this.imageflow_div.offsetTop;
        this.images_left = this.imageflow_div.offsetLeft;

        this.size = this.images_width * 0.5;
        this.max_height = this.images_width * 0.51;

        this.scrollbar_width = this.images_width * 0.6;
        this.max_conf_focus = this.options.focus * this.xstep;
        this.conf_slider_width = this.options.slider_width * 0.5;

        this.imageflow_div.style.height = this.max_height + 'px';
        this.img_div.style.height = this.images_width * 0.338 + 'px';

        this.caption_div.style.width = this.images_width + 'px';
        this.caption_div.style.marginTop = this.images_width * 0.03 + 'px';

        this.scrollbar_div.style.marginTop = this.images_width * 0.02 + 'px';
        this.scrollbar_div.style.marginLeft = this.images_width * 0.2 + 'px';
        this.scrollbar_div.style.width = this.scrollbar_width + 'px';
    },

    step: function() {
        if (this.target < this.current - 1 || this.target > this.current + 1) {
            this.moveTo(this.current + (this.target - this.current) / 3);
            window.setTimeout(this.step.bind(this), 50);
            this.timer = true;
        } else {
            this.timer = false;
        }
    },

    center: function() {
        this.glideTo(Math.floor(this.max / 2));
    },

    moveCurrent: function() {
        this.moveTo(this.current);
        this.glideTo(this.image_id);
    },

    glideTo: function(new_image_id) {
        this.image_id = new_image_id;
        this.target = ( - this.xstep) * new_image_id;
        if (!this.timer) {
            window.setTimeout(this.step.bind(this), 50);
            this.timer = true;
        }

        /* Display new caption */
        var caption = this.array_images[this.image_id].getAttribute('alt');
        if (caption == '') caption = '&nbsp;';
        this.caption_div.innerHTML = caption;

        /* Set scrollbar slider to new position */
        if (!this.dragging) {
            this.new_slider_pos = (this.scrollbar_width * ( - (this.target * 100 / ((this.max - 1) * this.xstep))) / 100) - this.new_posx;
            this.slider_div.style.marginLeft = (this.new_slider_pos - this.options.slider_width) + 'px';
        }
    },

    moveTo: function(x) {
        this.current = x;
        var zIndex = this.max;

        for (var index = 0; index < this.max; index++) {
            var image = this.array_images[index];
            var current_image = index * -this.xstep;

            /* Don't display images that are out of view */
            if ((current_image + this.max_conf_focus) < this.target || (current_image - this.max_conf_focus) > this.target) {
                image.style.visibility = 'hidden';
                image.style.display = 'none';
            } else {
                var z = Math.sqrt(10000 + x * x) + 100;
                var xs = x / z * this.size + this.size;

                /* Still hide images until they are processed, but set display style to block */
                image.style.display = 'block';

                /* Process new image height and image width */
                var new_img_h = (image.h / image.w * image.pc) / z * this.size;
                var new_img_w = image.pc / z * this.size;
                if (new_img_h > this.max_height) {
                    new_img_h = this.max_height;
                    new_img_w = image.w * new_img_h / image.h;
                }
                var w_space = 0;
                if (this.options.max_original && (new_img_h > image.h || new_img_w > image.w)){
                  new_img_h = image.h;
                  w_space = (new_img_w - image.w) / 2;
                  new_img_w = image.w;
                }
                var new_img_top = (this.images_width * 0.34 - new_img_h) + this.images_top + ((new_img_h / (this.options.reflection_p + 1)) * this.options.reflection_p);

                /* Set new image properties */
                image.style.left = xs - (image.pc / 2) / z * this.size + this.images_left + w_space +'px';
                if (new_img_w && new_img_h) {
                    image.style.height = new_img_h + 'px';
                    image.style.width = new_img_w + 'px';
                    image.style.top = new_img_top + 'px';
                }
                image.style.visibility = 'visible';

                /* Set image layer through zIndex */
                if (x < 0) {
                    zIndex++;
                } else {
                    zIndex--;
                }

                /* Standard onclick for every visible image: glide to center this image. */
                /* Kind a crude back reference. But i did not manage to get this.i when binding this */
                image.onclick = function(e) { this.glideTo(Event.element(e).i); }.bindAsEventListener(this);

                /* Change zIndex and onclick function of the focussed image */
                if (image.i == this.image_id) {
                    zIndex = zIndex + 1;
                    image.onclick = function() {
                        var linkElement = new Element('a');
                        // ** PATCH YOUR LIGHTBOX HERE ** //
                        // here some lightbox magic. we use the thubnail src and make it to full size src.
                        linkElement.href = this.getAttribute('src').replace(/bildeffekt/, "bild");
                        linkElement.title = this.getAttribute('alt');
                        linkElement.rel = 'lightbox';
                        //this requires lightbox to be bound to myLightbox
                        mylightbox.start(linkElement);
                    }
                }
                image.style.zIndex = zIndex;
            }
            x += this.xstep;
        }
    },

    /* Handle mouse and keyboard changes. Note that size of delta is ignored right now*/
    handle: function(delta) {
        if (delta > 0) {
            if (this.image_id > 0) {
                this.glideTo(this.image_id - 1)
            }
        } else {
            if (this.image_id < (this.max - 1)) {
                this.glideTo(this.image_id + 1)
            }
        }
    },

    handleKeyAction: function(event) {
        switch (event.keyCode) {
        case 39:
            this.handle(-1);
            event.stop();
            break;
        case 37:
            this.handle(1);
            event.stop();
            break;
        }
    },

    /* Simple event handler for mouse wheel event */
    handleMouseAction: function(event) {
        var delta = 0;
        if (event.wheelDelta) {
            delta = event.wheelDelta / 120;
        } else if (event.detail) {
            delta = -event.detail / 3;
        }
        if (delta) {
            this.handle(delta);
        }
        event.stop();
    },

    /* This function is called on mouse movement and moves an object (= slider div) on user action */
    handleDrag: function(event) {
        this.posx = event.pointerX();
        if (this.dragobject != null) {
            this.dragging = true;
            this.new_posx = (this.posx - this.dragx) + this.options.slider_width;

            /* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */
            if (this.new_posx < ( - this.new_slider_pos)) {
                this.new_posx = -this.new_slider_pos;
            }
            if (this.new_posx > (this.scrollbar_width - this.new_slider_pos)) {
                this.new_posx = this.scrollbar_width - this.new_slider_pos;
            }
            this.dragobject.style.left = this.new_posx + 'px';
            this.glideTo(Math.round((this.new_posx + this.new_slider_pos) / ((this.scrollbar_width) / (this.max - 1))));
        }
    },


    /* This function is called to drag an object (= slider div) */
    dragstart: function() {
        this.dragobject = this.slider_div;
        this.dragx = this.posx - this.dragobject.offsetLeft + this.new_slider_pos;
    },
    /* This function is called to stop dragging an object */
    dragstop: function() {
        this.dragobject = null;
        this.dragging = false;
    }
} // end of class

Event.observe(window, 'load', function() { myimageFlow = new ImageFlow(); });
