﻿/*
Javascript control showing a single WebGallery entity
*/

var WebGallery = Class.create();

WebGallery.prototype =
{
    // Constructor
    initialize : function(piEntityId, piTarget)
    {
        // Declare variable holding the id of the content entity
        this.Id = piEntityId;
        // Declare variable holding the id of the entity's html node
        this._nodeId = 'WebGallery_' + piEntityId;
        // Declare variable holding the html node which serves as content holder for this entity
        this._target = this.GetTarget(piTarget);
        
        // Declare variable holding the entity object
        this._entity;
        // Declare Array variable holding all web image entities
        this._webImageEntities = new Array();

        // Declare variable holding the number of images that are to be requested
        this._entitiesToRequest = 0;
        // Declare variable holding the number of images that have been requested
        this._entityRequestCount = 0;
        
        // Declare variable holding the html node which serves as content container
        this._htmlContainer;
        // Declare variable holding the html node which serves as image container
        this._imageContainer;
        // Declare variable holding the html node which serves as image canvas
        this._imageCanvas;
        // Declare variable holding the image html node
        this._image;
        this._currentImageId;
        // Declare variable holding the description node
        this._descNode;
        // Declare variable holding the html node which serves as thumbnail container
        this._thumbnailContainer;
        
        // Declare variable holding the width of the image container
        this._imageContainerWidth;
        
        // Call Build function to build the content holder
        this.Build();
        // Call RequestData function to get the xml data from the web service
        this.RequestGalleryData();
        
        this._cancelEvents = false;
    },
    
    GetTarget : function(piTarget)
    {
        try
        {
            return $(piTarget);
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'GetTarget', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    Build : function()
    {
        try
        {
            // Build new content holder node
            this._htmlContainer = Builder.node('div', { id : this._nodeId });
            this._htmlContainer.className = 'WebGallery';
            
            // Build image container
            this._imageContainer = Builder.node('div');
            this._imageContainer.className = 'WebGallery_ImageContainer';
            
            // Build image canvas
            this._imageCanvas = Builder.node('div');
            this._imageCanvas.className = 'WebGallery_ImageCanvas';
            this._imageContainer.appendChild(this._imageCanvas);
            
            // Build thumbnail container
            this._thumbnailContainer = Builder.node('div');
            this._thumbnailContainer.className = 'WebGallery_ThumbnailContainer';
            
            // Add elements to the htmlContainer
            this._htmlContainer.appendChild(this._thumbnailContainer);
            //this._htmlContainer.appendChild(this._imageContainer);
            this._htmlContainer.appendChild(Builder.node('div', { style: 'clear:left' }));
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'Build', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    RequestGalleryData : function()
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_REQUESTING_DATA', 'RequestData', arguments, 'WEBGALLERY', this.Id)
            // Create input parameters for the webservice method
            var params=$H( {piHostHeader : Site.HostHeader, piEntityId : this.Id} ).toQueryString();
            // Create new Ajax request
            new Ajax.Request("ISDataService.asmx/GetEntityData", { method : "post", parameters : params, requestHeaders : ['Pragma', 'no-cache', 'Cache-Control', 'no-store, no-cache, max-age=0, must-revalidate'], onSuccess : this.OnGalleryDataRequestResponse.bind(this), onFailure: this.OnRequestGalleryDataFail.bind(this) });
        }
        catch(e)
        {
            Logs.WriteException('ERROR_STARTING_REQUEST', 'RequestData', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    OnRequestGalleryDataFail : function()
    {
        Logs.WriteError('ERROR_REQUESTING_DATA', 'RequestData', null, 'WEBGALLERY', this.Id);
    },
    
    // Receives entity's xml data from the webservice
    OnGalleryDataRequestResponse : function(transport)
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_RECEIVING_DATA', 'OnDataRequestResponse', arguments, 'WEBGALLERY', this.Id)
            // Set local variable holding the xml data
            this._entity = new EntityObject(new XmlDocument(transport.responseXML));
            
            // Write error log if the last interaction did not succeed
            if(this._entity.Success == false)
            {
                // Write Error to the Log
                Logs.WriteError('ERROR_MISSING_XML_DATA', 'OnDataRequestResponse', arguments, 'WEBGALLERY', this.Id)
                
                return
            }
                    
            // Call ProcessGalleryContentInformation function to create entity objects/controls
            this.ProcessGalleryContentInformation();
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'OnDataReuqestResponse', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    ProcessGalleryContentInformation : function()
    {       
        var imageRefs = this._entity.Content.References;
        
        for(var i = 0; i < imageRefs.length; i++)
        {
            // Check if the current image reference is not null
            if(this._entity.Content.References[i] != null)
            {
                // Create a link for the image thumbnail
                var thumbLink = Builder.node('a', { style: 'cursor: pointer', href: 'IMageServer.aspx?action=getimage&id=' + this._entity.Content.References[i].Id + '&size=450', rel: 'lightbox[ui]'});
                this._thumbnailContainer.appendChild(thumbLink);
                
                // Create an html image object and add it to the thumbnail container
                var thumbImg = Builder.node('img', { style: 'cursor: pointer', name: this._entity.Content.References[i].Id, src: 'IMageServer.aspx?action=getimage&id=' + this._entity.Content.References[i].Id + '&size=small'});
                thumbLink.appendChild(thumbImg);
                
            }
        }
        
        myLightbox.updateImageList();
        
        /*try
        {
            // Get / calculate the dimensions of the gallery containers
            var htmlContainerWidth = 550;
            if((this._entity.Configuration.Width != null) && (this._entity.Configuration.Width.Value != null) && (this._entity.Configuration.Width.Value != ''))
            {
                htmlContainerWidth = this._entity.Configuration.Width.Value;
            }
            
            // Set the dimensions of the gallery containers
            this._htmlContainer.style.width = htmlContainerWidth + 'px';
            this._imageContainer.style.width = htmlContainerWidth + 'px';
            this._thumbnailContainer.style.width = htmlContainerWidth + 'px';
            // Set this._imageContainerWidth value
            this._imageContainerWidth = htmlContainerWidth;
            
            // Iterate through image references of the entity data object
            var imageRefs = this._entity.Content.References;
            this._entitiesToRequest = imageRefs.length;
            for(var i = 0; i < imageRefs.length; i++)
            {
                // Check if the current image reference is not null
                if(this._entity.Content.References[i] != null)
                {
                    // Create an html image object and add it to the thumbnail container
                    var thumbImg = Builder.node('img', { style: 'cursor: pointer', name: this._entity.Content.References[i].Id, src: 'IMageServer.aspx?action=getimage&id=' + this._entity.Content.References[i].Id + '&size=small'});
                    Event.observe(thumbImg, 'click', this.SwitchImage.bindAsEventListener(this));
                    this._thumbnailContainer.appendChild(thumbImg);
                    
                    // Get the image data from the webservice
                    this.RequestImageData(this._entity.Content.References[i].Id);
                }
            }
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'ProcessContentInformation', arguments, 'WEBGALLERY', this.Id, e, false)
        }*/
    },
    
    RequestImageData : function(piImageId)
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_REQUESTING_DATA', 'RequestImageData', arguments, 'WEBGALLERY', piImageId)
            // Create input parameters for the webservice method
            var params=$H( {piHostHeader : Site.HostHeader, piEntityId : piImageId} ).toQueryString();
            // Create new Ajax request
            new Ajax.Request("ISDataService.asmx/GetEntityData", { method : "post", parameters : params, requestHeaders : ['Pragma', 'no-cache', 'Cache-Control', 'no-store, no-cache, max-age=0, must-revalidate'], onSuccess : this.OnImageDataRequestResponse.bind(this), onFailure: this.OnImageDataRequestFail.bind(this) });
        }
        catch(e)
        {
            Logs.WriteException('ERROR_STARTING_REQUEST', 'RequestData', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    OnImageDataRequestFail : function()
    {
        this._entityRequestCount++;
        Logs.WriteError('ERROR_REQUESTING_DATA', 'RequestData', null, 'WEBGALLERY', this.Id);
    },
    
    OnImageDataRequestResponse : function(transport)
    {
        try
        {
            this._entityRequestCount++;
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_RECEIVING_DATA', 'OnImageDataRequestResponse', arguments, 'WEBGALLERY', this.Id)
            // Set local variable holding the xml data
            var entity = new EntityObject(new XmlDocument(transport.responseXML));
            
            // Write error log if the last interaction did not succeed
            if(entity.Success == false)
            {
                // Write Error to the Log
                Logs.WriteError('ERROR_MISSING_XML_DATA', 'OnImageDataRequestResponse', arguments, 'WEBGALLERY', this.Id)
                
                return
            }
                    
            this._webImageEntities.push(entity);
            if(this._entitiesToRequest == this._entityRequestCount)
            {
                this.ProcessImageContentInformation();
            }
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'OnDataReuqestResponse', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    ProcessImageContentInformation : function()
    {               
        for(var i = 0; i < this._webImageEntities.length; i++)
        {
            // Create an html image object and add it to the _webImages array
            var webImg = Builder.node('img', { name: i, src: 'IMageServer.aspx?action=getimage&id=' + this._webImageEntities[i].Id + '&size=' + parseInt(this._imageContainerWidth - 50)});
            
            // Create holder for the image
            var webImgHolder = Builder.node('div', { style: 'display:none;text-align:center;' });
            
            // Create holder for the image description
            var webImgDescHolder = Builder.node('p', { style: 'text-align_center;margin:5px 0px 0px 0px;' });
            
            // Add the web image to the web image holder
            webImgHolder.appendChild(webImg);
            
            // Check if an image description is povided
            if((this._webImageEntities[i].Content.Description != null) && (!this._webImageEntities[i].Content.Description.Value.blank()))
            {
                webImgDescHolder.innerHTML = this._webImageEntities[i].Content.Description.Value;
                webImgHolder.appendChild(webImgDescHolder);
            }
            
            var imageId = this._webImageEntities[i].Id;
            this[imageId] = webImgHolder;
        }
                   
        if(this._webImageEntities.length > 0)
        {
            var showImageFunc = function()
            {
                this.SetImageCanvasSize(this._webImageEntities[0].Id);
                this.ShowImageById(this._webImageEntities[0].Id);
            }
            
            window.setTimeout(showImageFunc.bind(this), 1200);
        }
    },
    
    Show : function()
    {
        try
        {
            this._target.appendChild(this._htmlContainer);
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'Show', arguments, 'WEBGALLERY', this.Id, e, false)
        }
    },
    
    SwitchImage : function(piEvent)
    {
        if(this._cancelEvents)
        {
            return;
        }
        
        this._cancelEvents = true;
        
        // Get the thumbnail image that has been clicked
        var thumbNail = Event.findElement(piEvent, 'img')
        
        // Check if the thumbnail image object is filled
        if(thumbNail)
        {
            if(thumbNail.name == this._currentImageId)
            {
                return;
            }
            else
            {
                this._currentImageId = thumbNail.name;
            }
            
            // Fade out the current large image
            Effect.Fade(this._image, { from:1.0, to:0.0, duration: 0.5 });
            
            // Create anonymous function to resize the image canvas
            var ResizeCanvasFunc = function()
            {
                this.ResizeImageCanvas(thumbNail.name);
            }
            
            // Create anonymous function to show the large image
            var ShowNewImageFunc = function()
            {
                this.ShowImageById(thumbNail.name);
            }
            
            window.setTimeout(ResizeCanvasFunc.bind(this), 500);
            window.setTimeout(ShowNewImageFunc.bind(this), 1300);
        }
    },
    
    ShowImageById : function(piImageId)
    {
        if(this[piImageId] != null)
        {                      
            this._image = this[piImageId];
            // Append the image to the image container
            this._imageCanvas.appendChild(this._image);
            
            // Create Appear effect for the image
            Effect.Appear(this._image, { duration: 0.5 });
        }
        
        window.setTimeout(function(){ this._cancelEvents = false; }.bind(this), 500);
    },
    
    ResizeImageCanvas : function(piImageId)
    {
        // Get the image at the requested index from the image array
        var image = this[piImageId];
        // Append the image to the document body
        document.body.appendChild(image);
        // Get the dimensions of the image
        var imgDims = $(image).getDimensions();
        // Remove the image from the document body
        document.body.removeChild(image);
        
        // Calculate the left margin for the image canvas
        var leftMargin = (this._imageContainerWidth - imgDims.width - 30) / 2;
        
        // Create morph effect to chnage the image canvas size according to the size of the image
        new Effect.Morph(this._imageCanvas, { duration:0.8, style: 'width:' + imgDims.width + 'px;height:' + imgDims.height + 'px;margin-left:' + leftMargin + 'px;' });
    },
    
    SetImageCanvasSize : function(piImageId)
    {
        // Get the image at the requested index from the image array
        var image = this[piImageId];
        // Append the image to the document body
        document.body.appendChild(image);
        // Get the dimensions of the image
        var imgDims = $(image).getDimensions();
        // Remove the image from the document body
        document.body.removeChild(image);
        
        // Calculate the left margin for the image canvas
        var leftMargin = (this._imageContainerWidth - imgDims.width - 30) / 2;
        
        // Create morph effect to chnage the image canvas size according to the size of the image
        $(this._imageCanvas).setStyle({ width: imgDims.width + 'px', height: imgDims.height + 'px', marginLeft: leftMargin + 'px' });
    }
}