// Fix for dom:loaded in IE7/8
// http://frugalcoder.us/post/2008/09/11/Document-Ready-and-Loaded-Events-with-prototypejs.aspx
Object.extend(document, {
    isDocReady: false,
    isDocLoaded: false,
    ready: function(fn) { Event.observe(document, "doc:ready", fn); },
    load: function(fn) { Event.observe(document, "doc:loaded", fn); }
});
Event.observe(document, "dom:loaded", function() {
    Event.fire(document, "doc:ready");
    document.isDocReady = true;
    if (document.isDocLoaded)
        Event.fire(document, "doc:loaded");
});
Event.observe(window, "load", function() {
    document.isDocLoaded = true;
    if (!document.isDocReady) return;
    Event.fire(document, "doc:loaded");
});

(function() {
    /*
    var language;
    $.ajax({
        url: "http://ajaxhttpheaders.appspot.com",
        dataType: 'jsonp',
        success: function(headers) {
            language = headers['Accept-Language'];
            nowDoSomethingWithIt(language);
        }
    });
    */
    if ((navigator.language || navigator.userLanguage).match(/^es-/) && !document.cookie.match(/autolanguage=/)) {
        var name='autolanguage', value=navigator.language, domain='www.metaldetector.com', path='/', expdays=30;
        var d=new Date(), exp=exdays===null?'':(value===null?'Thu, 01-Jan-1970 00:00:01 GMT':d.setDate(d.getDate()+exdays));
        document.cookie=name+'='+escape(value)+(exp?';expires='+exp:'')+';domain='+escape(domain)+';path='+escape(path);
        location.href = 'http://www.metaldetector.com/?___store=espanol&___from_store=default';
    }
})()

// Close Btn
closebtn = '//assets.metaldetector.com/js/images-global/zoom/closebox.png';

// Lightbox
LightboxOptions.fileLoadingImage = '//s4deed25173806.img.gostorego.com/802754/cdn/media/s4/de/ed/25/17/38/06/ajax-loader.gif';
LightboxOptions.fileBottomNavCloseImage = '//s4deed25173806.img.gostorego.com/802754/cdn/media/s4/de/ed/25/17/38/06/designeditor/theme/current/9/css_editor_images/modale_close_blk.png';

//Cufon.replace('.site-nav .level-1, .font-alt, .widget-new-products .widget-title h2');

