/* doubleVision.js
 * Designed for use with the VDP dual photo carousels
 * adapted generously from the carousel.js file for New Model Launch
 * @requires Prototype.js >= 1.6, Script.aculo.us > 1.8.0
 */
var DoubleVision = Class.create({
    initialize: function(dealerBool, dealerDivider, stockBool, stockDivider, carId, dealerId, tipCopy, tipTitle, options) {
        this.options = {
            carouselDealer: 'photos-dealer',
            carouselStock: 'photos-stock',
            btnDealerLeft: 'photos-btn-dealer-left',
            btnDealerRight: 'photos-btn-dealer-right',
            btnStockLeft: 'photos-btn-stock-left',
            btnStockRight: 'photos-btn-stock-right',
            viewport: 'photos-viewport'
        }

        Object.extend(this.options, options || {});
        this.btnDealerLeft = this.options.btnDealerLeft;
        this.btnDealerRight = this.options.btnDealerRight;
        this.btnStockLeft = this.options.btnStockLeft;
        this.btnStockRight = this.options.btnStockRight;
        this.carouselDealer = this.options.carouselDealer;
        this.carouselStock = this.options.carouselStock;
        this.viewport = this.options.viewport;
        this.carId = carId;
        this.dealerId = dealerId;

        if (dealerBool) {
            var dvDealer = new VDPCarousel(this.carouselDealer, dealerDivider, this.viewport, {
                buttonLeft: this.btnDealerLeft,
                buttonRight: this.btnDealerRight,
                photoType: 'seller',
                carId: this.carId,
                dealerId: this.dealerId
            });
        }
        if (stockBool) {
            var dvStock = new VDPCarousel(this.carouselStock, stockDivider, this.viewport, {
                buttonLeft: this.btnStockLeft,
                buttonRight: this.btnStockRight,
                photoType: 'atc',
                carId: this.carId,
                dealerId: this.dealerId,
                tipCopy: tipCopy,
                tipTitle: tipTitle
            });
        }
        if (dealerBool || stockBool) {
            var dvViewer = new VDPCarouselViewer(this.viewport);
        }

        var mainLinkElem = $('main-image');
        var mainLinkHandler = this.mainLinkHandler.bindAsEventListener(this);
        if (mainLinkElem) {
            mainLinkElem.observe('click', mainLinkHandler);
        }
    },

    mainLinkHandler: function(e) {
        e.stop();
        var el = e.element();
        if (el.hasClassName('view-larger-photos')) {
            var suffix = $(this.viewport).down('a').getAttribute('rel');
            var url = './img_popup.html?' + suffix;
            new Popup({url: url, width: 650, height: 670});
        }
    }
});


