jQuery(document).ready(function($) {
    $('.expandable').map(function() {
        var a = $(this);
        var content = a.parent().next('.content');
        if (a.hasClass('closed')) {
            content.css({display:'none'});
        }
        a.click(function(e) {
            e.preventDefault();
            if (a.hasClass('closed')) { content.slideDown(100); a.removeClass('closed'); }
            else { content.slideUp(100); a.addClass('closed'); }
        });
    });
});



/* Foodzie Gallery Slider used in Taste Club Product page */

var FoodzieGallerySlider = Class.create({
    initialize: function(options) {
        this.thumbMoveStep = options.thumbMoveStep;
        this.thumbPageDelta = options.thumbPageDelta;
        this.useTMDFlag = options.useTMDFlag;
        this.itemMoveStep = options.itemMoveStep;
        this.skipThumbCnt = options.skipThumbCnt;
        this.visibleThumbCnt = options.visibleThumbCnt;
        this.stopOnVideo = options.stopOnVideo;
        this.stopOnPlayingVideo = options.stopOnPlayingVideo;
        this.stopPlayingVideoAfterSwitchDelay = options.stopPlayingVideoAfterSwitchDelay;
        this.loopDelay = options.loopDelay;
        this.moLoopDelay = options.moLoopDelay;
        this.captionVisibleFor = options.captionVisibleFor;
        this.captionShowDelay = options.captionShowDelay;
        this.captionHideDelay = options.captionHideDelay;
        this.moveDelay = options.moveDelay;
        this.itemsCnt = $$('#product-img-container-id .product-img-box-container .product-img-box').size();
        this.currentIdx = 0;
        this.leftIdx = 0;
        this.thumbMoveDelta = Array(2)
        this.thumbMoveDelta[0] = 0.0
        this.thumbMoveDelta[1] = 0.0
        this.thumbContainer = $$('#product-img-container-id .horiz-slider .thumbs ol')[0];
        this.itemContainer  = $$('#product-img-container-id .product-img-box-container')[0];
        this.itemList       = this.itemContainer.select('.product-img-box');
        this.itemList.each(this.initItem.bind(this));
        this.stateArrow     = $$('#product-img-container-id .product-img-box-wrapper .state-arrow')[0];
        this.thumbList      = this.thumbContainer.select('li');
        this.thumbList.each(this.initThumbItem.bind(this));
        $$('#product-img-container-id .horiz-slider .slide-left')[0].observe('click', this.slideLeftClick.bindAsEventListener(this));
        $$('#product-img-container-id .horiz-slider .slide-right')[0].observe('click', this.slideRightClick.bindAsEventListener(this));
        this.moLoopExec = Array(this.itemsCnt)
        this.hcLoopExec = Array(this.itemsCnt)
        this.pvLoopExec = Array(this.itemsCnt)
        this.scEffect = Array(this.itemsCnt)
        this.itemClicked = Array(this.itemsCnt)
        this.startLoopExec()
        new PeriodicalExecuter(this.checkPlayingVideo.bind(this), 0.5)
        this.processPrevNextState()
    },
    processPrevNextState: function() {
        if (this.leftIdx==0) {
            $$('#product-img-container-id .horiz-slider .slide-left')[0].addClassName('inactive') 
        } else {
            $$('#product-img-container-id .horiz-slider .slide-left')[0].removeClassName('inactive')
        }
        if (this.leftIdx+this.visibleThumbCnt>this.itemsCnt || this.itemsCnt<6 ) {
            $$('#product-img-container-id .horiz-slider .slide-right')[0].addClassName('inactive') 
        } else {
            $$('#product-img-container-id .horiz-slider .slide-right')[0].removeClassName('inactive')
        }
    },
    checkPlayingVideo: function() {
        if (!this.itemList[this.currentIdx].hasClassName('video')) return;
        try {
            var obj
            obj = this.itemList[this.currentIdx].select('object')
            if (0<obj[0].getPlayerState() && obj[0].getPlayerState()<5 && this.stopOnPlayingVideo) {
                this.stopLoopExec()
            }
        } catch(e) {}
        try {
            obj = this.itemList[this.currentIdx].select('embed')
            if (0<obj[0].getPlayerState() && obj[0].getPlayerState()<5 && this.stopOnPlayingVideo) {
                this.stopLoopExec()
            }
        } catch(e) {}
    },
    pausePlayingVideo: function(idx) {
        if (!this.itemList[idx].hasClassName('video') || idx==this.currentIdx) {
            this.stopPVLoopExec(idx)
            return;
        }
        try {
            var obj
            obj = this.itemList[idx].select('object')
            obj[0].pauseVideo()
        } catch(e) {}
        try {
            obj = this.itemList[idx].select('embed')
            obj[0].pauseVideo()
        } catch(e) {}
        this.stopPVLoopExec(idx)
    },
    stopPVLoopExec: function(idx) {
        try {
            this.pvLoopExec[idx].stop();
        } catch (e) {}
    },
    startPVLoopExec: function(idx) {
        this.stopLoopExec(idx)
        if (this.stopPlayingVideoAfterSwitchDelay>0) {
            this.pvLoopExec[idx] = new PeriodicalExecuter(this.pausePlayingVideo.bind(this, idx), this.stopPlayingVideoAfterSwitchDelay)
        }
    },
    initItem: function(el, idx) {
        el.gsIdx = idx;
        this.hideCaption(el)
        el.observe('mouseover', this.itemMO.bindAsEventListener(this))
        el.observe('mouseout', this.itemMT.bindAsEventListener(this))
        el.observe('click', this.itemClick.bindAsEventListener(this))
    },
    initThumbItem: function(el, idx) {
        el.gsIdx = idx;
        el.observe('mouseover', this.thumbItemMO.bindAsEventListener(this))
        el.observe('mouseout', this.thumbItemMT.bindAsEventListener(this))
        el.observe('click', this.thumbItemClick.bindAsEventListener(this))
    },
    now: function() {
        return (new Date).getTime();
    },
    stopLoopExec: function() {
        try {
        this.loopExec.stop();
        } catch (e) {}
    },
    startLoopExec: function() {
        this.stopLoopExec()
        if (this.loopDelay != 0 && (!this.stopOnVideo || !this.itemList[this.currentIdx].hasClassName('video'))) {
            this.loopExec = new PeriodicalExecuter(this.moveRight.bind(this), this.loopDelay)
        }
    },
    stopMOLoopExec: function(el) {
        try {
            this.moLoopExec[el.gsIdx].stop();
        } catch (e) {}
    },
    startMOLoopExec: function(el) {
        this.stopMOLoopExec(el)
        this.moLoopExec[el.gsIdx] = new PeriodicalExecuter(this.thumbItemPosition.bind(this, el, null), this.moLoopDelay)
    },
    stopHCLoopExec: function(el) {
        try {
            this.hcLoopExec[el.gsIdx].stop();
        } catch (e) {}
    },
    startHCLoopExec: function(el) {
        this.stopHCLoopExec(el)
        this.hcLoopExec[el.gsIdx] = new PeriodicalExecuter(this.hideCaption.bind(this, el), this.captionVisibleFor+this.captionShowDelay)
    },
    getIdxPage: function(idx) {
        return Math.ceil((idx+1)/this.skipThumbCnt);
    },
    moveRight: function() {
        var itemIdx = (this.currentIdx>=this.itemsCnt-1) ? 0 : this.currentIdx+1
        if (itemIdx>=this.leftIdx+this.visibleThumbCnt) {
            var skipCount = this.getIdxPage(itemIdx)-this.getIdxPage(this.leftIdx)
            this.thumbItemPosition(this.thumbList[itemIdx], this.skipLeft.bind(this, skipCount))
        } else if (itemIdx<this.leftIdx) {
            var skipCount = this.getIdxPage(this.leftIdx)-this.getIdxPage(itemIdx)
            this.thumbItemPosition(this.thumbList[itemIdx], this.skipRight.bind(this, skipCount))
        } else {
            this.thumbItemPosition(this.thumbList[itemIdx], null)
        }
    },
    thumbItemMO: function(e) {
        var el = e.findElement('li');
        if (el.gsIdx == this.currentIdx) this.showCurrentCaption();
        this.startMOLoopExec(el)
        this.stopLoopExec();
    },
    thumbItemMT: function(e) {
        var el = e.findElement('li');
        if (el.gsIdx == this.currentIdx) this.hideCurrentCaption();
        this.stopMOLoopExec(el)
        this.startLoopExec();
    },
    thumbItemClick: function(e) {
        var el = e.findElement('li');
        this.stopMOLoopExec(el);
        this.thumbItemPosition(el, null);
    },
    showCurrentCaption: function() {
        this.showCaption(this.itemList[this.currentIdx])
    },
    itemMO: function(e) {
        var el = e.findElement('.product-img-box');
        if (this.scEffect[el.gsIdx] && this.scEffect[el.gsIdx].state=='running') return;
        if (this.hcLoopExec[el.gsIdx] && this.hcLoopExec[el.gsIdx].timer) return;
        if (el.gsIdx == this.currentIdx) this.showCurrentCaption();
        this.stopLoopExec();
    },
    itemMT: function(e) {
        var el = e.findElement('.product-img-box');
        if (this.within(el, Event.pointerX(e), Event.pointerY(e))) return;
        if (el.gsIdx == this.currentIdx) this.hideCurrentCaption();
        this.startLoopExec();
    },
    itemClick: function(e) {
        var el = e.findElement('.product-img-box');
        this.itemClicked[this.currentIdx] = true
    },
    within: function(el, x, y) {
        var co = el.cumulativeOffset()
        var dim = el.getDimensions()
        if (x<co[0] || y<co[1]) return false
        if (x>co[0]+dim.width || y>co[1]+dim.height) return false
        return true
    },
    showCaption: function(el) {
        try {
            var caption = el.select('.caption')[0]
            if (caption.getStyle('opacity') == 1) return;
            this.startHCLoopExec(el)
            this.scEffect[el.gsIdx] = new Effect.Opacity(caption, { from: 0, to: 1, duration: this.captionShowDelay});
        } catch (e) {}
    },
    hideCurrentCaption: function() {
        this.hideCaption(this.itemList[this.currentIdx])
    },
    hideCaption: function(el) {
        this.stopHCLoopExec(el)
        try {
            var caption = el.select('.caption')[0]
            try {
                this.scEffect[el.gsIdx].cancel();
            } catch (e) {}
            if (caption.getStyle('opacity') == 0) return;
            new Effect.Opacity(caption, { from: 1, to: 0, duration: this.captionHideDelay});
        } catch (e) {}
    },
    thumbItemPosition: function(el, afterFinishCb) {
        if (el.gsIdx == this.currentIdx || this.moving) return;
        this.moving = true;
        this.stopLoopExec();
        afterFinishCb = afterFinishCb || this.startLoopExec.bind(this)
        var arrowMove = this.getThumbMove(1, el.gsIdx-this.currentIdx)
        var itemMove  = -1*(el.gsIdx-this.currentIdx)*this.itemMoveStep
        this.itemClicked[this.currentIdx] = false
        this.startPVLoopExec(this.currentIdx)
        this.thumbList[this.currentIdx].select('img')[0].removeClassName('active')
        this.currentIdx = el.gsIdx
        this.itemClicked[this.currentIdx] = true
        this.thumbList[this.currentIdx].select('img')[0].addClassName('active')
        this.showCurrentCaption();
        new Effect.Parallel([
            new Effect.Move(this.stateArrow, {x:arrowMove, sync: true}),
            new Effect.Move(this.itemContainer, {x:itemMove, sync: true})
        ], {duration: this.moveDelay, afterFinish: this.decreaseMoving.bind(this, afterFinishCb)})
    },
    decreaseMoving: function(afterFinishCb) {
        this.moving = false;
        if (!!afterFinishCb) afterFinishCb()
    },
    addThumbMoveDelta: function(type, delta) {
        if (!this.useTMDFlag) return 0
        this.thumbMoveDelta[type] = this.thumbMoveDelta[type]+delta
    },
    useThumbMoveDelta: function(type) {
        if (!this.useTMDFlag) return 0
        var useTMD = this.thumbMoveDelta[type]>0 ? Math.floor(this.thumbMoveDelta[type]) : Math.ceil(this.thumbMoveDelta[type]);
        this.thumbMoveDelta[type] -= useTMD
        return useTMD
    },
    getThumbMove: function(type, skipCnt) {
        var thumbMove = skipCnt*this.thumbMoveStep
	thumbMove += this.thumbPageDelta*(skipCnt>0 ? Math.floor(skipCnt/this.skipThumbCnt) : Math.ceil(skipCnt/this.skipThumbCnt))
        this.addThumbMoveDelta(type, skipCnt/2)
        thumbMove = thumbMove + this.useThumbMoveDelta(type)
        return thumbMove
    },
    slideLeftClick: function(e) {
        this.skipRight(1);
    },
    skipRight: function(count) {
        if (this.leftIdx-this.skipThumbCnt<0 || this.moving) return;
        this.moving = true;
        var countLeft = this.getIdxPage(this.leftIdx)
        count = Math.min(count, countLeft)
        var skipThumbCnt = this.skipThumbCnt*count
        var thumbMove = this.getThumbMove(0, skipThumbCnt)
        var arrowMove = this.getThumbMove(1, skipThumbCnt)
        this.stopLoopExec();
        var afterFinishCb = this.startLoopExec.bind(this)
        new Effect.Parallel([
            new Effect.Move(this.thumbContainer, {x:thumbMove, sync: true}),
            new Effect.Move(this.stateArrow, {x:arrowMove, sync: true})
        ], {duration: this.moveDelay, afterFinish: this.decreaseMoving.bind(this, afterFinishCb)})
        this.leftIdx -= skipThumbCnt;
        this.processPrevNextState()
    },
    slideRightClick: function(e) {
        this.skipLeft(1);
    },
    skipLeft: function(count) {
        if (this.leftIdx+this.skipThumbCnt>=this.itemsCnt || this.moving) return;
        this.moving = true;
        var countLeft = this.getIdxPage(this.itemsCnt-1)-this.getIdxPage(this.leftIdx)
        count = Math.min(count, countLeft)
        var skipThumbCnt = this.skipThumbCnt*count
        var thumbMove = this.getThumbMove(0, -1*skipThumbCnt)
        var arrowMove = this.getThumbMove(1, -1*skipThumbCnt)
        this.stopLoopExec();
        var afterFinishCb = this.startLoopExec.bind(this)
        new Effect.Parallel([
            new Effect.Move(this.thumbContainer, {x:thumbMove, sync: true}),
            new Effect.Move(this.stateArrow, {x:arrowMove, sync: true})
        ], {duration: this.moveDelay, afterFinish: this.decreaseMoving.bind(this, afterFinishCb)})
        this.leftIdx = this.leftIdx + skipThumbCnt;
        this.processPrevNextState()
    }
});



