﻿// JScript File


/**********************************************
*   JS for MCUSAPlusPanel
***********************************************/

// function given the ID of a MCUSAPlusPanel, if visible sets it to invisible
// and vice versa.
function changePlusPanelDisplay(ID)
{
    var x = document.getElementById(ID);

    // switches between display and no display
    if (x.style.display == 'none')
    {
        x.style.display = 'block';
        document.images[ID + 'Img'].src = 'images/minus9x9.gif';
    }
    else
    {
        x.style.display = 'none';
        document.images[ID + 'Img'].src = 'images/plus9x9.gif';
    }

}

/**********************************************
*   JS for MCUSAExpandGroup
***********************************************/

// function given the ID of a MCUSAPlusPanel, if visible sets it to invisible
// and vice versa.
function changeExpandGroupDisplay(ID)
{
    var x = document.getElementById(ID + 'TBody');

    // switches between display and no display
    if (x.style.display == 'none')
    {
        x.style.display = 'block';
        document.images[ID + 'TBodyImg'].src = 'images/ArrowDown.gif';
    }
    else
    {
        x.style.display = 'none';
        document.images[ID + 'TBodyImg'].src = 'images/ArrowRight.gif';
    }
}

/**********************************************
*   JS for OptionNotePanel
***********************************************/

function changeNotePanelDisplay(ID)
{
    // switches between display and no display
    var x = document.getElementById(ID + 'Panel');

    if (x.style.display == 'none')
    {
        var tas = document.getElementsByName('OptionNotesPanel');
        for (i = 0; i < tas.length; i++)
        {
            tas[i].style.display = 'none';
        }

        x.style.display = 'block';
        var ta = document.getElementById(ID + 'TextArea');
        ta.focus();

        // if off the right side of the screen display on left.
        /*
        if(window.innerWidth)
        {
        var windowWidth = window.innerWidth;
        }
        else
        {
        var windowWidth = document.documentElement.offsetWidth;
        }
        
        if((findPosX(x) + x.offsetWidth) > windowWidth)
        {
        x.style.position = 'absolute';
        x.style.right = '0px';
        x.style.zIndex = '1000';
        }*/
    }
    else
    {
        x.style.display = 'none';
    }

    changeNotePanelBorder(ID);

}

function changeNotePanelBorder(ID)
{
    // sets border of image if TextArea has text
    ta = document.getElementById(ID + 'TextArea');
    var img;


    // if textarea has stuff in it
    if (ta.value.length > 0)
    {

        // get image object & set border style
        img = document.getElementById(ID + 'Img');
        img.style.border = 'solid 1px red';
        img.style.padding = '0px';
    }
    else
    {
        img = document.getElementById(ID + 'Img');
        img.style.border = 'solid 0px white';
        img.style.padding = '1px;';
    }
}

/**********************************************
*   JS for ListPanel height
***********************************************/
function changeListPanelHeight(listPanelID, filterPanelID)
{
    // minimum panel height
    var minHeight = 50;

    var panel = document.getElementById(listPanelID);
    var filter = document.getElementById(filterPanelID);
    if (window.innerHeight)
    {
        var panelHeight = window.innerHeight;
        var filterHeight = filter.offsetHeight;
    }
    else
    {
        var panelHeight = document.documentElement.offsetHeight;
        var filterHeight = 25;
    }

    var panelY = findPosY(panel);

    panelHeight -= findPosY(panel);
    panelHeight -= filterHeight;
    panelHeight -= 20;

    // sets minimum panel height
    if (panelHeight < minHeight)
    {
        panelHeight = minHeight;
    }

    // for testing purposes
    /*
    var jsTest = document.getElementById('jsText');
    jsTest.innerHTML = findPosY(panel);
    */

    panel.style.height = panelHeight + 'px';
}

