Element.Events.extend({
	'wheelup': {
		type: Element.Events.mousewheel.type,
		map: function(event){
			event = new Event(event);
			if (event.wheel >= 0) this.fireEvent('wheelup', event)
		}
	},

	'wheeldown': {
		type: Element.Events.mousewheel.type,
		map: function(event){
			event = new Event(event);
			if (event.wheel <= 0) this.fireEvent('wheeldown', event)
		}
	}
});

var moveTimer, moveStatus = false, prdScrolling = false, productScroll, Scroller = new Class({
    options: {
        images: [],
        cats: [],
        productContainer: $empty(),
        totalProducts: 0,
        moveDelay: 10,
        moveSteps: 5,
        moveDirection: "Right",
        productToScrollTo: $empty(),
        arrowLeft: $empty(),
        arrowRight: $empty(),
        product_: $empty(),
        loadedImages: [],
        startCoords: {
            left: 0,
            top: 0
        }
    },
    initialize: function(options) {
        this.setOptions(options);
        this.get("productContainer").setOpacity("0");
    },
    set: function() {
        // internal setter for options that can take a json or a simple pair
        switch ($type(arguments[0])) {
            case "object":
                this.setOptions(arguments[0]);
            break;
            default:
                if (arguments.length == 2) {
                    var newo = {}
                        newo[arguments[0]] = arguments[1];

                    this.setOptions(newo);
                } else {
                    C.log("incorrect number of arguments");
                }
            break;
            case "false":
                return false;
            break;
        }
    },
    get: function(key) {
        // this.options getter, 1.2 stylee...
        return this.options[key];
    },
    goToProduct: function(i) {
        // go to product with index i.
        var _this = this;
        prdScrolling = true; // added to recall productScrolling state due to window.scroll

        window.addEvent("scroll", function() {
            if (prdScrolling) {
                // need a fix, if window.scroll fires, it stops the instance of our Fx.Scroll (productScroll)

                // go w/o
                _this.get("productContainer").scrollTo(_this.get("moveSteps")*i);
                _this.get("productContainer").setOpacity(1);
                _this.setButtons(); // fix scrolling left/right buttons as per scroll state
                moveStatus = false;
                prdScrolling = false;
            }
        });

        productScroll = new Fx.Scroll(this.get("productContainer"), {
    		transition: Fx.Transitions.Elastic.easeOut,
    		duration: 1500,
    		wait: true,
    		onComplete: function() {
    			moveStatus = false;
    			prdScrolling = false;
    			_this.get("productContainer").setOpacity(1);
    			_this.setButtons();
    		}
    	});

        var el = this.get("productContainer").getSize();

    	moveStatus = true;
        productScroll.scrollTo(el.scroll.x+this.get("moveSteps")*i, 0);
    },
    setButtons: function() {
        var el = this.get("productContainer").getSize();
        if (this.get("totalProducts") <= 10) {
            this.get("arrowRight").setProperty("src", "/img/scroll-right-off.jpg");
            this.get("arrowLeft").setProperty("src", "/img/scroll-left-off.jpg");
            return false;
        }
        if ((el.scroll.x + el.size.x)>= el.scrollSize.x - 1) {
            this.get("arrowRight").setProperty("src", "/img/scroll-right-off.jpg");
        }
        else {
            this.get("arrowRight").setProperty("src", "/img/scroll-right.jpg");
        }

        if (el.scroll.x <= 0) {
            this.get("arrowLeft").setProperty("src", "/img/scroll-left-off.jpg");
        }
        else {
            this.get("arrowLeft").setProperty("src", "/img/scroll-left.jpg");
        }
    },
    move: function(fn) {

        if (moveStatus)
            return false;

        var _this = this;
        productScroll = new Fx.Scroll(this.get("productContainer"), {
    		offset: {
    		    x:0,
    		    y:0
    		},
    		transition: Fx.Transitions.Cubic.easeOut,
    		duration: this.get("moveDelay"),
    		onComplete: function() {
    			moveStatus = false;
    			_this.get("productContainer").setOpacity(1);
    			_this.setButtons();
    			if (fn)
    			    fn.call(this);
    		}
    	});
        var el = this.get("productContainer").getSize();
        if (this.get("moveDirection") == "Right") {
            if ((el.scroll.x + el.size.x)>= el.scrollSize.x - 1) {
                $clear(moveTimer);
                this.get("arrowRight").setProperty("src", "/img/scroll-right-off.jpg");
                return;
            }
            this.get("productContainer").setOpacity(.8);

            moveStatus = true;
            productScroll.scrollTo(el.scroll.x+this.get("moveSteps"), 0);

        }
        else {
            var el = this.get("productContainer").getSize();
            if (el.scroll.x <= 0) {
                $clear(moveTimer);
                this.get("arrowLeft").setProperty("src", "/img/scroll-left-off.jpg");
                return;
            }
            this.get("productContainer").setOpacity(.8);

            moveStatus = true;
            productScroll.scrollTo(el.scroll.x-this.get("moveSteps"), 0);
        }

    }, // end mover
    stop: function() {
        $clear(moveTimer);
    },
    moveResume: function() {
        if ($("zoomer"))
            $("zoomer").fade(1,0);
        if (this.get("totalProducts") <= 10)
            return;
        moveTimer = (function() {
            if (moveStatus == false)
                this.move();
        }).periodical(this.get("moveDelay"), this);
    },
    loadImages: function() {
        // pre-load them
        var _this = this;
        this.get("product_").empty();
    	this.get("images").each(function(im, c) {
    	    // need to make a containing layer.
            var prod_layer = new Element('div', {
                "class": "scrollImage curImage"
            }).setStyles({
                "text-align": "center",
                float: "left",
                opacity: 1,
                width: 78,
                height: 84,
                padding: 2,
                "margin-right": 1,
                border: (_this.get("currentProduct") == im.title) ? "1px solid #c6d9d3" : "1px solid #fff",
                background: (_this.get("currentProduct") == im.title) ? "#fff url(/img/prodScrollCurrent.gif) repeat-x bottom left" : "#fff url(/img/tiny_red.gif) no-repeat center center"
            }).inject(_this.get("product_")); // add to dom within the product_ object

            if (im.url != "#") {
                prod_layer.addEvent("click", function() {
                    window.location.href = im.url;
                }); // addEvent etc.
            }
            else {
                _this.set("productToScrollTo", c);
                prod_layer.removeClass("curImage");
            }

            var thumb = new Asset.image(im.image, {title: im.title + " by " + im.brand}).setStyles({height: 70, width: 70}).inject(prod_layer);
            new Element("div").setHTML("<div style='text-align: center; font-weight: bold;'>" +im.price+"</div>").inject(prod_layer);

            var mytime, showtime;

            prod_layer.addEvents({
                mouseenter: function() {
                    var __this = this;
                    $clear(mytime);
                    $clear(showtime);
                    if (moveStatus)
                        return false;

                    showtime = (function() {
                        _this.set("mouseOverDelay", 200);
                        if ($("zoomer")) {
                            $("zoomer").dispose();
                        }
                        var coords = __this.getPosition();
                        var parentScroll = _this.get("productContainer").getSize();

                        var newCoordinates = {
                            left: (_this.get("startCoords").left == 0) ? coords.x - parentScroll.scroll.x - 36 : _this.get("startCoords").left,
                            top: coords.y - 36,
                            newLeft: coords.x - parentScroll.scroll.x - 36
                        }

                        var zoomer = new Element("div", {
                            id: "zoomer"
                        }).setStyles({
                            border: "1px solid #000",
                            position: "absolute",
                            left: newCoordinates.left,
                            top: newCoordinates.top,
                            width: 144,
                            padding: 3,
                            background: "#fff url(/img/prodScrollCurrent.gif) repeat-x bottom left",
                            "text-align": "center"
                        }).setOpacity(.5).addEvents({
                            mouseleave: function() {
                                startCoords = this.getCoordinates();
                                mytime = (function() {
                                    _this.set("startCoords", {
                                        left: 0
                                    });
                                }).delay(500);
                                this.dispose();
                                _this.zoomed = false;
                                if ($("wheeltip"))
                                    this.tipaway();
                            },
                            mouseenter: function() {
                                _this.zoomed = true;
                                if (!_this.get("shown") && _this.get("images").length > 10) {
                                    /*this.tooltip("You can use your mousewheel to scroll between different products", {
                                        delay: 5000,
                                        topOffset: 82,
                                        id: "wheeltip",
                                        opacity: 1
                                    });*/
                                    _this.set("shown", true);
                                }
                            },
                            wheelup: function(e) {
                                new Event(e).stop();
                                _this.set("moveDirection", "Left");
                                _this.move((function() {
                                    this.dispose();
                                    _this.set("mouseOverDelay", 0);
                                }).bind(this));
                            },
                            wheeldown: function(e) {
                                new Event(e).stop();
                                _this.set("moveDirection", "Right");
                                _this.move((function() {
                                    this.dispose();
                                    _this.set("mouseOverDelay", 0);
                                }).bind(this));
                            }
                        }).adopt(thumb.clone().addClass((im.url != "#") ? "curImage" : "").setStyles({height: 129, width: 129}).addEvents({
                            click: function() {
                                prod_layer.fireEvent("click");
                            }
                        })).inject(document.body).fade(.5, 1, {remove: false});


                        if (_this.get("startCoords").left != 0) {
                            var adjust = new Fx.Style(zoomer, "left", {duration: 300, transition: Fx.Transitions.Expo.easeOut});
                            adjust.start(newCoordinates.left, newCoordinates.newLeft);
                        }

                        new Element("div").setStyles({"text-align": "center", "font-size": "10px"}).setHTML("<a href='"+im.url+"'>"+im.title+"</a><br />"+im.brand+"<br />Tog price: <span style='color: #C11A2C'>"+im.price+"</span>").inject(zoomer);
                    }).delay(_this.get("mouseOverDelay"));

                    // showtime();
                },
                mouseleave: function() {
                    $clear(showtime);
                }
            });


    	}) // each end

    	// load has completed, show the layer
        this.get("productContainer").setStyle("visibility", "visible");

        this.setButtons();
        var fx = new Fx.Styles(this.get("productContainer"), {duration: 500}).start({opacity: 1});

        // if not in view, we need to go there...
        // where?
        if (this.get("productToScrollTo") < this.get("totalProducts") || this.get("productToScrollTo") >= 10) {
            this.goToProduct(this.get("productToScrollTo") - 4);
        }
        else {
            this.set("productToScrollTo", 0);
        }

    }, // end loadImages
    setEvents: function() {
        // define events for arrows and the likes.
        var _this = this;
        this.get("arrowRight").addEvents({
            mouseenter: function() {
                _this.set("moveDirection", "Right");
                _this.moveResume();
            },
            mouseleave: function() {
                _this.stop();
            }
        });

        this.get("arrowLeft").addEvents({
            mouseenter: function() {
                _this.set("moveDirection", "Left");
                _this.moveResume();
            },
            mouseleave: function() {
                _this.stop();
            }
        });

        // changing category for images...
        /*
        $("ScrollStats").getFirst().addEvents({
            click: function() {
                toggleModal("#fff");

                $("modal").addEvents({
                    click: function() {
                        $("catselect").empty();
                        if (window.ie) {
                            $("modal").newFade({from: .8});
                            $("catselect").newFade();
                            return;
                        }
                        startC = $merge({
                            opacity: 0
                        }, startC);
                        myfx.start(startC).chain(function() {
                            $("modal").dispose();
                            $("catselect").dispose();
                        });
                    }
                });

                var catselect, startC = this.getCoordinates(), winSize = window.getSize();;
                var myfx = new Fx.Styles(catselect = new Element("div", {
                    id: "catselect"
                }).setStyles({
                    position: "absolute",
                    left: startC.left,
                    top: startC.top,
                    width: startC.width,
                    height: startC.height,
                    background: "#fff",
                    border: "1px solid #000",
                    "z-index": 10000000
                }).inject(document.body), {duration: 400, transition: Fx.Transitions.Expo.easeOut});

                // calc target coords.
                var cy = 478, cx = 596;
                catbox = {
                    y: winSize.scroll.y + (winSize.size.y / 2) - (cy / 2),
                    x: winSize.size.x / 2 - cx / 2,
                    width: cx,
                    height: cy
                }

                if (catbox.y <= 20)
                    catbox.y = 20;


                myfx.start({
                    height: catbox.height,
                    width: catbox.width,
                    left: catbox.x,
                    top: catbox.y
                }).chain(function() {
                    var catcaption = new Element("div", {
                        id: "catcaption"
                    }).setStyles({
                        background: "url(/img/modal_header.jpg) no-repeat -80px center",
                        height: 23,
                        width: catbox.width,
                        left: 0,
                        top: 0,
                        clear: "both",
                        opacity: 0,
                        "font-weight": "bold",
                        "text-align": "center",
                        "border-bottom": "4px solid #fff",
                        "border-top": "4px solid #fff"
                    }).setHTML("<div style='width: 500px; float: left; padding-top: 3px'>Please select a new category of products below</div>").inject(catselect).fade(0,.8, {reclaim: false, remove: false})

                    new Element("img", {
                        id: "closebutton",
                        "class": "curImage",
                        src: '/img/lightbox-close.gif',
                        'title': 'Click to close large views'
                    }).setStyles({
                        width: 80,
                        height: 26,
                        float: "right"
                    }).injectTop(catcaption).addEvent("click", function() {
                        $("modal").fireEvent("click");
                    });

                    var columns = [
                        new Element("div").setStyles({
                            float: "left",
                            width: 198,
                            "margin-right": 2
                        }).inject($("catselect")),
                        new Element("div").setStyles({
                            float: "left",
                            width: 198,
                            "margin-right": 2
                        }).inject($("catselect")),
                        new Element("div").setStyles({
                            float: "left",
                            width: 196
                        }).inject($("catselect"))
                    ];

                    var done = 0, targetDiv = 0;
                    _this.get("cats").each(function(el, i) {
                        done++;
                        if (done > 15 && el.level == 0) {
                            done = 0;
                            targetDiv++;
                        }

                        new Element("div", {
                            id: "cat"+i,
                            title: el.name
                        }).inject(columns[targetDiv]).setHTML("<strong>"+el.name+"</strong> (" + el.count+")")
                            .setStyles({
                            padding: 2,
                            margin: 1,
                            width: 190 - (el.level+1) * 2,
                            float: "left",
                            "padding-left": (el.level+1) * 2
                        }).addClass("cur").addEvents({
                            mouseenter: function() {
                                this.setStyles({background: "yellow"});
                            },
                            mouseleave: function() {
                                this.setStyles({background: "#fff"});
                            },
                            click: function(e) {
                                this.getParent().getParent().setStyles({
                                    background: "#fff url(/img/tiny_red.gif) no-repeat center center"
                                }).setHTML("<center><h1 style='margin-top:175px; color: #777'>Loading your new products, please wait...</h1></center>");
                                $("otherName").setText(this.getProperty("title"));
                                _this.set("images", []);
                                new Ajax("/accountAjax.php?a=getsubproducts&id="+el.id, {
                                    method: "get",
                                    onComplete: function() {
                                        zoomed = false;
                                        eval(this.response.text);
                                    }
                                }).request();
                            }
                        });
                    });
                });


            }
        }); // end cat event
        */

    } // end setEvents
}); // end togs_scroller

Scroller.implement(new Events, new Options);