document.observe('doc:loaded', function() {
	setupZoom();

    // Fix magento firebug console output
    // Comment out when out of development
    try {
        var iframe = document.createElement('iframe');
        document.getElementsByTagName('body')[0].appendChild(iframe);
        $(iframe).setStyle({display:'none'});
        window.console = iframe.contentWindow.console;
        console.firebug = "faketrue";
    } catch (e) {}
    /**/

    if ($('holiday-block')) new TabSwitch('holiday-block');

    // Add "View Details" button after all "Add to cart" buttons
    $$('.products-grid .btn-cart').each(function(el) {
        $(el).insert({after:'<a class="btn-view-details" href="'+$(el).up('li').down('a').href+'"><span>View Details</span></a>'});
    });

    // Normalize table cell height in product grid
    $$('.products-grid').each(function(ul) {
        var liHeight, maxHeight = 0, lis = $(ul).childElements(), i;
        for (i=0; i<lis.length; i++) {
            liHeight = lis[i].getHeight();
            if (liHeight>maxHeight) maxHeight = liHeight;
        }
        for (i=0; i<lis.length; i++) {
            if($$('.cms-home-es')[0]) {
            	lis[i].setStyle({height:(maxHeight-50)+'px'});
            } else if($$('.cms-home')[0]) {
            	lis[i].setStyle({height:(maxHeight-90)+'px'});
            } else if($$('.catalogsearch-result-index')[0]) {
            	lis[i].setStyle({height:(maxHeight-130)+'px'});
            } else if(ul.id == 'upsell-product-list') {
            	lis[i].setStyle({height:(maxHeight-10)+'px'});
            } else {
            	lis[i].setStyle({height:(maxHeight-50)+'px'});
            }
        }
    });

    // Create layered navigation collapsed tree
    if ($('narrow-by-list')) $('narrow-by-list').setStyle({display:'block'});
    $$('#narrow-by-list dt').each(function(e) {
        var dt=$(e), dd=dt.next();
        if (dt.innerHTML=='Category') {
            dt.toggleClassName('expanded');
        } else {
            dd.hide();
        }
        dt.observe('click', function(ev) {
            dt.toggleClassName('expanded');
            Effect.toggle(dd, 'blind', {duration:.3});
        });
    });

    // Move Overview under media
    var media = $$('.product-img-box'), overview = $$('.short-description');
    if (media.length && overview.length) {
        $(media[0]).insert({bottom:$(overview[0])});
        $(overview[0]).setStyle({display:'block'});
    }

    // Move Add this under media
    var addthis = $$('.social-icons-small');
    if (media.length && addthis.length) {
        $(media[0]).insert({bottom:$(addthis[0])});
        $(addthis[0]).setStyle({display:'block'});
    }

    // Move Bonus items under shop block
    var shopcol = $$('.product-view .product-shop'), bonusitems=$$('.block-bonus-items');
    if (shopcol.length && bonusitems.length) {
        $(shopcol[0]).insert({bottom:$(bonusitems[0])});
        $(bonusitems[0]).setStyle({display:'block'});
    }
    // Remove tags box
    var boxtag = $$('.box-tags');
    if (boxtag.length) {
        $(boxtag[0]).remove();
    }

    //
    var minelab_warn = $$('.minelab-warranty-truth'), main = $$('.tab-content .std'), pdfList=$$('.pdf-list');
    if (main.length && minelab_warn.length) {
        if (pdfList.length) {
        	$(pdfList[0]).insert({after:$(minelab_warn[0])});
        } else {
        	$(main[0]).insert({top:$(minelab_warn[0])});
        }
        $(minelab_warn[0]).setStyle({display:'block'});
    }

    //
    var clearance = $$('.clearance-info'), addtolinks = $$('.add-to-links');
    if (clearance.length && addtolinks.length) {
        $(addtolinks[0]).insert({before:$(clearance[0])});
        $(clearance[0]).setStyle({display:'block'});
    }

    //
    var pro_collateral=$$('.product-collateral'), related_pros=$$('.box-related');
    if (pro_collateral.length && related_pros.length) {
        $(pro_collateral[0]).insert({before:$(related_pros[0])});
        $(related_pros[0]).setStyle({display:'block'});
    }

    // Set Related Products Height + Style
    var related_pros_ul = $$('.box-related .block-content');
    if (related_pros_ul.length && related_pros.length) {
        $(related_pros[0]).setStyle({
            height: $(related_pros_ul[0]).getHeight()+50+'px',
            overflow: 'auto'
        });
    }

    var priceBox=$$('.price-box'), priceGuarantee=$$('.price-guarantee');
    if (priceBox.length && priceGuarantee.length) {
        $(priceBox[0]).insert({top:$(priceGuarantee[0])});
        $(priceGuarantee[0]).setStyle({display:'block'});
    }

    //
    var collateralTab=$$('.collateral-tabs'), tabContainer=$$('.tab-container');
	if (collateralTab.length && tabContainer.length) {
		$(collateralTab[0]).setStyle({
			height:$(tabContainer[0]).getHeight()+15+'px'
		})
	};

    //
    var crosssell=$$('.crosssell'), cartCollaterals=$$('.cart-collaterals');
    if (crosssell.length && cartCollaterals.length) {
        $(cartCollaterals[0]).insert({bottom:$(crosssell[0])});
        $(crosssell[0]).setStyle({display:'block'});
    }

    //
    var couponTitle=$$('.cart-collaterals .deals .discount h2'), couponLink=$$('.coupon-btn');
    if (couponTitle.length && couponLink.length) {
        $(couponTitle[0]).insert({after:$(couponLink[0])});
        $(couponLink[0]).setStyle({display:'block'});
    }

    // Holiday Block
    var holidayBlock=$$('.holiday-block-r2'), categoryView=$$('.category-view'), categoryDescr=$$('.category-view .category-description'), productEssentials=$$('.product-view'), brandDescr=$$('.brand-cat-description');
    if (holidayBlock.length && categoryDescr.length) {
    	$(categoryDescr[0]).insert({before:$(holidayBlock[0])});
        $(holidayBlock[0]).setStyle({display:'block'});
    } if (holidayBlock.length && productEssentials.length) {
    	$(productEssentials[0]).insert({before:$(holidayBlock[0])});
        $(holidayBlock[0]).setStyle({display:'block'});
    } if (holidayBlock.length && brandDescr.length) {
    	$(brandDescr[0]).insert({before:$(holidayBlock[0])});
        $(holidayBlock[0]).setStyle({display:'block'});
    } if (holidayBlock.length && categoryView.length && brandDescr.length==0 && categoryDescr.length==0) {
		$(categoryView[0]).insert({top:$(holidayBlock[0])});
    	$(holidayBlock[0]).setStyle({display:'block'});
    }

/* Add CC icon treatment in Cart and switch Paypal and Checkout position */
	cartcotypes = $$('.cart .totals .checkout-types li');
	if (cartcotypes.length) {
		$(cartcotypes[1]).insert({after:$(cartcotypes[0])});
		$(cartcotypes[1]).addClassName('cc');
	}

/* Newsletter Input Reset */
    $$('.mini-newsletter input:text').each(function(el) {
        var defValue = el.value;
        el.observe('focus', function(ev) {
            if (el.value==defValue) el.value = '';
        });
        el.observe('blur', function(ev) {
            if (el.value=='') el.value = defValue;
        });
    });


    function mouseEnterLeave(e) {
        var rel = e.relatedTarget, cur = e.currentTarget;
        if (rel && rel.nodeType == 3) {
            rel = rel.parentNode;
        }
        if (
            // Outside window
            rel == undefined ||
            // Firefox/other XUL app chrome
            (rel.tagName && rel.tagName.match(/^xul\:/i)) ||
            // Some external element
            (rel && rel != cur && rel.descendantOf && !rel.descendantOf(cur))
        ) {
            e.currentTarget.fire('mouse:' + this, e);
            return;
        }
    }

    $$('.block-home-brands .sub').each(function(el) {
        var sub = $(el), div = sub.up('div'), img = sub.previous('img'), stillOn, hideTimer, showEffect, hideEffect;

        function show() {
            // sub.setStyle({display:'block'}); return;
            hideEffect && hideEffect.cancel();
            sub.setStyle({display:'block', opacity:0, marginTop:'10px'});
            showEffect = new Effect.Parallel([
                new Effect.Opacity(sub, {to:1}),
                new Effect.Morph(sub, {style:{marginTop:'0px'}})
            ], {duration:.4});
        }
        function hide() {
            showEffect && showEffect.cancel();
            hideEffect = new Effect.Parallel([
                new Effect.Opacity(sub, {to:0, afterFinish: function() {
                    sub.setStyle({display:'none'});
                }}),
                new Effect.Morph(sub, {style:{marginTop:'-10px'}})
            ], {duration:.4});
        }
        div.observe('mouseover', mouseEnterLeave.bind('enter'));
        div.observe('mouseout', mouseEnterLeave.bind('leave'));
        div.observe(!!Prototype.Browser.IE ? 'mouseenter' : 'mouse:enter', show);
        div.observe(!!Prototype.Browser.IE ? 'mouseleave' : 'mouse:leave', hide);
    });
    $$('.checkout-cart-index .col1-layout').each(function(el) {
        el.removeClassName('col1-layout').addClassName('col2-right-layout');
        el.insert({bottom:$$('.sidebar')[0]});
    });

    var bca = $$('.breadcrumbs a'), prodName = $$('.product-main-info .product-name');
    if (bca.length==3 && bca[1].parentNode.className.match(/^category/) && prodName.length) {
        Element.insert(prodName[0], {top:'<a href="'+bca[2].href+'" class="category-back-link">&laquo; Back to '+bca[2].innerHTML+'</a>'});
    }

    /* Disable Select */
    document.ondragstart = function() {return false;}
    document.onselectstart = function() {return false;}

    //
    var contentVideoLink=$$('.catalog-product-view .video-link');
    if (contentVideoLink.length && contentVideoLink.up(0)!='.video-icon') {
        try {
            var li = contentVideoLink[0].wrap('<li class="video-icon"></li>');
        } catch (e) {
            var li = contentVideoLink[0].wrap('li', {'class':"video-icon"});
        }
        if (pdfList.length) {
            $(pdfList[0]).insert({bottom:li});
        } else {
            var ul = li.wrap('<ul class="pdf-list"></ul>');
            $(main[0]).insert({top:ul});
        }
    }
});