/**********************************************
*   JS for Generic positioning
***********************************************/
function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
        while (1)
    {
        curtop += obj.offsetTop;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function findPosX(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
        while (1)
    {
        curtop += obj.offsetLeft;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.y)
        curtop += obj.x;
    return curtop;
}

/**************************************
*   JS for Numeric TextBox
**************************************/

function FilterNumeric(e)
{
    var re;
    var keyNum = GetKeyNumberClicked(e);
    var ch = String.fromCharCode(keyNum);

    if (keyNum < 32)
    {
        return;
    }

    if ((keyNum <= 57) && (keyNum >= 48))
    {
        if (!e.shiftKey)
        {
            return;
        }
    }
    if ((ch == '-') || (ch == '.'))
    {
        return;
    }

    e.returnValue = false;
}

/**************************************
*   JS for TextAreas to set their maximum lengths
**************************************/
function doKeypress(control,e)
{
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
    if (maxLength && value.length > maxLength - 1)
    {
        e.returnValue = false;
        maxLength = parseInt(maxLength);
    }
}

function doBeforePaste(control,e)
{
    maxLength = control.attributes["maxLength"].value;
    if (maxLength)
    {
        e.returnValue = false;
    }
}

function doPaste(control,e)
{
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
    if (maxLength)
    {
        e.returnValue = false;
        maxLength = parseInt(maxLength);
        var oTR = control.document.selection.createRange();
        var iInsertLength = maxLength - value.length + oTR.text.length;
        var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
        oTR.text = sData;
    }
}

/**************************************
*   JS for Disabling all buttons that are stored in an array stored on the page.
**************************************/
function DisableButtons(clickedbtnId)
{
    var clickedbtn = $get(clickedbtnId);
    if (MCUSADisableOnClickBtnDisableOnClickButtonsArray != null)
    {
        for (var i = 0; i < MCUSADisableOnClickBtnDisableOnClickButtonsArray.length; i++)
        {
            var btn = window.document.getElementById(MCUSADisableOnClickBtnDisableOnClickButtonsArray[i]);
            if (btn != null)
            {
                // disable all buttons except the one that has been clicked
                // this is handled in the DisableLinkButton method
                if (btn != clickedbtn)
                {
                    //btn.disabled = true;
                    btn.removeAttribute("href");
                    btn.setAttribute("disabled", "disabled");
                    btn.style.backgroundColor = "E8E8E8";
                    btn.style.cursor = "default";
                    btn.style.color = "DarkGray";
                }
            }
        }
    }  
}

// disable a single link button
// if a custom flag has not been set, then set the disable attributes
// and set the flag that it has been clicked
// then if they click again, check the flag, and remove the href attribute
// which prevents the control from being clicked a second time
function DisableLinkButton(linkButtonId)
{
    var linkButton = $get(linkButtonId);
    var hasBeenClicked = false;

    if (Sys.Browser.agent == Sys.Browser.InternetExplorer)
    {
        if (linkButton.hasBeenClicked != null)
            hasBeenClicked = true;
    }
    else
    {
        if (linkButton.hasAttribute('hasBeenClicked'))
            hasBeenClicked = true;
    }
    
    if (!hasBeenClicked)
    {
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer)
            linkButton.hasBeenClicked = true;
        else
            linkButton.setAttribute('hasBeenClicked', true);
        
        //linkButton.setAttribute("disabled", "disabled");
        linkButton.style.color = "DarkGray";
        linkButton.style.backgroundColor = "E8E8E8";
        linkButton.style.cursor = "default";
    }
    else
    {
        linkButton.removeAttribute("href");
    }
}

function SetButtonStyleNotPressed(btn)
{
    if (btn != null)
    {
        btn.style.borderStyle = "solid";
        btn.style.borderWidth = "1px";
        btn.style.borderColor = "#D3D3D3"
        btn.style.cursor = "pointer";
    }
}

/**************************************
* JS that formats a given string as a currency without a $ or ",".
* Found this online
**************************************/
function formatCurrency(num)
{
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) +
            num.substring(num.length - (4 * i + 3));

    return (((sign) ? '' : '-') + num + '.' + cents);
}

