﻿/*
Central manager class handling all page related operations
*/

var PageManager = Class.create();

PageManager.prototype =
{
    // Constructor
    initialize : function(piPageId)
    {
        // Set page name variable
        this.Id = piPageId;
        // Declare variable holding the page entity
        this._entity;
        
        // Declare variable holding the web entity controls
        this._webEntities;
        
        // Call RequestData function to get the xml site data fromt he webservice
        this.RequestData();
    },
    
    RequestData : function()
    {
        try
        {
            // Write Log Entry
            Logs.WriteNotification('NOTIFY_REQUESTING_DATA', 'RequestData', arguments, 'PAGE', this.Id)
            // Create input parameters for the webservice method
            var params=$H( {piHostHeader : Site.HostHeader, piPageId : this.Id} ).toQueryString();
            // Create new Ajax request
            new Ajax.Request("ISDataService.asmx/GetPageData", { 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, 'PAGE', 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, 'PAGE', 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, 'PAGE', this.Id)
                // Write Alert to the log
                Logs.WriteAlert('ALERT_LOADING_ALTERNATIVE_PAGE', 'OnDataRequestResponse', arguments, 'PAGE', this.Id);
                
                // Set page id to show the standard page for this situation
                this.Id = '712f2e87-25d1-43e3-af61-d4cee053f168';
                // Call the RequestData function to load the standard page
                this.RequestData();
                
                return;
            }
                    
            // Call AddStyleSheet function to add the page's individual css file to the document
            this.AddStyleSheet();
            // Call ProcessTemplateInformation function to build the site template
            this.ProcessStructureInformation();
            // Call ProcessContentInformation function to create entity objects/controls
            this.ProcessContentInformation();
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'OnDataRequestResponse', arguments, 'PAGE', this.Id, e, false)
        }
    },
    
    AddStyleSheet : function()
    {
        try
        {
            // Check if a style sheet link element has already been put into the document's head
            if(Site._currentPageStyleElem != null)
            {
                // Remove the link element
                Site._currentPageStyleElem.parentNode.removeChild(Site._currentPageStyleElem);
            }
            
            // Get the template folder name
            var templateFolder = Site._entity.Templateinfo.Foldername.Value;
            
            // Create link element
            Site._currentPageStyleElem = Builder.node('link', { type: 'text/css', rel: 'stylesheet', href: 'Template/' + templateFolder + '/Css/page_' + this._entity.Id + '.css' });
            
            // Append the stylesheet link to the document head
            document.getElementsByTagName("head")[0].appendChild(Site._currentPageStyleElem);
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'AddStyleSheet', arguments, 'PAGE', this.Id, e, false)
        }
    },
    
    ProcessStructureInformation : function()
    {
        try
        {
            // Check if main content area is null and write error to the log if so
            if((this._entity.Structure.Main_content == null) || (this._entity.Structure.Main_content.Value.blank()))
            {
                // Write Error to the Log
                Logs.WriteError('ERROR_MISSING_MAIN_CONTENT_AREA', 'ProcessStructureInformation', arguments, 'PAGE', this.Id)
                return;
            }
            
            // Fill site's main area with the page's main area html markup
            if($(Site._entity.Structure.Main_content.Value) != null)
            {
                $(Site._entity.Structure.Main_content.Value).innerHTML = this._entity.Structure.Main_content.Value;
            }
            
            // Iterate through auxiliary areas and fill site's auxiliary areas with the page's auxiliary areas html markup
            for( var i = 0; i < this._entity.Structure.Auxiliary_content.keys().length; i++)
            {
                var auxKey = this._entity.Structure.Auxiliary_content.keys()[i];
                var auxField = this._entity.Structure.Auxiliary_content[auxKey];
                
                // Check if the target area is present
                if(Site._entity.Structure.Auxiliary_content[auxKey] != null)
                {
                    var auxTarget = $(Site._entity.Structure.Auxiliary_content[auxKey].Value);
                    
                    if(auxTarget != null)
                    {
                        auxTarget.innerHTML = auxField.Value;
                    }
                }
                else
                {
                    // Write Error to the Log
                    Logs.WriteError('ERROR_BAD_SITE_TARGET_AREA_REFERENCE', 'ProcessStructureInformation', arguments, 'PAGE', this.Id)
                    return;
                }
            }
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'ProcessStructureInformation', arguments, 'PAGE', this.Id, e, false)
        }
    },
    
    ProcessContentInformation : function()
    {       
        try
        {
            // Create new Array for holding the content entity controls
            this._webEntities = new Array();
            // Iterate through reference fields, create a control object for each content entity, and fill _webEntities Array
            for(var i = 0; i < this._entity.Content.References.length; i++)
            {
                var entityId = this._entity.Content.References[i].Id;
                var entityType = this._entity.Content.References[i].Type;
                var entityTarget = this._entity.Content.References[i].Target;
                
                switch(entityType.toUpperCase())
                {
                    case 'WEBIMAGE':
                        var newImage = new WebImage(entityId, entityTarget);
                        this._webEntities.push(newImage);
                        newImage.Show();
                        break;
                    case 'WEBTEXT':
                        var newText = new WebText(entityId, entityTarget);
                        this._webEntities.push(newText);
                        newText.Show();
                        break;
                    case 'WEBTEASER':
                        var newTeaser = new WebTeaser(entityId, entityTarget);
                        this._webEntities.push(newTeaser);
                        newTeaser.Show();
                        break;
                    case 'WEBSUBMENU':
                        var newSubMenu = new WebSubMenu(entityId, entityTarget);
                        this._webEntities.push(newSubMenu);
                        newSubMenu.Show();
                        break;
                    case 'WEBPAGEMENU':
                        var newPageMenu = new WebPageMenu(entityId, entityTarget);
                        this._webEntities.push(newPageMenu);
                        newPageMenu.Show();
                        break;
                    case 'WEBMENU':
                        var newMenu = new WebMenu(entityId, entityTarget);
                        this._webEntities.push(newMenu);
                        newMenu.Show();
                        break;
                    case 'WEBGALLERY':
                        var newGallery = new WebGallery(entityId, entityTarget);
                        this._webEntities.push(newGallery);
                        newGallery.Show();
                        break;
                }
            }
            
            window.setTimeout(this.CheckStatus.bind(this), 800);
        }
        catch(e)
        {
            Logs.WriteException('EXCEPTION_GENERAL', 'ProcessContentInformation', arguments, 'PAGE', this.Id, e, false)
        }
    },
    
    CheckStatus : function()
    {
        StateMgr.RegisterLinks();
        StateMgr.FadeInMainArea();
        /*if((this._entity.Content != null) && (this._entity.Content.Title != null) && (this._entity.Content.Title.Value != null) && (this._entity.Content.Title.Value.toLowerCase() == 'home'))
        {
            window.setTimeout(EmbedSound, 500);
        }*/
    }
}