﻿/*
Javascript control showing a single WebImage entity
*/

var WebImage = Class.create();

WebImage.prototype =
{
    // Constructor
    initialize : function(piEntityId, piTarget, piAlignment)
    {        
        // 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 = 'WebImage_' + piEntityId;
        // Declare variable holding the html node which serves as content holder for this entity
        this._target = this.GetTarget(piTarget);
        // Declare variable holding the image alignment
        this.Alignment = '';
        // Declare variable indicating the size of the large image
        // If set, this overrides the standard configuration of the image
        this.LargeImageSize = null;
        
        // Declare variable holding the entity object
        this._entity;
        
        // Declare variable holding the html node which serves as content container
        this._htmlContainer;
        // Declare variable holding the imageNode
        this._imageNode;
        // Declare variable holding the description node
        this._descNode;
        
        // Call Build function to build the content holder
        this.Build();
        // Call RequestData function to get the xml data from the web service
        this.RequestData();
        
        this._overlay;
    },
    
    GetTarget : function(piTarget)
    {
        try
        {
            return $(piTarget);
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'GetTarget', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    Build : function()
    {
        try
        {
            // Build new content holder node
            this._htmlContainer = Builder.node('div', { id : this._nodeId });
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'Build', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    RequestData : function()
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_REQUESTING_DATA', 'RequestData', arguments, 'WEBIMAGE', 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.OnDataRequestResponse.bind(this), onFailure: this.OnRequestFail.bind(this) });
        }
        catch(e)
        {
            Logs.WriteException('ERROR_STARTING_REQUEST', 'RequestData', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    OnRequestFail : function()
    {
        Logs.WriteError('ERROR_REQUESTING_DATA', 'RequestData', null, 'WEBTEXT', this.Id);
    },
    
    // Receives entity's xml data from the webservice
    OnDataRequestResponse : function(transport)
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_RECEIVING_DATA', 'OnDataRequestResponse', arguments, 'WEBIMAGE', 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, 'WEBIMAGE', this.Id)
                
                return
            }
                    
            // Call ProcessContentInformation function to create entity objects/controls
            this.ProcessContentInformation();
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'OnDataReuqestResponse', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    ProcessContentInformation : function()
    {       
        try
        {
            // Get image title
            var titleField = '';
            if((this._entity.Content.Title != null) && (this._entity.Content.Title.Value != null) && (!this._entity.Content.Title.Value.blank()))
            {
                titleField = this._entity.Content.Title.Value;
            }
            
            // Get the image size configuration parameter
            var imageSize = false;
            if(this._entity.Configuration.Image_size.Value == 'USE_GLOBAL_CONFIG')
            {
                imageSize = Site._entity.Configuration.Webimage.Image_size.Value.toLowerCase()
            }
            else
            {
                imageSize = this._entity.Configuration.Image_size.Value.toLowerCase()
            }
            
            // Build image node
            this._imageNode = Builder.node('img', { src : 'IMageServer.aspx?action=getimage&id=' + this.Id + '&size=' + imageSize, alt:titleField });
            
            // Check if the image has a followup link and create the link if so
            if((this._entity.Content.Followup != null) && (this._entity.Content.Followup.Value != null) && (!this._entity.Content.Followup.Value.blank()))
            {
                // Create a link node and set the href attribute
                var linkNode =  Builder.node('a', { href: this._entity.Content.Followup.Value });
                // Append the linkNode to the _htmlContainer
                this._htmlContainer.appendChild(linkNode);
                // Append the image to the link node
                linkNode.appendChild(this._imageNode);
            }
            else
            {
                // Append the image node to the content holder
                this._htmlContainer.appendChild(this._imageNode);
            }
            
            // Check if the an image description is present and if it is to be shown
            if((this._entity.Content.Description != null) && (this._entity.Content.Description.Value != null) && (!this._entity.Content.Description.Value.blank()))
            {
                var imgDesc = this._entity.Content.Description.Value;
                
                if((this._entity.Configuration.Show_description_while_small != null) && (this._entity.Configuration.Show_description_while_small.Value != null) && (!this._entity.Configuration.Show_description_while_small.Value.blank()))
                {
                    var showSmallDesc = this._entity.Configuration.Show_description_while_small.Value;
                }
                else
                {
                    return;
                }
                
                if(showSmallDesc == 'USE_GLOBA_CONFIG')
                {
                    showSmallDesc = Helpers.ParseBoolean(Site._entity.Configuration.Webimage.Show_description_while_small.Value.toLowerCase());
                }
                else
                {
                    showSmallDesc = Helpers.ParseBoolean(showSmallDesc);
                }
                
                if(showSmallDesc == true)
                {
                    // Create a paragraph node and insert the image description
                    this._descNode = Builder.node('p', { style: 'font-size:10px;text-align:center' });
                    this._descNode.innerHTML = imgDesc;
                    
                    // Append the description node to the htmlContainer
                    this._htmlContainer.appendChild(this._descNode)   
                }
            }
            
            // Set image alignment if any alignment configuration is provided
            if((!this.Alignment.blank()) && (this.Alignment != 'none'))
            {
                this._htmlContainer.className = 'WebImage' + this.Alignment.capitalize();
            }
            else
            {
                this._htmlContainer.className = 'WebImage';
            }
            
            // Check if a large image is to be shown on mouse over and which size it is supposed to have
            var largeImageSize = 'none';
            if(this._entity.Configuration.Large_image_size.Value == 'USE_GLOBAL_CONFIG')
            {
                largeImageSize = Site._entity.Configuration.Webimage.Large_image_size.Value.toLowerCase();
            }
            else
            {
                largeImageSize = this._entity.Configuration.Large_image_size.Value.toLowerCase();
            }
            
            // Set mouseover event handler function to show large image on mouseover if enabled
            if(this.LargeImageSize != null)
            {
                largeImageSize = this.LargeImageSize;
            }
            
            if(largeImageSize.toLowerCase() != 'none')
            {
                this._htmlContainer.style.cursor = 'pointer';
                this.LargeImageSize = largeImageSize;
                Event.observe(this._imageNode, 'click', this.InitLargeImage.bindAsEventListener(this));
            }
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'ProcessContentInformation', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    Show : function()
    {
        try
        {
            // Get the target html node
            var targetNode = $(this._target);
            // Check if the the target html node is null
            if(targetNode == null)
            {
                // Create new message box
                var msg = new WebMessage(Lingo.GetLingoItem('Error'), Lingo.GetLingoMessage('MSG_MISSING_MAIN_TARGET_AREA', 'WebImage', this.Id));
                // Show message box
                msg.Show();
                return;
            }
            
            // Append content holder to target html node
            targetNode.appendChild(this._htmlContainer);
            
            // Check if a description node is present and set its width according to the image width
            /*if( this._descNode != null)
            {
                var imgWidth = $(this._imageNode).getWidth();
                if((imgWidth != null) && (imgWidth > 0))
                {
                    this._descNode.style.width = imgWidth + 'px';
                }
            }*/
            
            this.Loaded = true;
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'Show', arguments, 'WEBIMAGE', this.Id, e, false)
        }
    },
    
    InitLargeImage : function()
    {
        if((this.LargeImageSize == null) || (this.LargeImageSize.toLowerCase() == 'none'))
        {
            return;
        }
        
        // Create modal dialogue
        this._overlay = new WebOverlay();
        
        // Get the window's scroll offset
        var scrollOffset = Helpers.GetWindowScrollOffset();
        // Calculate the value for the margin-top property
        var topMargin = -50 + scrollOffset.top;
        
        // Build container for large image
        var largeContainer = Builder.node('div', { id : this._nodeId + '_LargeContainer', style : 'top:50%;left:50%;width:50px;height:50px;margin:' + topMargin + 'px 0 0 -25px;border:1px solid #999999;position:absolute;z-index:150;background-image:url(Template/INVENIT1/Image/loadingImageWhite.gif);background-repeat:no-repeat;background-position:center center;display:none' })
        largeContainer.className = 'WebImageLarge';        
        // Append large image to document body
        document.body.appendChild(largeContainer);
        
        this._overlay.Show(0.6);
        Effect.Appear(largeContainer, { duration: 0.8 });
        
        var imageFunc = function()
        {
            // Build image node
            var imageNode = Builder.node('img', { id : this._nodeId + '_Large', src : 'IMageServer.aspx?action=getimage&id=' + this.Id + '&size=' + this.LargeImageSize, style: 'display:none' });
            // Append the image to the document body
            document.body.appendChild(imageNode);
            // Set event handlers
            Event.observe(imageNode, 'load', this.ShowLargeImage.bindAsEventListener(this));
            Event.observe(imageNode, 'click', this.HideLargeImage.bindAsEventListener(this));
        }
        
        window.setTimeout(imageFunc.bind(this), 1000);
    },
    
    ShowLargeImage : function()
    {        
        // Get the large image
        var largeImg = $(this._nodeId + '_Large');
        // Get the large image container
        var largeImgContainer = $(this._nodeId + '_LargeContainer');
        
        // Check, if elements are present
        if((largeImg == null) || (largeImgContainer == null))
        {
            this._overlay.Hide();
            return;
        }
        
        // Get the image dimesnions
        var imgDimensions = largeImg.getDimensions();
        // Get the window's scroll offset
        var scrollOffset = Helpers.GetWindowScrollOffset();
        // Calculate the value for the margin-top property
        var topMargin = ((imgDimensions.height / 2) * (-1)) + scrollOffset.top;
        // Create new effect
        new Effect.Morph(largeImgContainer, { duration:0.8, style: 'border:5px solid #999999;width:' + imgDimensions.width + 'px;height:' + imgDimensions.height + 'px;margin-top:' + topMargin + 'px;margin-left:-' + (imgDimensions.width / 2) + 'px;' });        
        
        func = function()
        {
            // Create close button
            var button = Builder.node('div', { style: 'width:15px;height:15px;top:4px;right:4px;position:absolute;background-color:#FFFFFF;z-index:800;font-weight:bold;cursor:pointer;font-size:14px;font-family:Arial;padding:0px 0px 2px 2px' });
            Event.observe(button, 'click', this.HideLargeImage.bindAsEventListener(this));
            largeImgContainer.appendChild(button);
            button.innerHTML = 'x';
            
            largeImgContainer.appendChild(largeImg);
            new Effect.Appear(largeImg, { duration: 0.4 });
        }
        
        window.setTimeout(func.bind(this), 800);
    },
    
    HideLargeImage : function()
    {
        // Get the large image container
        var largeImgContainer = $(this._nodeId + '_LargeContainer');
        
        func = function()
        {
            largeImgContainer.parentNode.removeChild(largeImgContainer);
        }
        
        window.setTimeout(func, 800);
        
        this._overlay.Hide();
        new Effect.Fade(largeImgContainer, { from: 1.0, to: 0.0, duration: 0.8 });
    }
}