/**************************************
* JS that returns the name of the current page.
**************************************/
function GetPageName()
{

    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    return sPage;
}

// set the last focus id to be the id of the given control
function SetLastFocusId(control)
{
    try { document.getElementById('__LASTFOCUS').value = control.id } catch (e) { }
}

// focus at the end of the textbox
function FocusOnEndOfTextbox(textboxControl)
{
    if (textboxControl.createTextRange)
    {
        var FieldRange = textboxControl.createTextRange();
        FieldRange.moveStart('character', textboxControl.value.length);
        FieldRange.collapse();
        FieldRange.select();
    }
}

// get the next control down the hierarchy of the given sender
// this will wrap around back to the beginning of the control tree
// returns null if no control is found
function GetNextControlDown(senderId)
{
    var sender = $get(senderId);
    var senderIndex = -1;
    for (i = 0; i < sender.form.elements.length; i++)
    {
        if (sender.id == sender.form.elements[i].id)
        {
            senderIndex = i;
            break;
        }
    }
    for (i = senderIndex + 1; i < sender.form.elements.length; i++)
    {
        if (sender.form.elements[i].type != "hidden" && sender.form.elements[i].type != "submit")
            return sender.form.elements[i];
    }
    for (i = 0; i < sender.form.elements.length; i++)
    {
        if (sender.form.elements[i].type != "hidden" && sender.form.elements[i].type != "submit")
            return sender.form.elements[i];
    }
    return null;
}

/**********************************************
*   JS for AutoResize DropDownList Control
***********************************************/

function ResetDdnWidth(object)
{
    if (object.originalWidth != "")
    {
        //object.style.position = "";
        object.style.width = object.originalWidth;
        object.originalWidth = "";
    }
}

function RearrangeDdnWidth(object)
{
    var objectPosition = fGetXY(object);
    if (object.originalWidth == "")
    {
        //        object.style.position = "absolute";
        //        object.style.top = objectPosition[1];
        //        object.style.left = objectPosition[0];
        object.originalWidth = object.style.width;
        object.style.width = "";
        object.focus();
    }
}

function fGetXY(aTag)
{
    var p = [0, 0];
    while (aTag != null)
    {
        p[0] += aTag.offsetLeft;
        p[1] += aTag.offsetTop;
        aTag = aTag.offsetParent;
    }
    return p;
}
// END JS for AutoResize DropDownList