/* Foodzie Countdown used in Taste Club pages */

var FoodzieCountdown = Class.create({
    initialize: function(options) {
        this.dayValue = 24*60*60*1000
        this.hourValue = 60*60*1000
        this.minuteValue = 60*1000
        this.secondValue = 1000
        if (!options.containers) return;
	this.dayLabel = options.dayLabel || 'Days'
        this.hourLabel = options.hourLabel ||  'Hrs'
        this.minuteLabel = options.minuteLabel ||  'Min'
        this.secondLabel = options.secondLabel ||  'sec'
        var container, targetTime, tDate;
        this.containers = [];
        for (i=0; i<options.containers.length; i++) {
            if ((container = $(options.containers[i].id)) && (targetTime = Date.parse(options.containers[i].targetDate))) {
                tDate = new Date()
                targetTime = targetTime-tDate.getTimezoneOffset()*60*1000
                tDate.setTime(targetTime)
                this.containers.push({containerId: options.containers[i].id, targetDate: tDate})
            }
        }
        for (i=0; i<this.containers.length; i++) {
            this.containers[i].loopExec = new PeriodicalExecuter(this.updateCountdown.bind(this,this.containers[i]), 1)
        }
    },
    updateCountdown: function(container) {
        var timeLeft = container.targetDate.getTime()-(new Date()).getTime()
        var hourLeft, minuteLeft, secondLeft
        if (timeLeft<=0) {
            hourLeft = minuteLeft = secondLeft = new String(0)
        } else {
            dayLeft    = Math.floor(timeLeft/this.dayValue)
            if (dayLeft>=4) timeLeft  -= dayLeft*this.dayValue
            else dayLeft = 0
            hourLeft   = Math.floor(timeLeft/this.hourValue)
            timeLeft  -= hourLeft*this.hourValue
            minuteLeft = Math.floor(timeLeft/this.minuteValue)
            timeLeft  -= minuteLeft*this.minuteValue
            secondLeft = Math.floor(timeLeft/this.secondValue)
        }
        var dayContainer, dayLabelContainer
        var hourContainer = $$('#'+container.containerId+' .hour')
        var minuteContainer = $$('#'+container.containerId+' .minute')
        var secondContainer = $$('#'+container.containerId+' .second')
        var hourLabelContainer = $$('#'+container.containerId+' .hour_label')
        var minuteLabelContainer = $$('#'+container.containerId+' .minute_label')
        var secondLabelContainer = $$('#'+container.containerId+' .second_label')
        if (dayLeft>0) {
            dayContainer    = hourContainer
            hourContainer   = minuteContainer
            minuteContainer = secondContainer
            secondContainer = null
            dayLabelContainer    = hourLabelContainer
            hourLabelContainer   = minuteLabelContainer
            minuteLabelContainer = secondLabelContainer
            secondLabelContainer = null
        }
        if (dayContainer && dayContainer[0]) {
            dayContainer[0].update(dayLeft<10 ? '0'+dayLeft : dayLeft)
        }
        if (hourContainer && hourContainer[0]) {
            hourContainer[0].update(hourLeft<10 ? '0'+hourLeft : hourLeft)
        }
        if (minuteContainer && minuteContainer[0]) {
            minuteContainer[0].update(minuteLeft<10 ? '0'+minuteLeft : minuteLeft)
        }
        if (secondContainer && secondContainer[0]) {
            secondContainer[0].update(secondLeft<10 ? '0'+secondLeft : secondLeft)
        }
        if (dayLabelContainer && dayLabelContainer[0]) {
            dayLabelContainer[0].update(this.dayLabel)
        }
        if (hourLabelContainer && hourLabelContainer[0]) {
            hourLabelContainer[0].update(this.hourLabel)
        }
        if (minuteLabelContainer && minuteLabelContainer[0]) {
            minuteLabelContainer[0].update(this.minuteLabel)
        }
        if (secondLabelContainer && secondLabelContainer[0]) {
            secondLabelContainer[0].update(this.secondLabel)
        }
    }
})

