// Depends on:
//  AtlasCommon.js

// setup "namespaces"
Type.registerNamespace("Infragistics.UI");

if (typeof DynamicPanel_js_Parsed == 'undefined')
{
// used to dynamically change the contents of a the given element (DIV or SPAN) using AJAX 
Infragistics.DynamicPanel = function(panelId)
{
    // fields
    this.__panel = null;
    this.__loadingPanel = null;
    this.__errorPanel = null;
    this.__authPanel = null;
    this.__webClient = null;
    
    if (typeof Infragistics.DynamicPanel.__initialized == 'undefined')
    {
        Infragistics.DynamicPanel.prototype.__ensureClient = function()
        {
            if (!this.__webClient)
                this.__webClient = new Infragistics.WebClient(Infragistics.WebClient.ResponseType.Xml, false, 15000, this.__updateError);
            return typeof this.__webClient == 'object';
        }
        
        Infragistics.DynamicPanel.prototype.__updateError = function(status, params)
        {
            this.__panel.innerHTML = this.__errorPanel ? this.__errorPanel.innerHTML : '<div class="loadingPanel">There was a problem loading.  Please try again later. If the problem continues, please let us know.</div>';
            return;
        }

        Infragistics.DynamicPanel.prototype.update = function(url, checkAuthorization)
        {
            if (!this.__panel)
                return Infragistics.ExceptionHandling.handleException('Panel not initialized.');
            if (!this.__ensureClient())
                return;
            this.__panel.innerHTML = this.__loadingPanel ? this.__loadingPanel.innerHTML : '<p>Loading...</p>';
            if (checkAuthorization)
            {
                var params = new Object();
                params.targetUrl = url;
                if (url.indexOf('?') >= 0) // strip off the querystring
                    url = url.substring(0, url.indexOf('?'));
                var authUrl = Infragistics.DynamicPanel.AUTH_URL + '?' + Infragistics.DynamicPanel.AUTH_URL_KEY + '=' + url;
                authUrl = Infragistics.DynamicPanel.__getCachePreventionUrl(authUrl);
                this.__webClient.beginRequest(authUrl, Function.createDelegate(this, this.__handleAuthResult), params);
            }
            else
            {
                if (url.indexOf(Infragistics.DynamicPanel.CACHE_RETURN_URL_KEY + '=') <= 0)
                {
                    if (url.indexOf('?') <= 0)
                        url += '?';
                    else
                        url += '&';
                    url += Infragistics.DynamicPanel.CACHE_RETURN_URL_KEY + '=' + window.location.href;
                    //alert(url);
                }
                this.__webClient.beginRequest(url, Function.createDelegate(this, this.__doPanelUpdate), null);
            }
        }
        
        Infragistics.DynamicPanel.prototype.__getCDATA = function(node)
        {
            if (node && node.hasChildNodes)
            {
                for (var i = 0; i < node.childNodes.length; i++)
                    if (node.childNodes[i].nodeName == '#cdata-section')
                        return node.childNodes[i].nodeValue;
            }
            return null;
        }
        
        Infragistics.DynamicPanel.prototype.__handleAuthResult = function(response)
        {
            if (response)
            {
                var responseDoc = response.Response;
                if (!responseDoc)
                {
                    Infragistics.ExceptionHandling.handleException('No response document provided to callback for panel ' + this.__panel.id + '.');
                    this.__updateError();
                    return;
                }
                var authResultNode = responseDoc.getElementsByTagName('AuthorizationResult')[0];
                if (!authResultNode || !authResultNode.hasChildNodes)
                {
                    this.__authorizationError();
                    return;
                }
                var authResult = authResultNode.childNodes[0].nodeValue;
                 // alert(authResult);
                // alert (response.CallbackParams.targetUrl);
                if (authResult == 'true')
                    this.update(response.CallbackParams.targetUrl, false);
                else
                    this.__notAuthorized();
            }
            else
                Infragistics.ExceptionHandling.handleException('No response provided to callback for panel ' + this.__panel.id + '.');
        }
        
        Infragistics.DynamicPanel.prototype.__notAuthorized = function()
        {
            this.__panel.innerHTML = this.__authPanel ? this.__authPanel.innerHTML : '<div class="unauthorizedPanel">You\'re not authorized to access the requested information.  If you think you should have access, ensure that you are logged in and try again.  If the problem persists, please let us know.</div>';
            return;
        }
        
        Infragistics.DynamicPanel.prototype.__authorizationError = function(response)
        {
            this.__updateError();
            var responseText = response.Response.hasChildNodes ? response.Response.childNodes[0].nodeValue : '';
            Infragistics.ExceptionHandling.handleException('Invalid authorization response of ' + responseText + ' for URL ' + response.CallbackParams.targetUrl + ' on panel ' + this.__panel.id + '.');
        }

        Infragistics.DynamicPanel.prototype.__doPanelUpdate = function(response)
        {
            // alert('In __doPanelUpdate');
            if (response && typeof response.Response == 'object')
            {
                var responseDoc = response.Response;
                // get panel content
                var panel = this.__panel;
                if (panel)
                {
                    var content = this.__getCDATA(responseDoc.getElementsByTagName("Content")[0]);
                    if (!content)
                        this.__updateError();
                    else
                        panel.innerHTML = content;
                }
                // get scripts
                var scripts = responseDoc.getElementsByTagName("Script");
                if (scripts && scripts.length > 0)
                {
                    var scriptsToEval = new Array();
                    // create a script block for each script and append it to the head element
                    var head = document.getElementsByTagName("head")[0];
                    for (var i = 0; i < scripts.length; i++)
                    {
                        var src = scripts[i].getAttribute('src');
                        if (src && (src.indexOf(Infragistics.DynamicPanel.LOOSE_SCRIPT_URL) >= 0 || !Infragistics.DynamicPanel.__getScriptLoaded(src)))
                        {
                            // add script to head element for downloading
                            var script = document.createElement('script');
                            script.type = 'text/javascript';
                            script.src = src;
                            head.appendChild(script);
                            // log that the script has been loaded
                            if (src.indexOf(Infragistics.DynamicPanel.LOOSE_SCRIPT_URL) <= 0)
                                Infragistics.DynamicPanel.__addLoadedScript(src);
                        }
                    }
                }
            }
            else
                Infragistics.ExceptionHandling.handleException('No response provided to callback for panel ' + this.__panel.id + '.');
        }
        Infragistics.DynamicPanel.__initialized = true;
    }
   
    Infragistics.DynamicPanel.__loadedScripts = null;
    
    Infragistics.DynamicPanel.__addLoadedScript = function(src)
    {
        Infragistics.DynamicPanel.__initScriptTracking();
        Infragistics.DynamicPanel.__loadedScripts[Infragistics.DynamicPanel.__loadedScripts.length] = src;
    }
    
    Infragistics.DynamicPanel.__getScriptLoaded = function(src)
    {
        Infragistics.DynamicPanel.__initScriptTracking();
        if (!Infragistics.DynamicPanel.__loadedScripts)
            return false;
        for (var i = Infragistics.DynamicPanel.__loadedScripts.length-1; i >= 0; i--)
        {
            if (src.indexOf('WebResources.axd') >= 0)
            {
                // here we account for the uniquifying timestamp on web resources
                var timeStampIdx = src.indexOf('&t='); // it adds this var to prevent caching, but we can't compare w/ it
                if (timeStampIdx >= 0)
                    src = src.substring(0, timeStampIdx);
            }
            if (Infragistics.DynamicPanel.__loadedScripts[i].indexOf(src) >= 0 ||
                '/' + Infragistics.DynamicPanel.__loadedScripts[i] == src) // the extra compare is a hack to compare against root-relative scripts returned from the response
                return true;
        }
        return false;
    }
    
    Infragistics.DynamicPanel.__initializingScriptTracking = false;
    
    Infragistics.DynamicPanel.__initScriptTracking = function()
    {
        if (Infragistics.DynamicPanel.__loadedScripts)
            return; // already initialized
        if (Infragistics.DynamicPanel.__initializingScriptTracking) // not sure if this will work, but it's an attempt at synchronization
        {
            var wait;
            while (Infragistics.DynamicPanel.__initializingScriptTracking)
                wait = true;
            if (Infragistics.DynamicPanel.__loadedScripts)
                return;
        }
        try
        {
            Infragistics.DynamicPanel.__initializingScriptTracking = true;  
            var temp = new Array();            
            var docScripts = document.getElementsByTagName('script');
            if (docScripts)
            {
                for (var i = 0; i < docScripts.length; i++)
                    if (docScripts[i].src && docScripts[i].src.length > 0)
                        temp[temp.length] = docScripts[i].src;
                Infragistics.DynamicPanel.__loadedScripts = temp;
            }
        } catch (e)
        {
            Infragistics.DynamicPanel.__initializingScriptTracking = false;
        }
    }
    
    // constructor logic
    this.__panel = Infragistics.DynamicPanel.__getAndValidatePanel(panelId);
    if (this.__panel)
    {
        var loadingPanelId = this.__panel.getAttribute('loadingPanelId');
        if (loadingPanelId)
            this.__loadingPanel = Infragistics.DynamicPanel.__getAndValidatePanel(loadingPanelId);
        var errorPanelId = this.__panel.getAttribute('errorPanelId');
        if (errorPanelId)
            this.__errorPanel = Infragistics.DynamicPanel.__getAndValidatePanel(errorPanelId);
        var unauthorizedPanelId = this.__panel.getAttribute('unauthorizedPanelId');
        if (unauthorizedPanelId)
            this.__authPanel = Infragistics.DynamicPanel.__getAndValidatePanel(unauthorizedPanelId);
    }
}

// #region DynamicPanel static methods
Infragistics.DynamicPanel.__getAndValidatePanel = function(panelId)
{
    var panel = document.getElementById(panelId);
    if (!panel)
        return Infragistics.ExceptionHandling.handleException('Could not find element with id of ' + panelId + ' for dynamic panel.');
    if (!(panel.tagName && (panel.tagName == 'DIV' || panel.tagName == 'SPAN')))
        return Infragistics.ExceptionHandling.handleException('Panel ' + panelId + ' must be a DIV or SPAN.');
    return panel;
}

Infragistics.DynamicPanel.__MAX_RETRIES = 4;

Infragistics.DynamicPanel.__evalScripts = function(scriptsToEval, attemptCount)
{
    if (scriptsToEval && scriptsToEval.length)
    {
        if (!attemptCount)
            attemptCount = 1;
        var newScripts = new Array();
        for (var i = 0; i < scriptsToEval.length; i++)
        {
            if (!scriptsToEval[i]) 
                continue;
            try
            {
                eval(scriptsToEval[i]);
            }
            catch (e)
            {
                if (attemptCount < Infragistics.DynamicPanel.__MAX_RETRIES) // set up the script to try again--assuming a required script hasn't finished loading
                    newScripts[newScripts.length] = scriptsToEval[i];
                Infragistics.ExceptionHandling.handleException('Could not evaluate script: ' + scriptsToEval[i], e);
            }
        }
        if (newScripts.length > 0 && attemptCount < Infragistics.DynamicPanel.__MAX_RETRIES)
            window.setTimeout(function() { Infragistics.DynamicPanel.__evalScripts(newScripts, attemptCount+1);}, 1000);
    }
}

Infragistics.DynamicPanel.linkClicked = function(link, doNotTrack)
{
    var navUrl = link.getAttribute('navUrl');
    var contentId = link.getAttribute('panelId');
    if (contentId)
    {
        if (!doNotTrack) // track the click
            Infragistics.DynamicPanel.__trackUrl(link, navUrl)    
        if (navUrl)
        {
            if (link.getAttribute('preventCaching') == 'True')
                navUrl = Infragistics.DynamicPanel.__getCachePreventionUrl(navUrl);
            Infragistics.DynamicPanel.update(contentId, navUrl, link.getAttribute('checkAuthorization') == 'True');
        }
    }
    return false;
}

Infragistics.DynamicPanel.__trackUrl = function(link, navUrl)
{
    try
    {
        if (link.href)
        {
            navUrl = link.href; // prefer the normal URL rather than the partial rendering one
            // now try to get the relative path
            var protocolIdx = navUrl.indexOf('://');
            if (protocolIdx >= 0)
            {
                var hostIdx = navUrl.indexOf('/', protocolIdx + 3);
                if (hostIdx >= 0)
                    navUrl = navUrl.substr(hostIdx);
            }
        }
        if (navUrl && typeof urchinTracker != 'undefined')
        {
            urchinTracker(navUrl); // track that this URL was clicked
            //alert('Tracking: ' + navUrl);
        }
    } catch(e) {} 
}

Infragistics.DynamicPanel.__getCachePreventionUrl = function(url)
{
    var dt = new Date();
    dt = dt.getFullYear().toString() + dt.getMonth().toString() + dt.getDay().toString() + 
        dt.getHours().toString() + dt.getMinutes().toString() + dt.getSeconds().toString() + dt.getMilliseconds().toString();
    return url + (url.indexOf('?') > 0 ? '&' : '?') + 't=' + dt;
}

Infragistics.DynamicPanel.update = function(panelId, newUrl, checkAuthorization)
{
    var panel = Infragistics.DynamicPanel.__getAndValidatePanel(panelId);
    if (panel)
    {
        if (typeof panel.dynamicPanel == 'undefined')
            panel.dynamicPanel = new Infragistics.DynamicPanel(panelId);
        panel.dynamicPanel.update(newUrl, checkAuthorization);
    }
}

Infragistics.DynamicPanel.redirectFromFrame = function(url)
{
    // first try to redirect top frame
    if (window.top)
    {
        try
        {
            window.top.location.href = url;
            return false;
        } catch (e) {}
    }
    // if the above fails, redirect current frame
    window.location.href = url;
    return false;
}

Infragistics.DynamicPanel.switchTabMenuKey = function(tabKey)
{
    if (window.top)
    {
        try // switching the tab in the top frame
        {
            if (navigator.userAgent.indexOf('Firefox') != -1)
            {
                // there's a bug in FF that makes using a timeout necessary.
                // more at http://the-stickman.com/web-development/javascript/iframes-xmlhttprequest-bug-in-firefox/
                window.top.setTimeout(function() { window.top.ig_switchByTabKey(tabKey); }, 50);
            }
            else
                window.top.ig_switchByTabKey(tabKey);
        } catch (e) 
        {
            Infragistics.ExceptionHandling.handleException('Could not switch top frame to tab key \'' + tabKey + '\'.', e);
        }
    }    
}
// #endregion DynamicPanel static methods

Infragistics.DynamicPanel.AUTH_URL = '/ClientAuthorize.axd';
Infragistics.DynamicPanel.AUTH_URL_KEY = 'authUrl';
Infragistics.DynamicPanel.LOOSE_SCRIPT_URL = '/LooseScriptHandler.axd';
Infragistics.DynamicPanel.CACHE_RETURN_URL_KEY = 'cacheReturnUrl';
Infragistics.DynamicPanel.THEME_IMAGE_PATH = '/App_Themes/default/images/';
DynamicPanel_js_Parsed = true;
}
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
