// This script was originally intended as a supplement to Atlas, but I decided to rip out atlas and only use the few functions I ended up needing.

// setup "namespaces"
Type.registerNamespace("Infragistics.UI");

// Script dependencies:
if (typeof AtlasCommon_js_Parsed == 'undefined')
{

var DEBUG = false;
var LOGGING = false;
var LOGGING_URL = '/JavascriptLogging.ashx';

// #region WebClient
// serves as a basic wrapper for XML HTTP functionality
// note this class is not thread safe; subsequent requests will abort previous ones if they
// have not completed
Infragistics.WebClient = function(responseType, disposeOnComplete, timeout, errorCallback)
{
    // define fields
    this.__http = null;
    this.__callback = null;
    this.__callbackParams = null;
    this.__target = null;
    this.__responseType = null;
    this.__timeout = timeout && !isNaN(timeout) ? parseInt(timeout) : 15000;
    this.__timeoutTimer = null;
    this.__disposeOnComplete = disposeOnComplete == true;
    this.__errorCallback = errorCallback;
    
    // define methods
    if (typeof Infragistics.WebClient.__initialized == 'undefined')
    {
        // only target is required
        // return value is the response text
        Infragistics.WebClient.prototype.request = function(target, action, values, responseType)
        {
            return this.__doRequest(target, action, values, false, null, null, responseType);
        }

        // only target is required
        // callback signature is: void name(responseObj)
        // response obj is an instance of Infragistics.WebClient.Response, which has .Response, .Headers, and .CallBackParams
        // callBackParams can be used to pass extra data with the call to be passed back to the callback (helps to uniquify 
        // callbacks when multiple async requests are processed on the same WebClient)
        Infragistics.WebClient.prototype.beginRequest = function(target, callback, callbackParams, action, values, responseType)
        {
            this.__doRequest(target, action, values, true, callback, callbackParams, responseType);
        }

        Infragistics.WebClient.prototype.__processResponse = function()
        {
            if (this.__http.readyState == 4)
            {
                this.__clearTimer();
                try
                {
                    if (this.__http.status != 200)
                    {
                        this.__responseError();
                        if (this.__http.status != 0) // don't handle status 0s; usually caused by aborts
                            Infragistics.ExceptionHandling.handleException('Request to ' + this.__target + ' failed with status of ' + this.__http.status + '.');
                        return;
                    }
                    if (this.__callback)
                    {
                        var response = this.__getResponse();
                        var headers = this.__http.getAllResponseHeaders();
                        this.__callback(new Infragistics.WebClient.Response(response, headers, this.__callbackParams));
                    }
                } catch (e)
                {
                    this.__responseError();
                    Infragistics.ExceptionHandling.handleException('Error processing response.', e);
                }
                finally
                {
                    if (this.__disposeOnComplete)
                        this.dispose();
                }
            }
        }
        
        Infragistics.WebClient.prototype.__responseError = function(status, params)
        {
            if (this.__errorCallback)
            {
                try
                {
                    var status = this.__http.status;
                    var params = this.__callbackParams;
                    this.__errorCallback(status, params);
                } catch (e) {} // ignore error callback errors
            }
        }        
        
        Infragistics.WebClient.prototype.__clearTimer = function()
        {
            if (this.__timeoutTimer)
            {
                window.clearTimeout(this.__timeoutTimer);
                this.__timeoutTimer = null;
            }
        }
        
        Infragistics.WebClient.prototype.__getResponse = function()
        {
            switch (this.__responseType)
            {
                case Infragistics.WebClient.ResponseType.Xml:
                    return this.__http.responseXML;
                default:
                    return this.__http.responseText;
            }
        }
        
        Infragistics.WebClient.prototype.__doRequest = function(target, action, values, async, callback, callbackParams, responseType)
        {
            if (!this.__http)
            {
                Infragistics.ExceptionHandling.handleException('No XmlHTTPRequest object.');
                return;
            }
            try
            {
                if (!action)
                    action = 'GET';
                if (!async)
                    async = false;
                this.__http.abort(); // end any previous request on this object
                this.__target = target;
                if (responseType)
                    this.__responseType = responseType;
                // open the connection
                if (async)
                {   
                    // setup the callback
                    this.__callback = callback;
                    this.__callbackParams = callbackParams;
                    this.__http.onreadystatechange = Function.createDelegate(this, this.__processResponse);
                }
                else
                {
                    this.__callback = null;
                    this.__callbackParams = null;
                }
                // setup a timeout
                this.__timeoutTimer = window.setTimeout(Function.createDelegate(this, function() { this.__responseError(); this.__http.abort(); Infragistics.ExceptionHandling.handleException('Request timed out for ' + target + '.');}), this.__timeout);
                // open the connection
                this.__http.open(action, target, async);
                // send the request
                this.__http.send(values);
                // if not async, return response
                if (!async)
                {
                    this.__clearTimer();
                    return new Infragistics.WebClient.Response(this.__getResponse(), this.__http.getAllResponseHeaders(), null);
                }
            } catch(e)
            {
                alert(e.message);
                this.__responseError(); 
                this.__http.abort();
                Infragistics.ExceptionHandling.handleException('Error processing request.', e);
            }
        }
        
        Infragistics.WebClient.prototype.dispose = function()
        {
            this.clearTimer();
            if (this.__http)
                this.__http.abort();
            this.__http = null;
        }
        
        Infragistics.WebClient.__initialized = true;
    }
    
    // constructor logic
    this.__http = Infragistics.WebClient.createXMLHttpRequest();
    this.__responseType = responseType ? responseType : Infragistics.WebClient.ResponseType.Text;
}

// #region WebClient static methods
Infragistics.WebClient.createXMLHttpRequest = function() 
{
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
    try { return new XMLHttpRequest(); } catch(e) {}
    alert('This page cannot function properly in your browser.  Please let us know if you think it should.');
    return null;
}

Infragistics.WebClient.getText = function(target, callback, callbackParams)
{
    return Infragistics.WebClient.__singleRequest(target, callback, callbackParams, Infragistics.WebClient.ResponseType.Text);
}

Infragistics.WebClient.getXml = function(target, callback, callbackParams)
{
    return Infragistics.WebClient.__singleRequest(target, callback, callbackParams, Infragistics.WebClient.ResponseType.Xml);
}

Infragistics.WebClient.__singleRequest = function(target, callback, callbackParams, type)
{
    var client = new Infragistics.WebClient(type, true);
    if (callback)
        client.beginRequest(target, callback, callbackParams);
    else
        return client.request(target);
    return null;
}
// #endregion WebClient static methods


// response type enum
Infragistics.WebClient.ResponseType = function() {};
Infragistics.WebClient.ResponseType.Text = 'Text';
Infragistics.WebClient.ResponseType.Xml = 'Xml';

// response type
Infragistics.WebClient.Response = function(response, headers, callbackParams)
{
    this.Response = response;
    this.Headers = headers;
    this.CallbackParams = callbackParams;
}
// #endregion WebClient

// #region Logger
Infragistics.Logging = function() {}
Infragistics.Logging__loggerClient = null;
Infragistics.Logging__getLoggerClient = function()
{
    if (!Infragistics.Logging.__loggerClient)
        Infragistics.Logging.__loggerClient = new Infragistics.WebClient();
    return Infragistics.Logging.__loggerClient;
}
Infragistics.Logging.log = function(message)
{
    try
    {
        if (LOGGING && LOGGING_URL)
        {
            var logger = Infragistics.Logging.__getLoggerClient();            
            if (logger)
                logger.beginRequest(LOGGING_URL, null, null, 'POST', 'sourceUrl=' + window.location.href + '&message=' + message);
        }
    } catch(e) {}
}
// #endregion Logger

// #region ExceptionHandling
Infragistics.ExceptionHandling = function() {}
// use this to handle exceptions
// innerEx is optional
// if debug is enabled, message will display; otherwise a general message will display
// will log the message and exception details
Infragistics.ExceptionHandling.handleException = function(message, innerEx)
{
    try
    {
        if (innerEx)
            message += '\n\nInner Exception:\n' + Infragistics.ExceptionHandling.toString(innerEx)
        if (DEBUG)
            alert(message);
        else
            alert('There is a problem with this page.  Please let us know if it continues.');
        Infragistics.Logging.log(message);
    } catch(e)
    {
    }
    finally
    {
        return false;
    }
}
Infragistics.ExceptionHandling.toString = function(ex)
{
    return 'Name: ' + ex.name + '\nNumber: ' + innerEx.number + '\nMessage: ' + innerEx.message;
}
// #endregion ExceptionHandling


// below are select atlas functions

Sys.UI.Control.getLocation = function(element) 
{
    // Ambrose - 10/9/06 - Modified to use built-in methods for getting bounds as the Atlas version didn't account for centering
    if (typeof document.getBoxObjectFor != 'undefined')
        return document.getBoxObjectFor(element);
    else
    {
        var offsetX = 0;
        var offsetY = 0;
        var parent;
        
        for (parent = element; parent; parent = parent.offsetParent) {
            if (parent.offsetLeft) {
                offsetX += parent.offsetLeft;
            }
            if (parent.offsetTop) {
                offsetY += parent.offsetTop;
            }
        }
        return { x: offsetX, y: offsetY, width: element.offsetWidth, height: element.offsetHeight };
    }
}

Sys.UI.Control.getBounds = function(element) 
{
    return Sys.UI.Control.getLocation(element); // avoiding duplication w/o changing interface
}

Sys.UI.Control.setLocation = function(element, position) {
    element.style.left = position.x + "px";
    element.style.top = position.y + "px";
}

Function.createDelegate = function(instance, method) 
{
    return function() { return method.apply(instance, arguments); }
}


// this is a custom add on to atlas 
Sys.UI.Control.getWindowDimensions = function()
{
    var width = 0, height = 0, left = 0, top = 0, right = 0, bottom = 0;
    // get width/height
    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      width = window.innerWidth;
      height = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      width = document.documentElement.clientWidth;
      height = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      width = document.body.clientWidth;
      height = document.body.clientHeight;
    }

    // get left/top
    if( typeof( window.pageYOffset ) == 'number' ) {
      //Netscape compliant
      top = window.pageYOffset;
      left = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      //DOM compliant
      top = document.body.scrollTop;
      left = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      //IE6 standards compliant mode
      top = document.documentElement.scrollTop;
      left = document.documentElement.scrollLeft;
    }
    right = left + width;
    bottom = top + height;
    
    return {left: left, top: top, right: right, bottom: bottom, width: width, height: height};
}