var FoodzieShowcaseSlider = function() {
    var currentIdx = 0
    var itemCnt = $('details-wrapper').childElements().findAll(function(el){return el.hasClassName('slide-content')}).size()
    var itemWidth = 640
    var moveLock = false
    var clearMoveLock = function() {moveLock=false}
    var buttons = $('details').childElements().find(function(el){return el.hasClassName('button-wrapper')}).select('span')
    buttons.each(function(el, idx){
	el.observe('click', function(e){
	    if (currentIdx==idx || moveLock) return
	    moveLock = true
	    new Effect.Move($('details-wrapper'), {x:(currentIdx-idx)*itemWidth, duration: .2, afterFinish: clearMoveLock})
	    buttons[currentIdx].removeClassName('active')
	    currentIdx = idx
	    buttons[currentIdx].addClassName('active')
	})
    })
}

var FoodzieProductsTableSlider = function() {
    var currentIdx = 0
    var cellCnt = $('products-grid-container').down('table').down('tr').childElements().size()
    var cellWidth = $('products-grid-container').down('table').down('tr').childElements()[0].getDimensions().width
    cellWidth = 187
    var moveLock = false
    var clearMoveLock = function() {moveLock=false}
    var processPrevNextState = function() {
        if (currentIdx==0) {
            $('products-grid-prev').addClassName('inactive') 
        } else {
            $('products-grid-prev').removeClassName('inactive')
        }
        if (currentIdx+3>=cellCnt) {
            $('products-grid-next').addClassName('inactive') 
        } else {
            $('products-grid-next').removeClassName('inactive')
        }
    }
    processPrevNextState()
    $('products-grid-next').observe('click', function(e){
        if (moveLock) return
        if (currentIdx+3<cellCnt) {
            moveLock = true
            currentIdx += 3
            new Effect.Move($('products-grid-container').down('table'), {x:-1*cellWidth*3, duration: .5, afterFinish: clearMoveLock})
        }
        processPrevNextState()
    })
    $('products-grid-prev').observe('click', function(e){
        if (moveLock) return
        if (currentIdx-3>=0) {
            moveLock = true
            currentIdx -= 3
            new Effect.Move($('products-grid-container').down('table'), {x:cellWidth*3, duration: .5, afterFinish: clearMoveLock})
        }
        processPrevNextState()
    })
}



