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 && sTime.charAt(1) < 6 && sTime > 0) {
        f.SetValue(oTextBox, '0' + sTime.charAt(0) + ':' + sTime.charAt(1) + sTime.charAt(2));
    }
    else if (sTime.length == 4 && sTime.charAt(2) < 6 && sTime.substr(0, 2) < 24 && sTime > 0) {
        f.SetValue(oTextBox, sTime.charAt(0) + sTime.charAt(1) + ':' + 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 = '^';
    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 SetControlValidClass(oControl, bIsValid) {

    f.SetClassIf(oControl, 'error', !bIsValid);

}

//Form Handler Functions
var FormHandler = new function() {

    var me = this;
    this.MessageBoxEvent;

    //show warning
    this.ShowWarning = function(oWarnings) {


        // build and add the div
        if (!f.GetObject('divInfo')) {

            var oInfo = document.createElement('div');
            oInfo.setAttribute('id', 'divInfo');
            f.SetClass(oInfo, 'warning');
            f.GetObject('divAll').insertBefore(oInfo, f.GetObject('divContent'))

        }

        //get array (either passed in, in which case use it, or make it)
        var aWarnings;
        if (oWarnings.constructor == Array) {
            aWarnings = oWarnings;
        } else {
            var aWarnings = new Array;
            aWarnings.push(oWarnings);
        }


        //set warning
        f.SetHTML('divInfo', f.BuildList(aWarnings));

        //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 = '#';
    }


    //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();
				this.RunWebService('/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)',240000);
	}
}


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);

}