function FancySlider(sliderId, options) {

    Element.insert(document.body, {bottom:'<div id="'+sliderId+'-modal" style="position:relative; display:none">'+
        '<div id="'+sliderId+'-overlay" class="slider-overlay" onclick="'+options.jsId+'.stop()">'+
        '</div>'+
        '<div id="'+sliderId+'-container" class="slider-container">'+
        	'<span class="modal-close" style="display:block; position:relative; width:100%;"><img src="' + closebtn + '" alt="Close" onclick="'+options.jsId+'.stop()" style="position:absolute; right:-28px; top:-13px;"/></span>'+
	            '<div class="slider-content">'+
	                '<div id="'+sliderId+'-content" class="fancy-slider" style="width:100%; height:100%;">'+
	                    '<div class="gallery"></div>'+
	                    '<div class="control pause" style="position:absolute;"></div>'+
	                    '<div class="footing"><div class="contents"><div class="bg"></div><div class="text"></div></div></div>'+
	                '</div>'+
	            '</div>'+
        '</div>'
    });

    var trigger = sliderId && $(sliderId), slider = $(sliderId+'-content'),
        gallery = slider.down('.gallery'), control = slider.down('.control'),
        footing = slider.down('.footing'),
        curItem = 0, numItems = options.data.items.length, timer, paused = false;

    function show() {
        curItem = 0;

        $(sliderId+'-modal').setStyle({display:'block'});
        $(sliderId+'-content').setStyle({display:'none'});
        footing && footing.setStyle({top:options.height+'px'});
        gallery.setStyle({left:0});
        //return;

        var v = document.viewport.getDimensions(), l = (v.width-options.width)/2, t = (v.height-options.height)/2;
        $(sliderId+'-container').setStyle({left:(v.width/2)+'px', top:(v.height/2)+'px', width:0, height:0});
        new Effect.Opacity(sliderId+'-overlay', {duration:.2, from:0, to:.4});
        new Effect.Morph(sliderId+'-container', {duration:.2, style:{left:l+'px', top:t+'px', width:options.width+'px', height:options.height+'px'}, afterFinish: function() {
            $(sliderId+'-content').setStyle({display:'block'});
        }});
    }

    function start() {
        timedMove();
    }

    function stop() {
        clearTimeout(timer);
        var v = document.viewport.getDimensions();

        $(sliderId+'-content').setStyle({display:'none'});
        new Effect.Opacity(sliderId+'-overlay', {duration:.4, from:.4, to:0, afterFinish:function() {
            $(sliderId+'-modal').setStyle({display:'none'});
        }});
        new Effect.Morph(sliderId+'-container', {duration:.4, style:{left:(v.width/2)+'px', top:(v.height/2)+'px', width:'10px', height:'10px'}});
    }

    // curItem is gallery shift, realCurItem is index in items collection
    function realCurItem() {
        return (curItem<1 ? 0 : (curItem>=numItems+1 ? 0 : curItem-1));
    }

    function move() {
        footing && new Effect.Move(footing, {y:options.height, mode:'absolute', duration:.3, afterFinish:function() {
            if ((text = options.data.items[realCurItem()].footing)) {
                footing.down('.text').update(text);
                var footingHeight = footing.down('.text').getHeight();
                footing.setStyle({height:footingHeight+'px'});
                new Effect.Move(footing, {y:options.height-footing.getHeight(), mode:'absolute', duration:.3});
            }
        }});
        new Effect.Move(gallery, {x:-options.width*curItem, mode:'absolute', duration:.6, afterFinish:function() {
            curItem = realCurItem()+1;
            gallery.setStyle({left:-options.width*curItem+'px'});
        }});
    }

    function timedMove() {
        control && control.setStyle({display:'block'});
        curItem++;
        move();
        timer = setTimeout(function() { timedMove() } , options.autoslide*1000);
    }

    trigger && trigger.insert('<a href="#" onclick="'+options.jsId+'.show(); return false"><img src="'+options.data.small_cover+'"/></a>');

    gallery.setStyle({width:options.width*(2+numItems)+'px', height:options.height, left:-options.width+'px'});
    var htmlArr = ['<div class="frame" style="width:'+options.width+'px"><a href="javascript:'+options.jsId+'.start()"><img src="'+options.data.cover+'" width="650" height="430" alt=""/></a></div>'];
    for (var i=0; i<numItems; i++) {
        htmlArr.push('<div class="frame" style="width:'+options.width+'px"><img src="'+options.data.items[i].img+'" width="650" height="430" alt=""/></div>');
    }
    htmlArr.push('<div class="frame" style="width:'+options.width+'px"><img src="'+options.data.items[0].img+'" width="650" height="430" alt=""/></div>');
    gallery.update(htmlArr.join(""));

    footing && footing.setStyle({top:options.height+'px'});
    //move();

    control && control.observe('click', function(ev) {
        if (!paused) {
            clearTimeout(timer); control.removeClassName('pause').addClassName('play');
            paused = true;
        } else {
            timedMove(); control.removeClassName('play').addClassName('pause');
            paused = false;
        }
    });

    return {
        show: show,
        start: start,
        stop: stop
    };
}

