﻿
function ButtonPostBack(oButton) {
    oButton.disabled = true;
    Postback(oButton.id, '');
}

function Postback(sCommand, sArgument, bCheckDelete) {

    //confirm delete if required	
    if (bCheckDelete == true) {
        if (confirm('Are you sure that you want to delete this record?') == false) {
            return;
        }
    }

    if (typeof (oWYSIWYG) != 'undefined') {
        TidyXHTML();

    }

    document.forms[0].Command.value = sCommand;
    document.forms[0].Argument.value = sArgument;
    document.forms[0].action = '';
    document.forms[0].submit();
}

function Replace(sString, sStringToReplace, sReplacement) {
    while (sString.indexOf(sStringToReplace) != -1) {
        sString = sString.replace(sStringToReplace, sReplacement);
    }
    return sString;
}

function iif(bCondition, oTrue, oFalse) {

    return bCondition ? oTrue : oFalse;

}

function SetFocus(sControlID) {
	var oControl=window.document.getElementById(sControlID);
	if (oControl != null){oControl.focus()};
}

function IntegerOnly(oEvent) {
    iKeyPress = iif(oEvent.keyCode, oEvent.keyCode, oEvent.which);
    return iKeyPress > 47 && iKeyPress < 58;
}

function TimeOnly(oEvent) {
    iKeyPress = iif(oEvent.keyCode, oEvent.keyCode, oEvent.which);
    return iKeyPress > 47 && iKeyPress < 59;
}

function ParseTime(oTextBox) {

    var sTime = f.GetValue(oTextBox);

    if (sTime.length == 3 && parseInt(sTime.charAt(1)) < 6 && parseInt(sTime) > 0) {
        f.SetValue(oTextBox, '0' + sTime.charAt(0) + ':' + sTime.charAt(1) + sTime.charAt(2));
    }
    else if (sTime.length == 4 && sTime.charAt(1) != ':' && parseInt(sTime.charAt(2)) < 6 && parseInt(sTime.substr(0, 2)) < 24 && parseInt(sTime) > 0) {
        f.SetValue(oTextBox, sTime.charAt(0) + sTime.charAt(1) + ':' + sTime.charAt(2) + sTime.charAt(3));
    }
    else if (sTime.length == 4 && sTime.charAt(1) == ':' && parseInt(sTime.charAt(2)) < 6 && parseInt(sTime.charAt(0)) > 0 && parseInt(sTime) > 0) {
		f.SetValue(oTextBox, '0' + sTime.charAt(0) + ':' + sTime.charAt(2) + sTime.charAt(3));
    }
}

function TextboxOnEnter(oEvent, oFunction) {

    if (f.GetKeyCodeFromEvent(oEvent) == 13) {
        oFunction();
        oEvent.cancelBubble = true;
        oEvent.returnValue = false;
    }

}