// Get the heigth of the page
function GetPageHeight()
{
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

// get the width of the page
function GetPageWidth()
{
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return myWidth;
}

// Get the css property for the given element
function GetCssProperty(Element, CssProperty)
{
    if (Element != null)
    {
        if (Element.currentStyle)
        {
            var convertToCamelCase = CssProperty.replace(/\-(.)/g, function(m, l) { return l.toUpperCase() });
            return Element.currentStyle[convertToCamelCase];
        }
        else if (window.getComputedStyle)
        {
            var elementStyle = window.getComputedStyle(Element, "");
            return elementStyle.getPropertyValue(CssProperty);
        }
    }
    else
        return null;
}

// moves the given panelid to the right of the given sender
// and up from the given sender
// choose whether or not to use the offset parent bounds for positioning
// this is for some situations where positions you have multiple floating popups
function PositionPanelNextToSenderUseParentOffset(senderId, panelId, offsetBottom, offsetRight, useOffsetParentBounds)
{
    var panelControl = $get(panelId);
    if (panelControl != null)
    {
        var senderControl = $get(senderId);
        var senderBounds = Sys.UI.DomElement.getBounds(senderControl);

        var offsetX = 0;
        var offsetY = 0;

        if (useOffsetParentBounds)
        {
            var offsetParentBounds = Sys.UI.DomElement.getBounds(panelControl.offsetParent);
            offsetX = offsetParentBounds.x;
            offsetY = offsetParentBounds.y;
        }

        Sys.UI.DomElement.setLocation(panelControl, senderBounds.x + senderBounds.width + offsetRight - offsetX, senderBounds.y - senderBounds.height - offsetBottom - offsetY);
    }
}

// moves the given panelid to the right of the given sender
// and up from the given sender
function PositionPanelNextToSender(senderId, panelId, offsetBottom, offsetRight)
{
    PositionPanelNextToSenderUseParentOffset(senderId, panelId, offsetBottom, offsetRight, false);
}

//Centers the panel in any given screen size.
//screenW and screenH are the width and the height of the screen respectively.
//For older browsers, window.screen is not known, therefore we default the
//width and the height of the screen to be 640 and 480 respectively.
//When the width and height of the screen has been calculated, we subtract
//the width and the height of the panel to be centered from the screen width and height, and divide
//by two to center it.
function SetPanelToCenterUseParentOffset(panelId, useParentOffset)
{
    var panelControl = $get(panelId);
    if (panelControl != null)
    {
        var screenW = 640;
        var screenH = 480;
        var x, y;
        var panelBounds = Sys.UI.DomElement.getBounds(panelControl);
        if (parseInt(navigator.appVersion) > 3)
        {
            screenW = document.documentElement.clientWidth;
            screenH = document.documentElement.clientHeight;
        }
        x = parseInt((screenW - panelBounds.width) / 2);
        y = parseInt((screenH - panelBounds.height) / 2);

        var offsetX = 0;
        var offsetY = 0;
        if (useParentOffset)
        {
            var offsetParentBounds = Sys.UI.DomElement.getBounds(panelControl.offsetParent);
            offsetX = offsetParentBounds.x;
            offsetY = offsetParentBounds.y;
        }

        Sys.UI.DomElement.setLocation(panelControl, x - offsetX, y - offsetY);
    }
}

function SetPanelToCenter(panelId)
{
    SetPanelToCenterUseParentOffset(panelId, false);
}

//Sets the focus of the control whose Id is controlId.
function SetFocus(controlId)
{
    var control = $get(controlId);
    control.focus();
}

// this will show or hide the given panel id.
function ShowPanelPopup(panelId, show)
{
    var pnlFormLetter = $get(panelId);
    if (show)
        pnlFormLetter.style.visibility = "visible";
    else
        pnlFormLetter.style.visibility = "hidden";
}

// this method calls a web service for the given webservice at the given path.
// it passes into that web service the primary key value and the user control name
// the output of this call is the resulting HTML and given result panel.
function CallRolloverWebService(path, webservice, primaryKeyValue, userControlName, resultPanelId)
{
    var wRequest = Sys.Net.WebServiceProxy.invoke
            (path, webservice, false, { "primaryKeyValue": primaryKeyValue, "userControlName": userControlName },
            RolloverWebServiceCompleted, null, resultPanelId);
}

// this is called when the CallRolloverWebService is completed
// set the results to be the inner html of the result panel
// the user context variable contains the result panel id
// result is a varaible containing HTML
function RolloverWebServiceCompleted(result, userContext, methodName)
{
    var resultPanel = $get(userContext);
    resultPanel.innerHTML = result;
}

// sets the given panel's inner HTML to blank if the cursor is not 
// inside the given sender.
function SetPanelBlankIfMouseNotOnSender(panelId, senderId, event)
{
    var x = event.x;
    var y = event.y;

    var panel = $get(panelId);
    var sender = $get(senderId);

    // debug code
    // alert("x: " + x + " senderBoundsX: " + senderBounds.x + "senderWidth: " + senderBounds.width + " y: " + y + " senderBoundsY: " + senderBounds.y + " senderHeight: " + senderBounds.height);

    // we only care about this if the panel is visible
    if (panel.style.visibility == 'visible')
    {
        // get the bounds and see if the x and y are inside the sender
        // if not, then set the panel's inner HTML to blank
        var senderBounds = Sys.UI.DomElement.getBounds(sender);
        if ((x < senderBounds.x || x > senderBounds.x + senderBounds.width) &&
            (y < senderBounds.y || y > senderBounds.y + senderBounds.height))
        {
            panel.innerHTML = '';
            panel.style.visibility = 'hidden';
        }
    }
}

/* ***** AUTOCOMPLETE UC SCRIPTS ***** */

// this returns the textbox element that the behavior is bound to
function AutoComplete_GetAutoCompleteTextBox(behaviorId)
{
    var behavior = $find(behaviorId);
    return behavior._element;
}

// when the auto complete item is selected, call another web service to
// update the dataset with the new unit value
// the value is an array.  the first element is the unit id and the second is the cached object name
// when the web service succeeds, fire a postback on the hidden link button so that this user control
// can fire it's "UnitSelected" event
function AutoComplete_ItemSelected(source, eventArgs)
{
    var value = eventArgs.get_value();

    var txtAutoComplete = AutoComplete_GetAutoCompleteTextBox(source.get_id());
    txtAutoComplete.setAttribute('ItemSelected', true);

    var hfResultsValue = document.getElementById(txtAutoComplete.getAttribute('SelectedValueId'));
    hfResultsValue.value = value;

    AutoComplete_ExecuteItemSelectedClientScript(txtAutoComplete, value);

    if (txtAutoComplete.getAttribute('OnSelectedWebService') != "")
    {
        AutoComplete_FireOnSelectedWebService(value, txtAutoComplete);
    }
    else
    {
        if (txtAutoComplete.getAttribute('PostBackOnSelected') != "false")
        {
            __doPostBack(txtAutoComplete.getAttribute('PostBackLinkButtonId'), '');
        }
    }
}

// executes any custom item selected client script
// this will take the given client script and add a parameter at the beginning that will be the selected
// value. if there are existing parameters, these will be maintained but the selected value will be at the beginning of the list
// this will be for all methods in the client script string (so that the user can pass in multiple methods separated by ;
function AutoComplete_ExecuteItemSelectedClientScript(txtAutoComplete, value)
{
    var itemSelectedClientScript = txtAutoComplete.getAttribute('ItemSelectedClientScript');
    if (itemSelectedClientScript != '')
    {
        var scripts = new Array();

        // break the scripts into an array and then parse each script
        // if there isn't a ; then there is only 1 script so just add that one script to the array
        if (itemSelectedClientScript.indexOf(';') == -1)
            scripts[0] = itemSelectedClientScript;
        else
            scripts = itemSelectedClientScript.split(';');

        var newScripts = new Array();
        for (var i = 0; i < scripts.length; i++)
        {
            var scriptTemp = scripts[i];
            var firstParen = scriptTemp.indexOf('(');
            var closingParen = scriptTemp.indexOf(')');
            var firstComma = scriptTemp.indexOf(',');

            if (firstParen != -1 && closingParen != -1) // there are parens
            {
                var frontOfParen = scriptTemp.substring(0, firstParen);
                var afterParen = scriptTemp.substring(firstParen + 1);

                if (firstParen + 1 == closingParen) // then there's nothing between the parenthesis
                {
                    scriptTemp = frontOfParen + "('" + value + "')";
                }
                else // insert the value and then dump everthing after
                {
                    scriptTemp = frontOfParen + "('" + value + "'," + afterParen;
                }
            }
            else // no parens
                scriptTemp += "('" + value + "')";

            newScripts[i] = scriptTemp;
        }

        // fire the scripts joined by ; and ending in a ;
        setTimeout(newScripts.join(';') + ';', 1);
    }
}

// when the completion list is shown, set the width to be the completion width
// if a completion width has been set
function AutoComplete_ClientShown(source, eventArgs)
{
    var txtAutoComplete = AutoComplete_GetAutoCompleteTextBox(source.get_id());
    var behavior = AutoComplete_GetBehaviorFromArray(txtAutoComplete);
    var textBoxBounds = Sys.UI.DomElement.getBounds(txtAutoComplete);

    if (txtAutoComplete.getAttribute('CompletionWidth') != "")
    {
        behavior._completionListElement.style.width = txtAutoComplete.getAttribute('CompletionWidth');

        if (txtAutoComplete.getAttribute('AlignCompletionToRight') == "true")
        {
            var completionWidth = parseInt(behavior._completionListElement.style.width.replace('px', ''));
            var textboxWidth = parseInt(txtAutoComplete.style.width.replace('px', ''));

            behavior._completionListElement.style.left = textBoxBounds.x - (completionWidth - textboxWidth);
        }
    }

    // automatically move the completion list to above the textbox if there isn't enough room below it
    // do this by grabbing the height of the completion list and comparing that with the location and page height
    // I couldn't find a good way to get the set height of the completion list
    // it turns out it varies which causes the auto complete to show up kind of wacky
    // so I put a property on the textbox to store the fixed height
    if (txtAutoComplete.getAttribute('CompletionHeight') != "")
    {
        var completionListHeight = parseInt(txtAutoComplete.getAttribute('CompletionHeight').replace('px', ''));

        if (!isNaN(completionListHeight))
        {
            var completionEndY = textBoxBounds.y + completionListHeight;
            if (completionEndY >= GetPageHeight())
            {
                var newCompletionY = textBoxBounds.y - 2 - completionListHeight;
                behavior._completionListElement.style.top = newCompletionY;
            }
        }
    }
}

// fire the web service that fires after an item is selected
function AutoComplete_FireOnSelectedWebService(value, txtAutoComplete)
{
    var path = GetPageName();
    if (txtAutoComplete.getAttribute('SelectedWebServicePath') != "")
        path = txtAutoComplete.getAttribute('SelectedWebServicePath');

    var wRequest = Sys.Net.WebServiceProxy.invoke
            (path, txtAutoComplete.getAttribute('OnSelectedWebService'), false, { "value": value, "cachedObjectName": txtAutoComplete.getAttribute('CachedObjectName') },
            null);

    if (txtAutoComplete.getAttribute('PostBackOnSelected') != "false")
    {
        __doPostBack(txtAutoComplete.getAttribute('PostBackLinkButtonId'), '');
    }
}

// return the auto complete extender behavior
function AutoComplete_GetBehaviorFromArray(txtAutoComplete)
{
    return $find(txtAutoComplete.BehaviorId);
}

// when the auto complete is blured
// if item selected is false and the flyout doesn't have the focus,
// then call the web service that goes out and gets the completion list
function AutoComplete_Blur(behaviorId)
{
    var txtAutoComplete = AutoComplete_GetAutoCompleteTextBox(behaviorId);
    var behavior = AutoComplete_GetBehaviorFromArray(txtAutoComplete);

    if (!txtAutoComplete.getAttribute('ItemSelected') && !behavior._flyoutHasFocus && behavior._element.value != "")
    {
        // call the web service that goes out and gets the auto complete list
        var wRequest = Sys.Net.WebServiceProxy.invoke
                    (behavior._servicePath, behavior._serviceMethod,
                     false, { "prefixText": behavior._element.value,
                         "count": 0,
                         "contextKey": behavior._contextKey
                     },
                     AutoComplete_GetAutoCompleteListCompleted, null, txtAutoComplete); // the user context is going to be the lookup array
    }
}

// after the completion list has obtained, take the first element
// in the list and set the value to be that
// if there are no results in the list then set the textbox and value to blank
function AutoComplete_GetAutoCompleteListCompleted(result, userContext, methodName)
{
    var txtAutoComplete = userContext; // the user context is the textbox

    var hfResultsValue = $get(txtAutoComplete.getAttribute('SelectedValueId'))
    if (result.length > 0)
    {
        // the following is the same code that is used in the ajax auto complete
        // to get the text and value from the results.
        // in this case, we only care about the first pair
        var text = null;
        var value = null;

        try
        {
            var pair = Sys.Serialization.JavaScriptSerializer.deserialize('(' + result[0] + ')');
            if (pair && pair.First)
            {
                // Use the text and value pair returned from the web service
                text = pair.First;
                value = pair.Second;
            } else
            {
                // If the web service only returned a regular string, use it for
                // both the text and the value
                text = pair;
                value = pair;
            }
        } catch (ex)
        {
            text = result[i];
            value = result[i];
        }

        hfResultsValue.value = value;
        AutoComplete_GetBehaviorFromArray(txtAutoComplete)._element.value = text;

        AutoComplete_ExecuteItemSelectedClientScript(txtAutoComplete, hfResultsValue.value);
    }
    else
    {
        hfResultsValue.value = '';
        AutoComplete_GetBehaviorFromArray(txtAutoComplete)._element.value = '';
    }

    if (txtAutoComplete.getAttribute('OnSelectedWebService') != "")
    {
        AutoComplete_FireOnSelectedWebService(hfResultsValue.value, txtAutoComplete);
    }
    else
    {
        if (txtAutoComplete.getAttribute('PostBackOnSelected') != "false")
        {
            __doPostBack(txtAutoComplete.getAttribute('PostBackLinkButtonId'), '');
        }
    }

    txtAutoComplete.setAttribute('ItemSelected',true);
}

// when the auto complete textbox has its keys down then set the item selected to false
function AutoComplete_KeyDown(behaviorId, e)
{
    var txtAutoComplete = AutoComplete_GetAutoCompleteTextBox(behaviorId);

    var keyNumClicked = GetKeyNumberClicked(e);

    // if they click enter and if the postback on enter is set and if if the postback on enter control is set
    // then proceed with the postback
    // clear the selected value if ClearSelectedOnKeyDown is true
    if (keyNumClicked == 13 && txtAutoComplete.getAttribute('PostbackOnEnter') == "true" && 
        txtAutoComplete.getAttribute('PostBackOnEnterControlID') != "")
    {
        if (txtAutoComplete.getAttribute('ClearSelectedOnKeyDown') == "true")
        {
            var hfResultsValue = $get(txtAutoComplete.getAttribute('SelectedValueId'))
            hfResultsValue.value = "";
        }

        txtAutoComplete.setAttribute('ItemSelected', false);
        var behavior = $find(behaviorId);

        if (behavior._element.value != "")
        {
            __doPostBack(txtAutoComplete.getAttribute('PostBackOnEnterControlID'), '');
        }
    }

    // the below code will reset the item selected value (telling the auto complete to get
    // its values when the user leaves the textbox) only if the keys pressed or not the following:
    // 13: enter; 9: tab; 17: ctrl; 16: shift;
    // ctrl + c (for copying); shift + tab (going back to a previous control)
    // anything else is a valid control.
    if (keyNumClicked != 13 && keyNumClicked != 9 && keyNumClicked != 17 && keyNumClicked != 16 &&
        (!(e.ctrlKey && keyNumClicked == 67)) &&
        (!(e.shiftKey && keyNumClicked == 9)))
    {
        if (txtAutoComplete.getAttribute('ClearSelectedOnKeyDown') == "true")
        {
            var hfResultsValue = $get(txtAutoComplete.getAttribute('SelectedValueId'))
            hfResultsValue.value = "";
        }

        txtAutoComplete.setAttribute('ItemSelected', false);
    }
    else if (keyNumClicked == 9) // if its a tab then move on to the next control down
    {
        var nextControl = GetNextControlDown(txtAutoComplete.id);
        if (nextControl != null)
            SetLastFocusId(nextControl);
    }
}
/* ***** END AUTOCOMPLETE UC SCRIPTS ***** */

function GetKeyCharacterClicked(e)
{        
    return String.fromCharCode(GetKeyNumberClicked(e))
}

function GetKeyNumberClicked(e)
{
    var keynum;
    var keychar;

    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    return keynum;
}

// this call is important so that the script manager knows that this script has been loaded
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 