var VDPCarousel = Class.create({
    initialize: function(id, divider, boundViewer, options) {
        this.options = {
            buttonLeft: 'leftbutton',
            buttonRight: 'rightbutton',
            photoType: '',
            carId: '',
            dealerId: '',
            tipCopy: '',
            tipTitle: ''
        }
        Object.extend(this.options, options || {});

        if (!$(id)) return false;
        this.carousel = $(id);
        this.buttonLeft = this.options.buttonLeft;
        this.buttonRight = this.options.buttonRight;
        this.slidebox = this.carousel.down("div.slidebox");
        this.carouselItems = $(this.carousel).select('div.photos-container');
        this.currentPage = 1;
        this.divider = divider;
        this.perPage = 1;
        this.numItems = this.carouselItems.length;
        this.numPages = Math.ceil(this.numItems / this.perPage);
        this.photoType = this.options.photoType;
        this.totalPhotos = this.slidebox.select('a img');
        this.totalCount = this.totalPhotos.length;
        this.viewer = $(boundViewer);
        this.carId = this.options.carId;
        this.dealerId = this.options.dealerId;
        this.tipCopy = this.options.tipCopy;
        this.tipTitle = this.options.tipTitle;

        this.addButtons();
        this.checkButtons();
        this.updatePagination();
        this.pageWidth = this.getPageWidth();
        var thumbnailHandler = this.thumbnailHandler.bindAsEventListener(this);
        this.slidebox.observe('click', thumbnailHandler);
    },

    addButtons: function() {
        if (this.numPages <= 1) {
            return;
        }
        /* Add the left & Right Buttons */
        var slideLeft = this.slideLeft.bind(this);
        var slideRight = this.slideRight.bind(this);
        var left = new Element("a", {'id': this.buttonLeft, 'class': 'button left'}).update('Prev');
        var right = new Element("a", {'id': this.buttonRight, 'class': 'button right'}).update('Next');
        left.observe('click', slideLeft);
        right.observe('click', slideRight);
        this.carousel.insert({top: right}).insert({top: left});
    },

    checkButtons: function() {
        if (this.numPages <= 1) {
            return;
        }
        this.currentPage == this.numPages ? $(this.buttonRight).className = 'button right off' : $(this.buttonRight).className = 'button right';
        this.currentPage == 1 ? $(this.buttonLeft).className = 'button left off' : $(this.buttonLeft).className = 'button left';
    },

    getPageWidth: function() {
        return (this.carouselItems[0].getWidth()) * this.perPage;
    },

    slideRight: function() {
        if (this.currentPage == this.numPages) {
            return;
        }
        this.currentPage++;
        this.slide(-this.pageWidth);
        this.updatePagination();
        this.throwAsisTag('dv_' + this.photoType + '_photo_vdp_click.asis?car_id=' + this.carId + '&dealer_id=' + this.dealerId + '&rdpage=DVNEXT');
    },

    slideLeft: function() {
        if (this.currentPage == 1) {
            return;
        }
        this.currentPage--;
        this.slide(this.pageWidth);
        this.updatePagination();
        this.throwAsisTag('dv_' + this.photoType + '_photo_vdp_click.asis?car_id=' + this.carId + '&dealer_id=' + this.dealerId + '&rdpage=DVPREV');
    },

    slide: function(distance) {
        var fadeIn = this.fadeIn.bind(this);
        var fadeOut = this.fadeOut.bind(this);
        new Effect.Move(this.slidebox, {x: distance,
            y: 0,
            mode: 'relative',
            delay: 0.3,
            duration: 0.6,
            fps: 50,
            afterFinish: fadeIn,
            beforeStart: fadeOut});
    },

    updatePagination: function() {
        this.currentPhotoStart = ((this.currentPage * this.divider) - (this.divider)) + 1;
        this.currentPhotoEnd = ((this.currentPage * this.divider) < this.totalCount) ? (this.currentPage * this.divider) : this.totalCount;
        var pagination = this.currentPhotoStart + '-' + this.currentPhotoEnd + ' of ' + this.totalCount;
        var thisCarousel = $(this.carousel.id + '-pagination');
        if (thisCarousel && this.currentPhotoEnd > 1) {
            thisCarousel.update(pagination);
        }
    },

    fadeOut: function() {
        new Effect.Opacity(this.slidebox, {from: 1.0, to: 0.5, duration: 0.3, fps: 50});
    },

    fadeIn: function() {
        this.checkButtons();
        new Effect.Opacity(this.slidebox, {from: 0.5, to: 1.0, duration: 0.3, fps: 50});
    },

    slideToPageHandler: function(e) {
        var el = e.element();
        if (el.hasClassName('page-indicator')) {
            var toPage = (el.identify().split("-")[1]) * 1;
            if (toPage != this.currentPage) this.slideToPage(toPage);
        }
    },

    slideToPage: function(pageNumber) {
        var distance = (-(pageNumber - this.currentPage)) * this.pageWidth;
        this.currentPage = pageNumber;
        this.slide(distance);
    },

    thumbnailHandler: function(e) {
        e.stop();
        var el = e.element();
        if (el.tagName.toLowerCase() == "a" && el.down('img')) {
            this.updatePhoto(el);
            this.makeSelected(el);
        }
    },

    updatePhoto: function(el) {
        var rel = el.getAttribute('rel');
        if (!rel) {
            return;
        }
        var newImage = el.down('.hidden');
        var clone = newImage.cloneNode(true);
        var link = new Element('a', {href: '/', rel: rel, alt: 'Click to enlarge this photo.'}).update(clone);
        if (rel.include('isStock=false')) {
            var borderColor = '#000';
        } else {
            var borderColor = '#959595';
        }
        link.setStyle({borderColor: borderColor});
        this.viewer.update(link);

        // This section is temporary, showing stock photo indicator until watermarks are in place
        var photoIndicatorId = 'photos-stock-indicator';
        var photoIndicatorElem = $(photoIndicatorId);
        var photoIndicatorTipId = 'stock-photo-tip';
        var photoIndicatorTip = $('stock-photo-tip');
        if (this.photoType == 'atc') {
            if (!photoIndicatorElem) {
                var stockIndicator = new Element('p', {
                    id: photoIndicatorId,
                    'class':'link-with-icon'
                });
                var stockTip = new Element('img', {
                    id: photoIndicatorTipId,
                    src: '/img/fyc/searchresults/icon-help-orange-trans.gif',
                    'class': 'help-icon'
                });
                stockIndicator.update('Stock Photo ').insert({bottom: stockTip});
                $('main-links').insert({top: stockIndicator});
                if (this.tipCopy) {
                    new Tip(photoIndicatorTipId, this.tipCopy, {title: this.tipTitle});
                }
            }
        } else if (this.photoType == 'seller') {
            if (photoIndicatorTip) {
                Tips.remove(photoIndicatorId);
                photoIndicatorElem.remove();
            }
        }
        //

        clone.removeClassName('hidden');
    },

    bindTip: function (tipId, tipContent, tipOptions) {
        if (!$(tipId)) return;

        new Tip(tipId, tipContent, tipOptions);
    },

    makeSelected: function(el) {
        var prevSelected = $('thumbs').down('.selected');
        if (prevSelected) {
            prevSelected.removeClassName('selected');
        }
        el.className = 'selected';
    },

    throwAsisTag: function(asis) {
        var seperator = asis.indexOf("?") != -1 ? "&" : "?";
        var cacheKillURI = "/no_cache/ac/" + asis + seperator + "cacheKill=" + new Date().getTime();
        var asisImg = new Image();
        asisImg.src = cacheKillURI;
    }

});