/* *************     Validation Functions ********** */
function ClientValidation(oButton, sTable, sWarn) {

    var sControlID, sNiceName, sValidation,
		sControlPrefix, oControl, sControlValue, sWarnings = '',
		iSelectedValue, sSelectedValue, sFocusControl = '', bIsValid;

    if (sWarn != undefined) {
        sWarnings = sWarn;
    }

    //postback if we haven't got the validation array
    if (typeof (aValidation) == 'undefined') {
        ButtonPostBack(oButton);
        return;
    }

    for (var i = 0; i < aValidation.length; i++) {

        if (sTable == '' || sTable == aValidation[i][0]) {
            sControlID = aValidation[i][1];
            sNiceName = aValidation[i][2];
            sValidation = aValidation[i][3];
            
            oControl = document.getElementById(sControlID);
            bIsValid = true;

            //if the control is null then don't do nowt
            if (oControl != null) {
                sControlPrefix = sControlID.substring(0, 3);

                // textbox
                if (sControlPrefix == 'txt') {

                    sControlValue = oControl.value;

                    // not empty
                    if (sValidation.indexOf('NotEmpty') > -1 && oControl.className.indexOf('number') == -1
								 && sControlValue == '') {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be specified|';
                    }

                    /* not empty is numeric */
                    if (sValidation.indexOf('NotEmpty') > -1 && oControl.className.indexOf('number') > -1
								 && SafeNumeric(sControlValue) == 0) {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be specified|';
                    }

                    //email
                    if (sValidation.indexOf('IsEmail') > -1 && IsEmail(sControlValue) == false && sControlValue != '') {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be a valid email address|';
                    }

                    //time
                    if (sValidation.indexOf('IsTime') > -1 && IsTime(sControlValue) == false && sControlValue != '') {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be a valid time (hh:mm)|';
                    }

                    //credit card
                    if (sValidation.indexOf('IsCardNumber') > -1 && IsCardNumber(sControlValue) == false && sControlValue != '') {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' is not a valid Credit Card number|';
                    }

                }

                // autocomplete
                if (sControlPrefix == 'acp') {

                    var oAutoControlValue = document.getElementById(sControlID + 'Hidden');
                    sControlValue = oAutoControlValue.value;

                    /* not empty */
                    if (sValidation.indexOf('NotEmpty') > -1 && SafeNumeric(sControlValue) == 0) {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be specified|';
                    }
                }


                // date textbox
                if (sControlPrefix == 'dtb') {
                    sControlValue = oControl.value;

                    // not empty
                    if (sValidation.indexOf('NotEmpty') > -1 && sControlValue == '') {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be specified|';
                    } else if (sControlValue != '' && IsDate(sControlValue) == false) {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be a Valid Date|';
                    }
                }

                //plopdown
                if (sControlPrefix == 'ddl' || sControlPrefix == 'add' || sControlPrefix == 'sdd') {

                    iValue = SafeInt(oControl.options[oControl.selectedIndex].value);
                    sValue = oControl.options[oControl.selectedIndex].text;

                    //not empty
                    if (sValidation.indexOf('NotEmpty') > -1 &&
							((iValue == 0 && sControlPrefix == 'ddl' && sValue == '') ||
							(iValue == 0 && sControlPrefix != 'ddl') || (sControlPrefix == 'add' && iValue < 1))) {
                        bIsValid = false;
                        sWarnings += 'The ' + sNiceName + ' must be specified|';
                    }
                }

                //custom validation
                if (sValidation == 'CustomValidation') {
                    if (typeof (aValidation[i][4]) == 'boolean') {
                        if (!aValidation[i][4]) {
                            sWarnings += aValidation[i][2] + '|';
                            bIsValid = false;
                        }
                    } else if (!aValidation[i][4]()) {
                        sWarnings += aValidation[i][2] + '|';
                        bIsValid = false;
                    }
                }

                //set control valid class
                SetControlValidClass(oControl, bIsValid);

                //if it's the first warning then set the focus control
                if (sWarnings != '' && sFocusControl == '') {
                    sFocusControl = sControlID;
                }
            }
        }
    }

    //postback if all's ok or show warnings instead
    if ((sWarnings.length == 0) && (!oButton == undefined)) {
        ButtonPostBack(oButton);
    } else if (sWarnings.length == 0) {
        FormHandler.CloseInfo();    
    } else if (sWarnings.length > 0) {
        var aWarnings = sWarnings.split('|');
        FormHandler.ShowWarning(aWarnings);
    }

    return sWarnings.length == 0;    
}




//validators
function IsEmail(sEmail) {
    var sEmailRegEx = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
    var o = new RegExp(sEmailRegEx);
    return o.test(sEmail);
}