function BannerSlider(slider, options) {
    var slider = $(slider), frames = slider.select('.slide'), nav = slider.down('.slide-nav'), curSlide = 0, timer;
    slider.select('.slide').each(function(el) {
        el.setStyle({display:'none', opacity:0});
    });
    slider.down('.slide', 0).setStyle({display:'block', opacity:1});
    function move(newSlide, schedule) {
        if (curSlide==newSlide) {
            if (schedule) scheduleNext();
            return;
        }
        nav.down('a', curSlide).removeClassName('active');
        nav.down('a', newSlide).addClassName('active');
        var curSlideEl = slider.down('.slide', curSlide), newSlideEl = slider.down('.slide', newSlide);
        new Effect.Opacity(curSlideEl, {duration:.5, from:1, to:0, afterFinish:function() {
            curSlideEl.setStyle({display:'none'});
        }});
        newSlideEl.setStyle({display:'block'});
        new Effect.Opacity(newSlideEl, {duration:.5, from:0, to:1, afterFinish:function() {
            curSlide = newSlide;
            if (schedule) scheduleNext();
        }});
    }
    function scheduleNext() {
        clearTimeout(timer);
        timer = setTimeout(function() { move((curSlide+1)%frames.length, true); }, options.delay||3500);
    }
    var navHtml = '';
    for (var i=0; i<frames.length; i++) {
        if (i) frames[i].setStyle({opacity:0});
        navHtml += '<a href="javascript:'+options.jsId+'.move('+i+')"'+(!i?' class="active"':'')+'>&bull;</a> ';
    }
    nav.insert({bottom:navHtml});

    slider.observe('mouseover', function(ev) { clearTimeout(timer); });
    slider.observe('mouseout', function(ev) { scheduleNext() });

    scheduleNext();

    return {move:move};
}

