// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = '/shared/packages/lightbox/loading.gif';        
var closeButton = '/shared/packages/lightbox/close.gif';        

function LightBoxEventHandler()
{
    this._default_thumb_anchor_id = "";
    this._main_pline_thumb = "";
    
    this.Captions=Array();
    function CaptionObject(ID,Caption)
    {
        this.ID=ID;
        this.Caption=Caption;
    }
    //
    // getPageScroll()
    // Returns array with x,y page scroll values.
    // Core code from - quirksmode.org
    //
    this.getPageScroll=function()
    {
        var yScroll;

        if (self.pageYOffset)
        {
            yScroll = self.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop)
        {
            // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
        }
        else if (document.body)
        {
            // all other Explorers
            yScroll = document.body.scrollTop;
        }

        arrayPageScroll = new Array('',yScroll) 
        return arrayPageScroll;
    }



    //
    // getPageSize()
    // Returns array with page width, height and window width, height
    // Core code from - quirksmode.org
    // Edit for Firefox by pHaez
    //
    this.getPageSize=function()
    {
        
        var xScroll, yScroll;
        
        if (window.innerHeight && window.scrollMaxY)
        {    
            xScroll = document.body.scrollWidth;
            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;
        }
        
        var windowWidth, windowHeight;
        if (self.innerHeight)
        {
            // all except Explorer
            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 = windowWidth;
        else
            pageWidth = xScroll;

        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
        return arrayPageSize;
    }

    //
    // showLightbox()
    // Preloads images. Pleaces new image in lightbox then centers and displays.
    //
    this.showLightbox=function(objLink,Caption,Context)
    {
        // prep objects
        var objOverlay = document.getElementById('lightbox_overlay');
        var objLightbox = document.getElementById('lightbox');
        var objCaption = document.getElementById('lightboxCaption');
        var objImage = document.getElementById('lightboxImage');
        var objLoadingImage = document.getElementById('loadingImage');
        var objLightboxDetails = document.getElementById('lightboxDetails');
        var objVideoContainer   = document.getElementById('video_container');

        var arrayPageSize = this.getPageSize();
        var arrayPageScroll = this.getPageScroll();
        
        var left_mod = 0;

        // center loadingImage if it exists
        if (objLoadingImage)
        {
            objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
            objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
            objLoadingImage.style.display = 'block';
        }

        // set height of Overlay to take up whole page and show
        objOverlay.style.height = (arrayPageSize[1] + 'px');
        objOverlay.style.display = 'block';
        
        // 7/20/2010 -- do some checks for a single LB
        var obj_gallery_div = document.getElementById("lightbox_thumbs_outer");
        
        if( objLink.id.match(/__SINGLE__/) )
        {            
            obj_gallery_div.style.display = "none";               
            left_mod = 0;
        }
        else
        {
            obj_gallery_div.style.display = "block";   
            left_mod = 183;
        }
        
        if (objLink.href.match(/youtube\.com\/watch/i))
        {
            var hRef = objLink.href;
            var videoId = hRef.split('=');
            videoID = videoId[1];
            var width=640;
            var height=480;
            objVideoContainer.innerHTML='';
            objImage.style.display='none';
            
            so = new SWFObject("http://www.youtube.com/v/"+videoID, "flvvideo", 640, 480, "0");
            //so.addParam("wmode", "transparent");
            so.write(objVideoContainer);
             // center lightbox and make sure that the top and left values are not negative
                // and the image placed outside the viewport
                var lightboxTop     = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - height) / 2);
                var lightboxLeft    = ((arrayPageSize[0] - 20 - width) / 2) - left_mod;
                
                objLightbox.style.top   = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
                objLightbox.style.left  = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";


                //objLightboxDetails.style.width = width + 'px';
                
                if(objLink.getAttribute('title') || typeof(Caption) != "undefined")
                {
                    objCaption.style.display = 'block';
                    //objCaption.style.width = imgPreload.width + 'px';
                    if(typeof(Caption) != "undefined")
                        objCaption.innerHTML = Caption;
                    else
                        objCaption.innerHTML = objLink.getAttribute('title');
                }
                else         
                    objCaption.style.display = 'none';

                if (objLoadingImage)
                    objLoadingImage.style.display = 'none';
                objLightbox.style.display = 'block';

                // After image is loaded, update the overlay height as the new image might have
                // increased the overall page height.
                
                arrayPageSize = Context.getPageSize();
                objOverlay.style.height = (arrayPageSize[1] + 'px');
                
                document.onkeypress=function(e)
                {
                    if (e == null)
                    {
                        // ie
                        keycode = event.keyCode;
                    }
                    else
                    {
                        // mozilla
                        keycode = e.which;
                    }
                    key = String.fromCharCode(keycode).toLowerCase();
                    
                    if(key == 'x')
                        Context.hideLightbox.call(Context);                
                }
                return false;
                
        }
        else
        {
            // preload image
            objVideoContainer.innerHTML='';
            imgPreload = new Image();

            imgPreload.onload=function()
            {
                objImage.src = objLink.href;

                // center lightbox and make sure that the top and left values are not negative
                // and the image placed outside the viewport
                // var lightboxTop     = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
                // var lightboxLeft    = ((arrayPageSize[0] - 20 - imgPreload.width) / 2) - 110;

                var lightboxTop     = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - 480 ) / 2);
                var lightboxLeft    = ((arrayPageSize[0] - 20 - 640) / 2) - left_mod;
                
                objLightbox.style.top   = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
                objLightbox.style.left  = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";


                //objLightboxDetails.style.width = imgPreload.width + 'px';
                
                if(objLink.getAttribute('title') || typeof(Caption) != "undefined")
                {
                    objCaption.style.display = 'block';
                    //objCaption.style.width = imgPreload.width + 'px';
                    if(typeof(Caption) != "undefined")
                        objCaption.innerHTML = Caption;
                    else
                        objCaption.innerHTML = objLink.getAttribute('title');
                }
                else         
                    objCaption.style.display = 'none';

                if (objLoadingImage)
                    objLoadingImage.style.display = 'none';
                objLightbox.style.display = 'block';
                objImage.style.display='block';

                // After image is loaded, update the overlay height as the new image might have
                // increased the overall page height.
                
                arrayPageSize = Context.getPageSize();
                objOverlay.style.height = (arrayPageSize[1] + 'px');  
                
                
                // Check for 'x' keypress
                //Context.listenKey.call(Context,Context);
                document.onkeypress=function(e)
                {
                    if (e == null)
                    {
                        // ie
                        keycode = event.keyCode;
                    }
                    else
                    {
                        // mozilla
                        keycode = e.which;
                    }
                    key = String.fromCharCode(keycode).toLowerCase();
                    
                    if(key == 'x')
                        Context.hideLightbox.call(Context);                
                }
                return false;
            }
            imgPreload.src = objLink.href;
        }    
    }


    this.hideLightbox=function()
    {
        // get objects
        objOverlay = document.getElementById('lightbox_overlay');
        objLightbox = document.getElementById('lightbox');

        // hide lightbox and overlay
        objOverlay.style.display = 'none';
        objLightbox.style.display = 'none';
                
        // disable keypress listener
        document.onkeypress = '';
        return false;
    }
    
    this.initAnchor=function(id,caption,handler,context)
    {
        var obj=document.getElementById(id);
        if(obj==null)
            return;
        
        this.Captions.push(new CaptionObject(id,caption));    
        
        obj.onclick = function()
        {
            handler.call(context,obj,context);return false;
        };        
    }
    
    this.triggerLightBox=function(obj,context)
    {
        this.showLightbox(obj,this.FindCaptionById(obj.id),context);
    }
   
    this.FindCaptionById=function(ID)
    {
        for(var c=0;c<this.Captions.length;c++)
        {
            if(this.Captions[c].ID ==ID)
                return this.Captions[c].Caption;
        }
        return null;
    }
    
    
    /* Adds a thumbnail to the lightbox for an image present on the pline page.
     * 
     * anchor_id = must match the id of the <a> element on the pline page
     * thumb_url = must be the 50x50 image
     * caption = text of the caption
     */
    this.add_thumb_minor=function(anchor_id, thumb_url, caption)
    {        
        /*
        if( this._default_thumb_anchor_id == "" )
        {
            this._default_thumb_anchor_id = anchor_id;
            this._main_pline_thumb = thumb_url;
        }
        else if( this._main_pline_thumb == thumb_url ) 
        {
            // In some cases the main pline image is uploaded twice or not tagged properly,
            // in which case we want to ignore it and not display it twice in the gallery.  
            // So do nothing.
            return;
        }
        
        // let's not duplicate thumbs, check by 50x50 image
        if( gallery_obj.innerHTML.indexOf( thumb_url ) > -1 )
        {
            // don't do anything
        }
        else
        {
            this.gallery_helper( "<div onclick=\"GlobalLightBoxEventHandler.thumb_minor_action('" + anchor_id + "')\" style='cursor: pointer;'><img src='" + thumb_url + "' width='50px' height='50px' title='Click For Full Size' alt='' style='margin-bottom: 5px;' /><br style='clear: both;' /><div class='lb_gallery_caption_element'><div class='lb_gallery_caption'>" + this.fix_caption(caption) + "</div></div></div>" );
            }
            
        */
                   
    }
    
    /* Adds a thumbnail to the lightbox for a product-level image
     *
     * anchor_id = must match the id of the <a> element on the product page
     * thumb_url = must be the 50x50 image
     * caption = text of the caption
     * 
     * This func differs from others in that it does a check to see if the pline thumbs already display the product thumb
     */
    
    
    /* Adds a thumbnail to the lightbox for an image not present on the pline page.
     * 
     * anchor_id = unique id, should not equal any other id on the pline page
     * thumb_url = must be the 50x50 image
     * full_url = link to the image to display in the lb
     * caption = text of the caption
     */
    this.add_thumb_major=function(anchor_id, thumb_url, full_url, caption)
    {
        /*
        // Don't show the main pline image twice...
        if( this._main_pline_thumb != thumb_url ) 
        {
            this.gallery_helper( "<div onclick=\"GlobalLightBoxEventHandler.thumb_minor_action('" + anchor_id + "')\" style='cursor: pointer;'><img src='" + thumb_url + "' border='0' width='50px' height='50px' title='Click For Full Size' alt='' style='margin-bottom: 5px;' /><br style='clear: both;' /><div class='lb_gallery_caption_element'><div class='lb_gallery_caption'>" + this.fix_caption(caption) + "</div></div></div><a id='" + anchor_id + "' href='" + full_url + "'></a>" );
        }
        */
     }
    
    /* Triggers the onclick action of the supplied anchor_id.
     * 
     * This function is meant to be called by a thumbnail from the lb gallery in order to switch to its image,
     * IF and ONLY IF that thumbnail is also present on the pline page.
     * 
     * anchor_id = the id of the <A> element on the pline page.
     */
    this.thumb_minor_action=function(anchor_id)
    {        
        var element = document.getElementById(anchor_id);
        
        // let's make sure the alpha tint is showing in the background still
        var bg = document.getElementById('lightbox_overlay');
        bg.style.display= "block";
        
        element.onclick();
    }
    
    /*  Force the lightbox to show with the first loaded thumb/image
     */
    this.show_default_lightbox=function()
    {
        this.thumb_minor_action( this._default_thumb_anchor_id );  
    }
    
    this.set_default_thumb_action=function(anchor_id)
    {
        this._default_thumb_anchor_id = anchor_id;
    }
    
    /* Creates a two column lightbox gallery of the provided data.
     * 
     * data = Thumbnail HTML, needs to be everything except the layout markup 
     * 
     * Note:    Execution path
     *          1. _REMOVEME_ exists?
     *              2b. Replace with data
     *          2. _REMOVEME2_ exists?
     *              2b. Replace with data
     *          3. Doesn't exist?
     *              3b. Replace with data + _REMOVEME_
     * 
     *          _REMOVEME_ isn't pretty, but anything else will run into errors or odd
     *          behavior in IE7 or 8.  We take out any errant _REMOVEME_ in a cleanup func.
     */
    this.gallery_helper=function(data)
    {
        /*
        var gallery_obj = document.getElementById("lightbox_thumbs_outer");
        
        if( gallery_obj.innerHTML.indexOf("_REMOVEME_") > -1 )
        {
            //console.warn( gallery_obj.innerHTML.match( "<span id=\"next_thumb\" />") );
            gallery_obj.innerHTML = gallery_obj.innerHTML.replace( "_REMOVEME_", data );
        }
        else if( gallery_obj.innerHTML.indexOf("_REMOVEME2_") > -1 )
        {
            gallery_obj.innerHTML = gallery_obj.innerHTML.replace( "_REMOVEME2_", data );
        }
        else
        {
            gallery_obj.innerHTML = gallery_obj.innerHTML + "<div class='lb_gallery_row'><div class='lb_gallery_div_a'><div class='lb_gallery_element'>" + data + "</div></div><div class='lb_gallery_row_part_2'><div class='lb_gallery_div_b'><div class='lb_gallery_element'>_REMOVEME_</div></div><div class='lb_gallery_div_c'><div class='lb_gallery_element'>_REMOVEME2_</div></div></div></div><br />";
            
        }
        */
    }
    
    /* Cleans up the lb gallery for presentation
     * 
     * Note: We have to remove any remaining "_REMOVEME_" from the gallery.  
     *       Should be called once when the lb images are done loading.
     */
    this.cleanup_gallery=function()
    {
        var gallery_obj = document.getElementById("lightbox_thumbs_outer");
        
        if( gallery_obj.innerHTML.indexOf("_REMOVEME_") > -1 )
        {
            gallery_obj.innerHTML = gallery_obj.innerHTML.replace( "_REMOVEME_", "" );
        }
        
        if( gallery_obj.innerHTML.indexOf("_REMOVEME2_") > -1 )
        {
            gallery_obj.innerHTML = gallery_obj.innerHTML.replace( "_REMOVEME2_", "" );
        }
    }
    
    /* Returns a turnacated caption
     *
     * caption = raw caption text, unformatted
     */
    this.fix_caption=function(caption)
    {
       if( caption.length > 25 )
       {
           return caption.substring(0,22) + "...";
       } 
       
       return caption;
    }
}