var VDPCarouselViewer = Class.create({
    initialize: function(boundViewer) {
        if (!$(boundViewer)) return false;
        this.viewer = $(boundViewer);

        var viewerHandler = this.viewerHandler.bindAsEventListener(this);
        this.viewer.observe('click', viewerHandler);
    },

    viewerHandler: function(e) {
        e.stop();
        var el = e.element();
        if (el.tagName.toLowerCase() == "a" || el.tagName.toLowerCase() == "img") {
            this.openPhotos(el);
        }
    },

    openPhotos: function(el) {
        var url = './img_popup.html?' + el.parentNode.getAttribute('rel');
        new Popup({url: url, width: 650, height: 670});
    }

})

var Popup = Class.create();
Popup.prototype = {
    initialize:function(options) {
        this.options = {
            url: '/',
            resizable: '1',
            width: 300,
            height: 300,
            location: 'no',
            menubar: 'no',
            status: 'no',
            titlebar: 'no',
            toolbar: 'no',
            scrollbars: 'no'
        }
        Object.extend(this.options, options || {});
        var t = (screen.height - this.options.height) / 2;
        var l = (screen.width - this.options.width) / 2;
        window.open(this.options.url, '', 'resizable=' + this.options.resizable + ',width=' + this.options.width + ',height=' + this.options.height + ",top=" + t + ",left=" + l + ",titlebar=" + this.options.titlebar + ",menubar=" + this.options.menubar + ",toolbar=" + this.options.toolbar + ",status=" + this.options.status + ",location=" + this.options.location + ",scrollbars=" + this.options.scrollbars);
    }
}