function IsURL(sURL) {
    var sURLRegEx = /(ht|f)tp(s?)\:\/\/[a-zA-Z0-9\-\._]+(\.[a-zA-Z0-9\-\._]+){2,}(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?/;
    var o = new RegExp(sURLRegEx);
    return o.test(sURL);
}

function IsTime(sTime) {
    var sTimeRegEx = /[0-2][0-9]:[0-6][0-9]/;
    var o = new RegExp(sTimeRegEx);
    return o.test(sTime);
}

function IsDate(sDate) {
    var nonDigit = /\D/g;
    var displaydateformat = /^[0-3][0-9]\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(19|20)\d\d$/;
    var now = new Date();
    var dDate;
    var iDay;
    var sMonth;
    var iYear;

    //bomb out if no characters
    if (sDate.length == 0) return false;

    //display date
    if (displaydateformat.test(sDate)) {

        //test for max days
        iDay = parseInt(sDate.substring(0, 2));
        sMonth = sDate.substring(3, 6);
        iYear = parseInt(sDate.substring(7, 11));
        if (iDay <= 31 && (sMonth == 'Jan' || sMonth == 'Mar' || sMonth == 'May' || sMonth == 'Jul'
					|| sMonth == 'Aug' || sMonth == 'Oct' || sMonth == 'Dec')) {
            return true;
        } else if (iDay <= 30 && (sMonth == 'Apr' || sMonth == 'Jun' || sMonth == 'Sep' || sMonth == 'Nov')) {
            return true;
        } else if (sMonth == 'Feb' && ((iDay <= 29 && d.CheckLeapYear(iYear) == true)
						|| (iDay <= 28 && d.CheckLeapYear(iYear) == false))) {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }

}
    
function IsSecurityCode(sCode, length) {
    if (length == undefined) length = 3;
    var sExp = '^[0-9]{3,4}$';
//    for (var i = 0;i<length;i++){
//        sExp+='[0-9]';
//    }
    //    sExp+='$';

    var o = new RegExp(sExp);
    return o.test(sCode);
}

function IsCardNumber(sCardNumber) {

    var iSum = 0;
    var bAlt = false;
    var iDigit;
    for (var i = sCardNumber.length; i--; i >= 0) {
        iDigit = n.SafeInt(s.Substring(sCardNumber, i, i + 1));
        if (bAlt) {
            iDigit *= 2;
            if (iDigit > 9) { iDigit -= 9; }
        }
        iSum += iDigit;
        bAlt = !bAlt;
    }
    return iSum % 10 == 0;
}







//Safe Types
function SafeInt(sInteger) {
    if ((sInteger == null) || (sInteger == '') || (sInteger == '0')) {
        return 0;
    } else {

        //remove any commas
        var aInt = sInteger.split(",");
        var sTotal = '';
        for (var loop = 0; loop < aInt.length; loop++) {
            sTotal += aInt[loop];
        }
        return parseInt(parseFloat(sTotal));
    }
}

function SafeNumeric(sNumber) {
    if ((sNumber == null) || (sNumber == '') || (sNumber == '0')) {
        return 0;
    } else {

        //remove any commas
        var aInt = sNumber.split(",");
        var sTotal = '';
        for (var loop = 0; loop < aInt.length; loop++) {
            sTotal += aInt[loop];
        }
        return parseFloat(sTotal);
    }
}

function SafeBoolean(sBoolean) {
	if (sBoolean != undefined && sBoolean != null && sBoolean.toString().toLowerCase() != 'false' && sBoolean) {
		return true;
	} else {
		return false;
	}
}

function SetControlValidClass(oControl, bIsValid) {

    f.SetClassIf(oControl, 'error', !bIsValid);

}

//Form Handler Functions
var FormHandler = new function() {

    var me = this;
    this.MessageBoxEvent;
    
    
    //show a message
    this.BuildMessage = function (oMessages, sClass) {
        
        // build and add the div
        if (!f.GetObject('divInfo')) {

            var oInfo = document.createElement('div');
            oInfo.setAttribute('id', 'divInfo');
            f.SetClass(oInfo, sClass);
            f.GetObject('divAll').insertBefore(oInfo, f.GetObject('divMain'))}
        else {
            f.SetClass('divInfo', sClass);
        }

        
        //get array (either passed in, in which case use it, or make it)
        var aMessages;
        if (oMessages.constructor == Array) {
            aMessages = oMessages;
        } else {
            var aMessages = new Array;
            aMessages.push(oMessages);
        }


        //set messages
        f.SetHTML('divInfo', f.BuildList(aMessages));

        //add header
        var oHeader = document.createElement('div');
        oHeader.setAttribute('id', 'divInfoHeader');
        f.GetObject('divInfo').appendChild(oHeader);

        //add close
        var aClose = document.createElement('a');
        f.AttachEvent(aClose, 'click', function() { FormHandler.CloseInfo() });
        aClose.setAttribute('href', '#');
        aClose.setAttribute('id', 'aCloseInfo');
        f.SetHTML('aCloseInfo', 'close');
        f.GetObject('divInfo').appendChild(aClose);

        //add footer
        var oFooter = document.createElement('div');
        oFooter.setAttribute('id', 'divInfoFooter');
        f.GetObject('divInfo').appendChild(oFooter);

        me.MessageBoxEvent = f.AttachEvent(document, 'keypress',
		        function(event) {
		            if (f.GetKeyCodeFromEvent(event) == 27) {
		                f.DetachEvent(me.MessageBoxEvent);
		                me.CloseInfo();
		            }
		        });

        window.location = '#';
    }
    
    
    //show warning
    this.ShowWarning = function(oWarnings) {
        me.BuildMessage(oWarnings, 'warning')
    }



    //show information
    this.ShowInformation = function(oInformation) {
        me.BuildMessage(oInformation, 'information')
    }


    //CloseInfo
    this.CloseInfo = function() {

        if (f.GetObject('divInfo')) {
            f.GetObject('divInfo').parentNode.removeChild(f.GetObject('divInfo'));
        }
    }


}



//Session Persister
var oPersistSession;
function SessionPersister(bRun) {

	if (typeof f != 'undefined') {
		if (oPersistSession == null) {
			oPersistSession = new WebService();

			oPersistSession.Go = function(URL) {
				aParams = new Array();
				var sURLBase = window.location.protocol + '//' + window.location.host;
				this.RunWebService(sURLBase + '/webservices/support.asmx', 'http://intuitivesystems', 'PersistSession', aParams, this, false);
			}

			oPersistSession.Done = function(oXML) {
				var oReturn = this.GetTagValue(oXML, 'PersistSessionResult');
			}
		}

		if (bRun) { oPersistSession.Go(); }
		setTimeout('SessionPersister(true)',60000);
	}
}


function ShowTermsAndConditions(sURL) {
	var iTop=(screen.availHeight-800)/2;
	var iLeft=(screen.availWidth-800)/2;
	
	var sFeatures='scrollbars=yes, menubar=no, resizable=yes, status=no,' + 
				'titlebar=no, toolbar=no, height=800, width=800,top=' + iTop + ', Left=' + iLeft;
	
	window.open(sURL,'_blank',sFeatures,true);

}


//wait message
function ShowWaitMessage(sDivID) {
    if (!sDivID)
        {sDivID='divWaitMessage'}
    if (f.GetObject(sDivID)) {
        document.body.appendChild(f.GetObject(sDivID));
        e.ModalPopup.Show(sDivID)
    }
}


function HideWaitMessage(sDivID) {
    if (!sDivID)
        {sDivID = 'divWaitMessage'}
    if (f.GetObject(sDivID)) {
        e.ModalPopup.Close()
    }
}

//modal popup - sets which objects to display inside a popup - hand in an array of ['tag', 'id', show_flag]
//e.g:
//	PopupDisplayObjects(new Array(['label', 'lblInfo', 1], ['label', 'lblWarning', 0], ['input', 'btnClose', 0]));
//	ShowWaitMessage();
function PopupDisplayObjects(aObjects) {
    if (aObjects) {
        var aPopupDivs = f.GetElementsByClassName('div', 'modalpopup')
        
        for (var iPopup = 0; iPopup < aPopupDivs.length; iPopup++) {
        
            for (var iClass = 0; iClass < aObjects.length; iClass++) {
                var aPopupObjects = f.GetElementsByClassName(aObjects[iClass][0], aObjects[iClass][1], aPopupDivs[iPopup]);
                
                for (var iObject = 0; iObject < aPopupObjects.length; iObject++) {
                    if (aObjects[iClass][2]) {
                        f.Show(aPopupObjects[iObject])
                    } else {
                        f.Hide(aPopupObjects[iObject])
                    }
                }
                
            }
            
        }
    }
}

//make links external
function MakeLinksExternal(oContainer) {
    var oContainer = f.SafeObject(oContainer);
    
    if (oContainer) {
        var aLinks = oContainer.getElementsByTagName('a');
        for ( var i = 0; i < aLinks.length; i++ ) {
            aLinks[i].setAttribute('target', '_blank');
        }
    }
}

//Image swapping
var ImageSwap = new function() {

    this.Hover = function(aLink, sImageURL) {
        f.GetObject('imgMainImage').src = sImageURL;
        var aThumbnailLinks = f.GetObjectsByIDPrefix('imgThumb', 'img');
        for (var i = 0; i < aThumbnailLinks.length; i++) {
            f.SetClassIf(aThumbnailLinks[i], 'selected', aThumbnailLinks[i] == aLink);
        }
    }
}





// Trade Login
var Trade = new function() {

    this.ValidateLogin = function() {

        f.SetClassIf('txtAbta', 'error', f.GetValue('txtAbta') == '');
        f.SetClassIf('txtPassword', 'error', f.GetValue('txtPassword') == '');

        var aErrorControls = f.GetElementsByClassName('*', 'error', 'divTradeLogin');

        if (aErrorControls.length == 0) {
            oTradeLogin.Go(f.GetValue('txtAbta'), f.GetValue('txtPassword'));
        } else {
            f.SetHTML('divTradeLoginError', 'Please make sure you have entered your login details correctly');
            f.Show('divTradeLoginError');
        }

    }

    this.Logout = function() {
        oTradeLogout.Go();
    }

    // Webservice
    var oTradeLogin = new WebService();
    oTradeLogin.Go = function(LoginName, Password) {
        aParams = new Array(['LoginName', LoginName], ['Password', Password]);
        this.RunWebService('/webservices/support.asmx', 'http://intuitivesystems', 'TradeLogin', aParams, this, false);
    }

    oTradeLogin.Done = function(oXML) {
        var oReturn = this.GetTagValue(oXML, 'TradeLoginResult');
        if (oReturn != 'false') {
            window.location = 'default.aspx';
        } else {
            f.SetHTML('divTradeLoginError', 'Your Login or Password is incorrect. Please check your details and try again.');
            f.Show('divTradeLoginError');
        }
    }

    var oTradeLogout = new WebService();

    oTradeLogout.Go = function() {
        aParams = new Array();
        this.RunWebService('/webservices/support.asmx', 'http://intuitivesystems', 'TradeLogout', aParams, this, false);

    }

    oTradeLogout.Done = function() {
        window.location = 'default.aspx';
    }


}


function ClearSelection(oList) {
    document.getElementById('hid' + oList.name).value = '';
}



/* auto complete/suggest */
var oASTextbox;
var sASBaseURL;
var oASTimer;
function AutoSuggestKeyUp(oEvent, oTextbox, sBaseURL) {

    iKeyCode = iif(oEvent.keyCode, oEvent.keyCode, oEvent.which);

    if (iKeyCode < 41 && iKeyCode != 32 && iKeyCode != 8) { return; }

    var oDiv = document.getElementById(oTextbox.id + 'Container');

    if (oTextbox.value.length > 1) {

        if (oASTimer) {
            clearTimeout(oASTimer);
        }
        oASTextbox = oTextbox;
        sASBaseURL = sBaseURL;
        oASTimer = setTimeout('AutoSuggest_Try()', 300);
    } else {

        //clear the value
        AutoSuggestClear(oTextbox);
    }
}


function AutoSuggest_Try() {
    var aParams = document.getElementById(oASTextbox.id + 'Params').value.split('|');
    oASTextbox.className += ' autocompleteworking';
    AutoSuggestSendRequest(sASBaseURL, oASTextbox.id, aParams[0], aParams[1], aParams[4], aParams[5], aParams[6], oASTextbox.value)
}


function AutoSuggestClear(oTextbox) {
    var oHidden = document.getElementById(oTextbox.id + 'Hidden');
    oHidden.value = '0';
}


function AutoSuggestKeyDown(oEvent, oTextbox) {


    iKeyCode = iif(oEvent.keyCode, oEvent.keyCode, oEvent.which);
    var oDiv = document.getElementById(oTextbox.id + 'Container');
    var oHidden = document.getElementById(oTextbox.id + 'Hidden');

    if (oDiv.style.display != 'none') {

        switch (iKeyCode) {
            case 38: //up arrow
                AutoSuggestMove(oDiv, -1);
                return;
            case 40: //down arrow
                AutoSuggestMove(oDiv, 1);
                return;
            case 33: //page up
                AutoSuggestMove(oDiv, -5);
                return;
            case 34: //page down
                AutoSuggestMove(oDiv, 5);
                return;
            case 27: //escape
                AutoSuggestHideContainer(oDiv);
                return;
            case 9: //tab
                //if there's only one item in the box then select it
                var iSelected = AutoSuggestGetCurrentSelectedIndex(oDiv);
                if (iSelected == -1) {
                    iSelected = 0;
                }
                AutoSuggestSelect(oDiv, oTextbox, oHidden, iSelected);
                return;
            case 13: //enter

                //if there's only one item in the box then select it
                var iSelected = AutoSuggestGetCurrentSelectedIndex(oDiv);
                if (iSelected == -1) {
                    iSelected = 0;
                }
                AutoSuggestSelect(oDiv, oTextbox, oHidden, iSelected);

                //get autopostback param, if true (and something is selected) then postback(oTextbox.id)
                var bAutoPostback = document.getElementById(oTextbox.id + 'Params').value.split('|')[7];
                if (bAutoPostback == 'True' && iSelected > -1) {
                    Postback(oTextbox.id, 0);
                }

                if (bAutoPostback != 'True' && f.GetValue(oTextbox.id + '_Script') != '') {
                    var sScript = f.GetValue(oTextbox.id + '_Script');
                    eval(sScript);
                }

                oEvent.cancelBubble = true;
                oEvent.returnValue = false;
                return false;
        }

    }
}


function AutoSuggestMove(oDiv, iNumberToMove) {

    var iItemCount = oDiv.childNodes.length - 1;
    var iCurrentSelected = AutoSuggestGetCurrentSelectedIndex(oDiv);
    var iTarget = iCurrentSelected + iNumberToMove;

    if (iTarget < 0) {
        iTarget = 0;
    } else if (iTarget > iItemCount) {
        iTarget = iItemCount;
    }

    AutoSuggestSetSelected(oDiv, iTarget, iCurrentSelected);
}


function AutoSuggestSelect(oDiv, oTextbox, oHidden, iSelected, bMouseClick) {

    oDiv = f.SafeObject(oDiv);
    oTextbox = f.SafeObject(oTextbox);
    oHidden = f.SafeObject(oHidden);

    if (iSelected > -1) {
        var sDisplay = Replace(oDiv.childNodes[iSelected].innerHTML, '<span>', '')
        sDisplay = Replace(sDisplay, '</span>', '')
        sDisplay = Replace(sDisplay, '<SPAN>', '')
        sDisplay = Replace(sDisplay, '</SPAN>', '')
        sDisplay = Replace(sDisplay, '&amp;', '&')

        if (sDisplay.indexOf('<') > -1) {
            sDisplay = sDisplay.substring(0, sDisplay.indexOf('<'));
        }

        oTextbox.value = sDisplay;

        oHidden.value = oDiv.childNodes[iSelected].id;

        //if it's been selected via a mouse click then check for postback
        if (bMouseClick) {

            //get autopostback param, if true (and something is selected) then postback(oTextbox.id)
            var bAutoPostback = document.getElementById(oTextbox.id + 'Params').value.split('|')[7];
            if (bAutoPostback == 'True' && iSelected > -1) {
                Postback(oTextbox.id, 0);
            }

            if (bAutoPostback != 'True' && f.GetValue(oTextbox.id + '_Script') != '') {
                var sScript = f.GetValue(oTextbox.id + '_Script');
                eval(sScript);
            }

        }

    }
    
    AutoSuggestHideContainer(oDiv);

}

function AutoSuggestShowContainer(oDiv) {

    var oTextbox = document.getElementById(oDiv.id.replace(/Container/, ''));

    oDiv.style.display = 'block';

    oTextbox.style.position = 'relative';

    var aParams = document.getElementById(oTextbox.id + 'Params').value.split('|');
    if (SafeInt(aParams[2]) != 0 || SafeInt(aParams[3])) {
        oDiv.style.top = aParams[3]+'px';
        oDiv.style.left = aParams[2]+'px';
    } else {
        oDiv.style.top = oTextbox.offsetTop + (oTextbox.offsetHeight - 2) + 'px';
        oDiv.style.left = oTextbox.offsetLeft + 'px';
    }

    oDiv.style.width = (oTextbox.offsetWidth - 2) + 'px';

    AutoSuggestManageHiddenControls(oDiv, 'Show');

}

function AutoSuggestHideContainer(oDiv) {
    oDiv.style.display = 'none';
    AutoSuggestManageHiddenControls(oDiv, 'Hide');
}

function AutoSuggestManageHiddenControls(oDiv, sType) {

    //see if there's any hidden controls to sort
    var oHidden = document.getElementById(oDiv.id.replace(/Container/, 'HiddenControls'));
    if (oHidden != null) {

        var aHiddenControls = oHidden.value.split(';');
        var oHiddenControl;
        for (var iLoop = 0; iLoop <= aHiddenControls.length - 1; iLoop++) {

            oHiddenControl = document.getElementById(aHiddenControls[iLoop]);
            if (oHiddenControl != null) {

                if (sType == 'Show') {
                    oHiddenControl.style.visibility = 'hidden';
                } else {
                    oHiddenControl.style.visibility = '';
                }
            }
        }
    }
}

function AutoSuggestSetSelected(oDiv, iSelectIndex, iDeselectIndex) {

    if (iDeselectIndex > -1) {
        oDiv.childNodes[iDeselectIndex].className = '';
    }
    oDiv.childNodes[iSelectIndex].className = 'selected';

    oDiv.scrollTop = oDiv.childNodes[iSelectIndex].offsetTop - 30;

}

function AutoSuggestGetCurrentSelectedIndex(oDiv) {
    for (var i = 0; i < oDiv.childNodes.length; i++) {
        if (oDiv.childNodes[i].className == 'selected') {
            return i;
        }
    }
    return -1;
}


function SetAutoCompleteParams(ID, Table, Expression, Left, Top, SecondExpression, Filter, Order, AutoPostback) {
    f.SetValue(ID + 'Params', Table + '|' + Expression + '|' + Left + '|' + Top + '|' + SecondExpression + '|' + Filter + '|' + Order + '|' + AutoPostback);
}

function ClearAutoComplete(ID) {
    f.SetValue(ID, '');
    f.SetValue(ID + 'Hidden', 0);
}




/*  auto suggest clever stuff */
var oASRequest;

function AutoSuggestSendRequest(sPage, sControl, sTable, sExpression, sSecondExpression, sFilter, sOrder, sSearch) {

    if (sSearch.length < 3) { return; }

    var sUrl = sPage + '?Control=' + sControl + '&Table=' + sTable + '&Expression=' + sExpression
		+ '&SecondExpression=' + sSecondExpression + '&Filter=' + sFilter + '&Order=' + sOrder + '&Search=' + sSearch;


    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        oASRequest = new XMLHttpRequest();
        oASRequest.onreadystatechange = AutoSuggestReceiveResponse;
        oASRequest.open("GET", sUrl, true);
        oASRequest.send(null);

        // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        //isIE = true;
        oASRequest = new ActiveXObject("Microsoft.XMLHTTP");
        if (oASRequest) {
            oASRequest.onreadystatechange = AutoSuggestReceiveResponse;
            oASRequest.open("GET", sUrl, true);
            oASRequest.send();
        }
    }
}


function AutoSuggestReceiveResponse() {

    if (oASRequest.readyState == 4) {
        if (oASRequest.status == 200) {
            AutoSuggestDisplayResults(oASRequest.responseText);

        } else {
            alert("There was a problem retrieving the XML data:\n" +oASRequest.statusText);
        }
    }
}

function AutoSuggestDisplayResults(sResults) {

    var aResults = sResults.split('|');
    var oContainer = document.getElementById(aResults[0] + 'Container');
    var sResult = '';
    var aSplit;

    //work out ids
    var sDiv = oContainer.id;
    var sTextbox = aResults[0];
    var sHidden = aResults[0] + 'Hidden';

    for (var i = 1; i < aResults.length; i++) {

        aSplit = aResults[i].split('^');
        if (aSplit.length == 2) {
            //sResult+='<div id="'+aSplit[1]+'">'+aSplit[0]+'</div>'
            sResult += '<div id="' + aSplit[1] + '" onclick="AutoSuggestSelect(\'' + oContainer.id + '\',\'' + sTextbox + '\',\'' + sHidden + '\',' + (i - 1) + ',true);">' + aSplit[0] + '</div>'
        } else {
            //sResult+='<div id="'+aSplit[2]+'">'+aSplit[0]+'<div>'+aSplit[1]+'</div>'+'</div>'
            sResult += '<div id="' + aSplit[2] + '" onclick="AutoSuggestSelect(\'' + oContainer.id + '\',\'' + sTextbox + '\',\'' + sHidden + '\',' + (i - 1) + ',true);">' + aSplit[0] + '<div>' + aSplit[1] + '</div>' + '</div>'
        }
    }

    var oTextbox = f.GetObject(sTextbox);
    oTextbox.className = s.Replace(oTextbox.className, ' autocompleteworking', '');

    oContainer.innerHTML = sResult;
    AutoSuggestShowContainer(oContainer);
}