function TabSwitch(el) {
    el = $(el);
    var curTab, curPane, tabs = el.select('ul.block-tabs li'), panes = {};
    tabs.each(function(tab) {
        tab = $(tab);
        var a = tab.select('a')[0], tabId = a.href.replace(/^.*#/,''), pane = $(tabId);
        if (!pane) return;
        if (tab.hasClassName('active')) {
            curTab = tab;
            curPane = pane;
        } else {
            pane.setStyle({display:'none'});
        }
        a.observe('click', function(ev) {
            if (tab===curTab) return;
            curTab.removeClassName('active');
            curPane.setStyle({display:'none'});
            curTab = tab;
            curPane = pane;
            tab.addClassName('active');
            pane.setStyle({display:'block'});
            ev.stop();
        });
    });
}

/* Disable Right Click */
Event.observe(window, 'contextmenu', function(event) {
    if (event.element().tagName.match(/^input|select|textarea$/i)) {
        return;
    }
    event.stop();
});

/* Slider Carousel */
var MDSlider = Class.create({
    initialize: function(options) {
        this.options = {
            moveDuration: .5,
            moveStep: 1,
            prevClass: 'arrow-left',
            nextClass: 'arrow-right',
            startPosition: 0,
            cycle: 'none',
            cycleDuration: 10,
            isListItemContainer: false
        }
        Object.extend(this.options, options)
        if (!$(this.options.containerId)) return;
        if (this.options.container && $(this.options.container)) {
            this.container = $(this.options.container)
        } else {
            this.container = $(this.options.containerId)
        }
        if (this.options.itemContainer && $(this.options.itemContainer)) {
            this.itemContainer = $(this.options.itemContainer)
        } else if (this.options.itemContainerId && $(this.options.itemContainerId)) {
            this.itemContainer = $(this.options.itemContainerId)
        } else if (this.options.itemContainerClass 
            && (this.itemContainer = this.container.select('.'+this.options.itemContainerClass)) 
            && this.itemContainer.size()>0
        ) { 
            this.itemContainer = this.itemContainer[0]
        } else {
            this.itemContainer = this.container
        }
        if (this.options.itemClass) {
            this.items = this.itemContainer.childElements().findAll((function(el){return el.hasClassName(this.options.itemClass)}).bind(this))
        } else {
            this.items = this.itemContainer.childElements()
        }
        this.itemCnt = this.items.size()
        if (this.itemCnt==0) return
        if (this.options.navigationContainer && $(this.options.navigationContainer)) {
            this.navigationContainer = $(this.options.navigationContainer)
        }
        if (this.options.navigationItems && this.options.navigationItems.length>0) {
            this.navigationItems = this.options.navigationItems
        } else if (this.navigationContainer) {
            if (this.navigationContainer.childElements().size()>0) {
                this.navigationItems = this.navigationContainer.childElements()
            } else {
                this.navigationItems = []
                if (this.options.isListItemContainer && this.itemCnt>0) {
                    this.navigationContainer.insert('<ul class="bulls"></ul>')
                    this.navigationContainer = this.navigationContainer.childElements().last()
                }
                for (i=0; i<this.itemCnt; i++) {
                    if (this.options.isListItemContainer) {
                        navItemHtml = '<li><a href="javascript:void(0);">&bull;</a></li>'
                    } else {
                        navItemHtml = '<a href="javascript:void(0);">&bull;</a>'
                    }
                    this.navigationContainer.insert({bottom: navItemHtml})
                    this.navigationItems.push(this.navigationContainer.childElements().last())
                }
            }
        }
        if (this.navigationItems && this.navigationItems.length>0) {
            for (i=0; i<this.navigationItems.length; i++) {
                this.navigationItems[i].observe('click', this.onMoveByIdx.bindAsEventListener(this, i))
            }
        }
        this.moveWidth = this.options.moveWidth || this.items[0].getDimensions().width
        this.currentIdx = 0
        try {
            this.prevBtn = $(this.options.prevBtnId) || this.container.select('.'+this.options.prevClass)[0]
            this.prevBtn.observe('click', this.onMovePrev.bindAsEventListener(this))
        } catch (e) {}
        try {
            this.nextBtn = $(this.options.nextBtnId) || this.container.select('.'+this.options.nextClass)[0]
            this.nextBtn.observe('click', this.onMoveNext.bindAsEventListener(this))
        } catch (e) {}
        this.moveLock = false
        if (this.options.startPosition>1 && this.options.startPosition<=this.itemCnt) this.moveByIdx(this.options.startPosition-1, true)
        this.startCycle()
        this.processPrevNextState()
    },
    startCycle: function() {
        this.stopCycle()
        if (-1 != ['left','right'].indexOf(this.options.cycle) && this.options.cycleDuration>0) {
            if (this.options.cycle == 'left') {
                this.cycleLoop = new PeriodicalExecuter(this.movePrev.bind(this, false), this.options.cycleDuration)
            } else if (this.options.cycle == 'right') {
                this.cycleLoop = new PeriodicalExecuter(this.moveNext.bind(this, false), this.options.cycleDuration)
            }
        }
    },
    stopCycle: function() {
        try {
            this.cycleLoop.stop()
        } catch (e) {}
    },
    processPrevNextState: function() {
        try {
            if (this.currentIdx==0) this.prevBtn.addClassName('inactive') 
            else this.prevBtn.removeClassName('inactive')
        } catch (e) {}
        try {
            if (this.currentIdx+this.options.moveStep>=this.itemCnt) this.nextBtn.addClassName('inactive') 
            else this.nextBtn.removeClassName('inactive')
        } catch (e) {}
        try {
            this.navigationItems.invoke('removeClassName', 'active')
            this.navigationItems[this.currentIdx].addClassName('active')
        } catch (e) {}
    },
    onMovePrev: function(e) {
        this.stopCycle()
        this.movePrev(false)
    },
    movePrev: function (instant) {
        if (this.moveLock) return
        if (this.currentIdx-this.options.moveStep>=0) {
            this.moveLock = true
            this.currentIdx -= this.options.moveStep
            if (instant) {
                new Effect.Move(this.itemContainer, {x:this.moveWidth*this.options.moveStep, duration: 0, afterFinish: this.clearMoveLock.bind(this)})
            } else {
                new Effect.Move(this.itemContainer, {x:this.moveWidth*this.options.moveStep, duration: this.options.moveDuration, afterFinish: this.clearMoveLock.bind(this)})
            }
            this.processPrevNextState()
        } else if (this.options.cycle=='left') {
            this.moveByIdx(this.itemCnt-1)
        }
    },
    onMoveNext: function(e) {
        this.stopCycle()
        this.moveNext(false)
    },
    moveNext: function (instant) {
        if (this.moveLock) return
        if (this.currentIdx+this.options.moveStep<this.itemCnt) {
            this.moveLock = true
            this.currentIdx += this.options.moveStep
            if (instant) {
                new Effect.Move(this.itemContainer, {x:-1*this.moveWidth*this.options.moveStep, duration: 0, afterFinish: this.clearMoveLock.bind(this)})
            } else {
                new Effect.Move(this.itemContainer, {x:-1*this.moveWidth*this.options.moveStep, duration: this.options.moveDuration, afterFinish: this.clearMoveLock.bind(this)})
            }
            this.processPrevNextState()
        } else if (this.options.cycle=='right') {
            this.moveByIdx(0)
        }
    },
    onMoveByIdx: function (e, idx) {
        this.stopCycle()
        this.moveByIdx(idx, false)
    },
    moveByIdx: function (idx, instant) {
        if (this.moveLock || idx<0 || idx>=this.itemCnt || this.currentIdx == idx) return
        this.moveLock = true
        if (instant) {
            new Effect.Move(this.itemContainer, {x:-1*this.moveWidth*(idx-this.currentIdx), duration: 0, afterFinish: this.clearMoveLock.bind(this)})
        } else {
            new Effect.Move(this.itemContainer, {x:-1*this.moveWidth*(idx-this.currentIdx), duration: this.options.moveDuration, afterFinish: this.clearMoveLock.bind(this)})
        }
        this.currentIdx = idx
        this.processPrevNextState()
    },
    clearMoveLock: function() {
        this.moveLock = false
        this.startCycle()
    }
})