var __sharedQuery = null;

Infragistics.QueryString = function(q) 
{
    this.__keys = null;

    if (!q)
        q = window.location.search;
    if (q.length > 1) 
    {
        q = q.substring(1, q.length);
        this.keyValuePairs = q.split("&");
    }
    else
        this.keyValuePairs = new Array(0);
        
    if (typeof Infragistics.QueryString.__initialized == 'undefined') // prevent method recreation
    {
        Infragistics.QueryString.prototype.getKeyValuePairs = function() { return this.keyValuePairs; }

        Infragistics.QueryString.prototype.getValue = function(key) 
        {
            for (var j = this.keyValuePairs.length-1; j > -1; j--) 
            {
                var pair = this.keyValuePairs[j].split("=");
                if (pair[0] == key)
                    return pair[1];
            }
            return false;
        }
        
        Infragistics.QueryString.prototype.getKeys = function() 
        {
            if (!this.__keys)
            {
                this.__keys = new Array(this.getLength());
                for (var j = this.keyValuePairs.length-1; j > -1; j--) 
                    this.__keys[j] = this.keyValuePairs[j].split("=")[0];
            }
            return this.__keys;
        }
        
        Infragistics.QueryString.prototype.toString = function()
        {
            return '?' + this.keyValuePairs.join('&');
        }
        
        Infragistics.QueryString.prototype.replace = function(key, newValue, replaceInHistory)
        {
            var index = this.keyValuePairs.length;
            var newDiff = true;
            for (var j = index-1; j > -1; j--)
            {
                var pair = this.keyValuePairs[j].split("=");
                if (pair[0] == key)
                {
                    index = j;
                    newDiff = (newValue != pair[1]);
                    break;
                }
            }
            if (newDiff)
            {
                this.keyValuePairs[index] = key + "=" + newValue;
                if (replaceInHistory)
                {
                    var newLocation = encodeURI(document.location.href.substring(0, document.location.href.indexOf('?')) + this.toString());
                    // alert(newLocation);
                    document.location.replace(newLocation);
                }
            }
        }
        
        Infragistics.QueryString.prototype.getLength = function() { return this.keyValuePairs.length; } 
        
        Infragistics.QueryString.__initialized = true;
    }
}

Infragistics.QueryString.getShared = function()
{
    if (!__sharedQuery)
        __sharedQuery = new Infragistics.QueryString(); 
    return __sharedQuery;
}

DemoMenuClick = function(menuId, itemId)
{
    var item = igmenu_getItemById(itemId);
    if (item)
    {
        var tag = item.getTag();
        if (tag == null)
            tag = '';
        
        var demoInfo = ig_getToasterById('DemoInfoPanel');
        if (demoInfo)
        {
            demoInfo.setInfo(item.getText(), tag);
            demoInfo.collapseContent(0);
        }
    }
}

AtlasCommon_js_Parsed = true;
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
