// -----------------------------------------------------------------------------------
//	VideoBox by View 2008
//	Lightbox v2.04
//	by Lokesh Dhakar - http://www.lokeshdhakar.com
//
// -----------------------------------------------------------------------------------
/*

Table of Contents
-----------------
Configuration

Lightbox Class Declaration
- initialize()
- updateImageList()
- start()
- changeImage()
- resizeImageContainer()
- showImage()
- updateDetails()
- updateNav()
- enableKeyboardNav()
- disableKeyboardNav()
- keyboardAction()
- preloadNeighborImages()
- end()
    
Function Calls
- document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
VideoboxOptions = Object.extend({
    fileLoadingImage: '/_layouts/PMI/GCW/Images/loading-lightbox.gif',
    fileBottomNavCloseImage: '/_layouts/PMI/GCW/Images/close-lightbox.gif',

    overlayOpacity: 0.3,   // controls transparency of shadow overlay
    fadeDuration: 0.2, 	// controls the speed of the fade in seconds (10=slowest and 0=instant)

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable

    // When grouping images this is used to write: Image # of #.
    // Change it for non-english localization
    labelImage: "Image",
    labelOf: "of"
}, window.VideoboxOptions || {});

// -----------------------------------------------------------------------------------

var Videobox = Class.create();

Videobox.prototype = {
    imageArray: [],
    activeImage: undefined,

    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {

        this.updateImageList();

        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (VideoboxOptions.resizeSpeed > 10) VideoboxOptions.resizeSpeed = 10;
        if (VideoboxOptions.resizeSpeed < 1) VideoboxOptions.resizeSpeed = 1;

        this.resizeDuration = VideoboxOptions.animate ? ((11 - VideoboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = VideoboxOptions.animate ? VideoboxOptions.fadeDuration : 0;  // shadow fade in/out duration

        // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (VideoboxOptions.animate ? 250 : 1) + 'px';


        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="overlay"></div>
        //  <div id="lightbox">
        //      <div id="outerImageContainer">
        //          <div id="imageContainer">
        //              <img id="lightboxImage">
        //              <div style="" id="hoverNav">
        //                  <a href="#" id="prevLink"></a>
        //                  <a href="#" id="nextLink"></a>
        //              </div>
        //              <div id="loading">
        //                  <a href="#" id="loadingLink">
        //                      <img src="images/loading.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //      <div id="imageDataContainer">
        //          <div id="imageData">
        //              <div id="imageDetails">
        //                  <span id="caption"></span>
        //                  <span id="numberDisplay"></span>
        //              </div>
        //              <div id="bottomNav">
        //                  <a href="#" id="bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //  </div>


        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="VideoOverlay"></div>
        //  <div id="videobox">
        //		<div id="flash"></div>
        //	</div>

        var videoPath = "";
        var videoTitle = "";
        var objBody = $$('body')[0];
        objBody.appendChild(Builder.node('div', { id: 'VideoOverlay' }));
        objBody.appendChild(Builder.node('div', { id: 'videobox' }, [
			Builder.node('div', { id: 'flash' }),
			Builder.node('div', { id: 'videoDataContainer' }, [
					Builder.node('div', { id: 'videoDataHolder' }, [
					Builder.node('div', { id: 'videoData' }, [
                    Builder.node('div', { id: 'videoDetails' }, [
                        Builder.node('span', { id: 'videoCaption' }),
                        Builder.node('span', { id: 'numberDisplay' }),
						Builder.node('div', { id: 'bottomNavVideo' },
							Builder.node('a', { id: 'bottomNavVideoClose', href: 'javascript:Videobox.prototype.end();' },
								Builder.node('img', { src: VideoboxOptions.fileBottomNavCloseImage })
								)
							)
                    ]),
        //Builder.node('div',{id:'bottomNav'},
        //Builder.node('a',{id:'bottomNavClose', href: 'javascript:Videobox.prototype.end();' },
        //Builder.node('img', { src: VideoboxOptions.fileBottomNavCloseImage })
        //)
        //)
                ])
			])
			])

			]));

        $('VideoOverlay').hide().observe('click', (function() { this.end(); }).bind(this));
        $('videobox').hide().observe('click', (function(event) { if (event.element().id == 'videobox') this.end(); }).bind(this));
        $('bottomNavVideoClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

        var th = this;
        (function() {
            var ids =
                'flash VideoOverlay videobox videoDataContainer videoData videoDetails videoCaption numberDisplay bottomNavVideo bottomNavVideoClose';
            $w(ids).each(function(id) { th[id] = $(id); });
        }).defer();
    },

    //
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateImageList: function() {
        this.updateImageList = Prototype.emptyFunction;

        document.observe('click', (function(event) {
            var target;
            if (!lightboxKiller) {
                target = event.findElement('a[rel^=videobox]') || event.findElement('area[rel^=videobox]');
            }
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },

    //
    //  start()
    //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {

        if (Prototype.Browser.IE) {
            $$('select').each(function(node) { node.style.display = 'none' });
            $$('input.replaceSelect').each(function(node) { node.remove() });

            var selEls = document.getElementsByTagName("select");
            for (var i = 0; i < selEls.length; i++) {
                var dropdownIndex = selEls[i].selectedIndex;
                var dropdownValue = selEls[i][dropdownIndex].text;
                selEls[i].parentNode.appendChild(Builder.node('input', { className: 'replaceSelect', value: dropdownValue }));
            }

            $$('input.replaceSelect').each(function(node) { node.style.display = 'inline' });
        }
        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('VideoOverlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        if (!this.tb_detectMacXFF()) {
            new Effect.Appear(this.VideoOverlay, { duration: this.overlayDuration, from: 0.0, to: VideoboxOptions.overlayOpacity });
        } else {
            this.VideoOverlay.className = "MacFireFoxFix";
            new Effect.Appear(this.VideoOverlay, { duration: this.overlayDuration, from: 0.0, to: 1.0 });
        }



        this.imageArray = [];
        var imageNum = 0;

        if ((imageLink.rel == 'videobox')) {
            // if image is NOT part of a set, add single image to imageArray
            this.imageArray.push([imageLink.href, imageLink.rev]);
            videoPath = imageLink.href;
            videoTitle = imageLink.rev;
            //alert(videoPath);
            //edit WRAP TEAM
            if (getURLCurrentLanguage() == 'id_id') {
                buildFlash("flash", "_LAYOUTS/PMI/GCW/Swf/VideoPlayer.swf", "flashPlayer", "375", "460", videoPath, "/_layouts/pmi/gcw/images/sampoerna_preload_video.jpg");
            } else {
                buildFlash("flash", "_LAYOUTS/PMI/GCW/Swf/VideoPlayer.swf", "flashPlayer", "375", "460", videoPath, "/_layouts/pmi/gcw/images/pmi_preload_video.jpg");
            }
            //alert(videoTitle);
            document.getElementById("videoCaption").innerHTML = videoTitle;

        } else {
            // if image is part of a set..
            this.imageArray =
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor) { return [anchor.href, anchor.rev]; }).
                uniq();

            while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
        }

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var lightboxLeft = arrayPageScroll[0];
        this.videobox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();

        this.changeImage(imageNum);
    },
    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function(imageNum) {

        this.activeImage = imageNum; // update global var

        // hide elements during transition
        if (VideoboxOptions.animate);
        // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        //this.videoDataContainer.setStyle({opacity: .0001});
        this.videoDataContainer.setStyle({ opacity: 20 });
        this.numberDisplay.hide();

        var imgPreloader = new Image();


        // once image is preloaded, resize image container


        imgPreloader.onload = (function() {
            this.flash.src = this.imageArray[this.activeImage][0];
            this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.imageArray[this.activeImage][0];
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get current width and height
        var widthCurrent = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();

        // get new width and height
        var widthNew = (imgWidth + VideoboxOptions.borderSize * 2);
        var heightNew = (imgHeight + VideoboxOptions.borderSize * 2);

        // scalars based on change from old to new
        var xScale = (widthNew / widthCurrent) * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, { scaleX: false, duration: this.resizeDuration, queue: 'front' });
        if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, { scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration });

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)) {
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;
        }

        (function() {
            this.prevLink.setStyle({ height: imgHeight + 'px' });
            this.nextLink.setStyle({ height: imgHeight + 'px' });
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },

    //
    //  showImage()
    //  Display image and begin preloading neighbors.
    //
    showImage: function() {
        this.loading.hide();
        new Effect.Appear(this.flash, {
            duration: this.resizeDuration,
            queue: 'end',
            afterFinish: (function() { this.updateDetails(); }).bind(this)
        });

        this.preloadNeighborImages();
    },

    //
    //  updateDetails()
    //  Display caption, image number, and bottom nav.
    //
    updateDetails: function() {

        // if caption is not null
        this.videoCaption.show();
        if (this.imageArray[this.activeImage][1] != "") {
            this.videoCaption.show();
            this.videoCaption.update(this.imageArray[this.activeImage][1]).show();
        }

        // if image is part of set display 'Image x of x' 
        if (this.imageArray.length > 1) {
            this.numberDisplay.update(VideoboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + VideoboxOptions.labelOf + '  ' + this.imageArray.length).show();
        }

        new Effect.Parallel(
            [
                new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }),
                new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration })
            ],
            {
                duration: this.resizeDuration,
                afterFinish: (function() {
                    // update overlay size and update nav
                    var arrayPageSize = this.getPageSize();
                    this.VideoOverlay.setStyle({ height: arrayPageSize[1] + 'px' });
                    this.updateNav();
                }).bind(this)
            }
        );
    },

    //
    //  updateNav()
    //  Display appropriate previous and next hover navigation.
    //
    updateNav: function() {

        this.hoverNav.show();

        // if not first image in set, display prev image button
        if (this.activeImage > 0) this.prevLink.show();

        // if not last image in set, display next image button
        if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();

        this.enableKeyboardNav();
    },

    //
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction);
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction);
    },

    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();

        if (key.match(/x|o|c/) || (keycode == escapeKey)) { // close lightbox
            this.end();
        } else if ((key == 'p') || (keycode == 37)) { // display previous image
            if (this.activeImage != 0) {
                this.disableKeyboardNav();
                this.changeImage(this.activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)) { // display next image
            if (this.activeImage != (this.imageArray.length - 1)) {
                this.disableKeyboardNav();
                this.changeImage(this.activeImage + 1);
            }
        }
    },

    //
    //  preloadNeighborImages()
    //  Preload previous and next images.
    //
    preloadNeighborImages: function() {
        var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1) {
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
        }
        if (this.activeImage > 0) {
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
        }

    },

    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        //this.videobox.hide();
        document.getElementById('videobox').style.display = 'none';
        document.getElementById('VideoOverlay').style.display = 'none';
        document.getElementById('flash').innerHTML = '';


        //new Effect.Fade(this.VideoOverlay, { duration: this.overlayDuration });
        if (Prototype.Browser.IE) {
            $$('input.replaceSelect').each(function(node) { node.remove() });
            $$('select').each(function(node) { node.style.display = 'inline' });
        }
    },

    /* Insert at the end of the thickbox.js file */
    tb_detectMacXFF: function() {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
            return true;
        }
    },

    //
    //  getPageSize()
    //
    getPageSize: function() {

        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;

            // Fix below for opera not scrolling

            if ((browser == "Opera")) {
                operaHeight = document.viewport.getDimensions().height * 2;
                //alert(operaHeight);
                yScroll = operaHeight + document.viewport.getScrollOffsets().top;
                //alert(yScroll);
            }

        }

        var windowWidth, windowHeight;

        if (self.innerHeight) {	// all except Explorer
            if (document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = xScroll;
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth, pageHeight];
    }
}

document.observe('dom:loaded', function() { new Videobox(); });
