
function isIE() {
    return (typeof (document.all) != 'undefined');
}

function getIEVersion() {
    var versionText = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return parseFloat(versionText);
}

function isIE7() {
    if (isIE()) {
        return getIEVersion() >= 7;
    }
    return false;
}

function isIE6() {
    if (isIE()) {
        return getIEVersion() < 7;
    }
    return false;
}

// Javascrpt for client side validation
function AddClientSideLabelValidation() {
    var __funcbody, newfunc;

    if (typeof (ValidatorUpdateDisplay) != "undefined") {

        __funcbody = ValidatorUpdateDisplay.toString();
        __funcbody = __funcbody.substring(__funcbody.indexOf("{") + 1,
										 __funcbody.lastIndexOf("}"));

        newfunc = new Function("val", "SetLabel(val ); " +
													 __funcbody);

        ValidatorUpdateDisplay = newfunc;
    }
}



function SetLabel(val) {
    if (val == null || val.controltovalidatelabel == null || val.noerrorcssclass == null || val.errorcssclass == null) {
        return;
    }
    var ctrl = document.getElementById(val.controltovalidatelabel);
    if (ctrl != null && typeof (ctrl) != "undefined") {
        var x;
        var retval;
        retval = true;

        // Find out all validators associated
        var vals = new Array();
        for (x = 0; x < Page_Validators.length; x++) {
            if (Page_Validators[x].controltovalidate == val.controltovalidate)
                vals.push(Page_Validators[x]);
        }

        //Determine if some validator fails
        for (x = 0; x < vals.length && retval; x++)
            retval = vals[x].isvalid;

        ctrl.className = retval ? val.noerrorcssclass : val.errorcssclass;
    }
}

// End javascript for client side validation


// Javascript for custom date validation

var oneMinute = 60 * 1000  // milliseconds in a minute	
var oneHour = oneMinute * 60
var oneDay = oneHour * 24
var oneWeek = oneDay * 7
var months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

function reformatDateTextBox(txtBox, locale) {
    var d = parseDate(txtBox.value, locale);
    if (d != null) {
        var year = d.getFullYear();
        if (year > 0 && year < 31) year = 2000 + year;
        if (year > 30 && year < 101) year = 1900 + year;
        var dateday = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
        txtBox.value = dateday + '-' + months[d.getMonth()] + '-' + year;
    }
}

function parseDate(dateText, locale) {
    // parses date from text

    var retVal = null;
    var match = null;

    var monthPos = null;
    var dayPos = null;
    var yearPos = null;

    var usDateFormatRegEx = "^\\s*(\\d{1,2})[/.-](\\d{1,2})[/.-](\\d{2,4})\\s*$";
    var intDateFormatRegEx = "^\\s*(\\d{1,2})[/.-](\\w{3})[/.-](\\d{2,4})\\s*$";

    // test for MM/dd/yyyy
    var re = new RegExp(usDateFormatRegEx);
    match = re.exec(dateText);
    if (match != null) {

        if (locale == 'en-GB') {
            monthPos = 2;
            dayPos = 1;
            yearPos = 3;
        }
        else {
            monthPos = 1;
            dayPos = 2;
            yearPos = 3;
        }

    }

    // if prev test failed then test again
    if (match == null) {
        re = new RegExp(intDateFormatRegEx);
        // test for dd/MMM/yyyy
        match = re.exec(dateText);
        if (match != null) {
            monthPos = 2;
            dayPos = 1;
            yearPos = 3;
        }
    }

    // did we find a match
    if (match != null) {

        // parse day and year since they are simple year
        var day = new Number(match[dayPos]);
        var year = new Number(match[yearPos]);

        var monthText = match[monthPos];
        var month = new Number();

        // if month is a string we need to parse it		
        if (/[A-Za-z]+/.test(monthText)) {

            // convert it to lower case
            var monthLower = new String(monthText);
            monthLower = monthLower.toLowerCase();

            // look in the months array for a match
            var found = false;
            for (i = 0; i < months.length; i++) {
                if (months[i].toLowerCase() == monthLower) {
                    month = i;
                    found = true;
                    break;
                }
            }

            // bail out its not found
            if (!found) return null;

        } else {
            month = new Number(monthText);

            // dec 1 since month is 0-11 range
            month--;
        }

        // validate the year and translate, if necessary
        if (year < 50) year += 2000;
        else if (year >= 50 && year < 100) year += 1900;

        // validate the month
        if (month >= 0 && month < 12 && day <= getDaysInMonth(year, month)) {
            // set the date because its valid
            retVal = new Date();
            retVal.setFullYear(year, month, day);
            retVal.setHours(0, 0, 0, 0);
        }
    }

    return retVal;
}

function getDaysInMonth(year, month) {
    // figure out if the day exists by figuring out the month and year
    // then going to the next month and subtracting one day from the first
    // of the month to get the last day of the previous month 
    var monthEnd = new Date();
    if (month == 11)
        monthEnd.setFullYear(year + 1, 1, 1);
    else
        monthEnd.setFullYear(year, month + 1, 1);
    monthEnd.setHours(0, 0, 0, 0);
    monthEnd = new Date(monthEnd - oneDay);
    return monthEnd.getDate();
}

// Validate the date is a good date
function validateDate(oSrc, args) {
    //CFDateValidator_LOCALE should get set by a startup script in CFDateValidator
    args.IsValid = (parseDate(args.Value, CFDateValidator_LOCALE) != null);
}

// Compare 2 dates and validate the day of the month is the same
function compareDayOfMonth(oSrc, args) {
    args.IsValid = true;

    var currentDate = parseDate(args.Value);
    var compareVal;
    var compareDate;
    if (oSrc.CompareDate != null) {
        compareVal = ValidatorGetValue(oSrc.CompareDate)
        compareDate = parseDate(compareVal);
    }

    if (currentDate != null && compareDate != null) {
        args.IsValid = (currentDate.getDate() == compareDate.getDate())

    }
}

function addMonth(oDate, oMonths) {
    if (oMonths == null) {
        return oDate;
    }
    oMonths = oMonths * 1;
    if (oMonths == 0) {
        return oDate;
    }
    var oNewDate = new Date(oDate);
    oNewDate.setMonth(oNewDate.getMonth() + oMonths);
    return oNewDate;
}

function compareTwoDates(oDate1, oDate2, dateCompareLogic) {
    if (dateCompareLogic == "greaterthan") {
        return oDate1.valueOf() > oDate2.valueOf();
    }
    else if (dateCompareLogic == "greaterthanequal") {
        return oDate1.valueOf() >= oDate2.valueOf();
    }
    else if (dateCompareLogic == "lessthan") {
        return oDate1.valueOf() < oDate2.valueOf();
    }
    else // dateCompareLogic = "lessthanequal"
    {
        return oDate1.valueOf() <= oDate2.valueOf();
    }
}

function compareDates(oSrc, args) {
    args.IsValid = true;

    var currentDate = parseDate(args.Value);
    var compareVal;
    var compareDate;
    if (oSrc.DateTextBox != null) {
        compareVal = ValidatorGetValue(oSrc.DateTextBox)
        compareDate = parseDate(compareVal);
        compareDate = addMonth(compareDate, oSrc.DateCompareAddMonths);
    }

    if (currentDate == null) {
        return;
    }
    if (compareDate != null) {
        args.IsValid = compareTwoDates(currentDate, compareDate, oSrc.DateCompareLogic);
    }
    if (oSrc.DateValue != null) {
        compareDate = parseDate(oSrc.DateValue);
        compareDate = addMonth(compareDate, oSrc.DateCompareAddMonths);
    }
    if (args.IsValid && compareDate != null) {
        args.IsValid = compareTwoDates(currentDate, compareDate, oSrc.DateCompareLogic);
    }
}

// End javascript for custom date validation


// Javascript for text box with submit upon hitting enter

function CheckKeyDown(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        return false;
    }
    else return true;
}

function CheckKeyUp(e, textboxId, buttonId) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        var textboxObj = document.getElementById(textboxId);
        var buttonObj = document.getElementById(buttonId);
        if (textboxObj != null && buttonObj != null) {
            textboxObj.blur();
            textboxObj.focus();
            buttonObj.click();
            return false;
        }
    }

    return true;
}

// Javascript for popup help window
var currentExpandedBtnId;
var currentExpandedHelpId;
var delayBubble;
var delayBubbleWaiting = false;

function stopTimer() {
    if (delayBubbleWaiting) // stop only if running 
    {
        delayBubbleWaiting = clearTimeout(delayBubble);
    }
}

// Close any open help
function closeOpenHelp() {
    stopTimer();
    if (currentExpandedBtnId != null) {
        toggleHelp(currentExpandedBtnId, currentExpandedHelpId);
    }
}

// Used for the bubble checkbox control
function toggleHelpDelay(obtnId, ohelpId, reverse, flip, delay) {
    closeOpenHelp();
    var delayedFunction = "delayBubbleWaiting=false;hideShowHelpBubble('" + obtnId + "', '" + ohelpId + "', " + reverse + ", " + flip + ")";
    delayBubbleWaiting = true;
    delayBubble = setTimeout(delayedFunction, delay);
}

function toggleHelp(obtnId, ohelpId, reverse, flip) {
    stopTimer();
    // Close any open help
    if (currentExpandedBtnId != null && currentExpandedBtnId != obtnId) {
        toggleHelp(currentExpandedBtnId, currentExpandedHelpId);
    }
    hideShowHelpBubble(obtnId, ohelpId, reverse, flip);
}

function hideShowHelpBubble(obtnId, ohelpId, reverse, flip) {
    toggleElement(ohelpId, false);
    if (isElemVisible(ohelpId)) {
        var left = 0;
        var top = 0;

        currentExpandedBtnId = obtnId;
        currentExpandedHelpId = ohelpId;
        var helpballoon = document.getElementById(ohelpId);
        var helpbutton = document.getElementById(obtnId);
        
        if (reverse) {
            if (flip) {
                helpballoon.style.left = getAbsoluteLeft(helpbutton) - 35 - left + 'px';
                helpballoon.style.top = (getAbsoluteTop(helpbutton) + 14) - top + 'px';
            }
            else {
                helpballoon.style.left = getAbsoluteLeft(helpbutton) - 35 - left + 'px';
                helpballoon.style.top = ((getAbsoluteTop(helpbutton) - helpballoon.clientHeight)) - top + 'px';
            }
        }
        else {
            if (flip) {
                helpballoon.style.left = getAbsoluteLeft(helpbutton) - 140 - left + 'px';
                helpballoon.style.top = (getAbsoluteTop(helpbutton) + 11) - top + 'px';
            }
            else {
                helpballoon.style.left = getAbsoluteLeft(helpbutton) - 140 - left + 'px';
                helpballoon.style.top = ((getAbsoluteTop(helpbutton) - helpballoon.clientHeight)) - top + 'px';
            }
        }
        
        if (isIE6()) {
            var helpballoon = document.getElementById(ohelpId);
            hideCollidedSelectBoxes(helpballoon);
        }
    }
    else {
        currentExpandedBtnId = null;
        currentExpandedHelpId = null;
        if (isIE6()) {
            showSelectBoxes(helpballoon);
        }
    }
}

function hideCollidedSelectBoxes(o) {
    var selectArray = document.getElementsByTagName('select');

    for (var i = 0; i < selectArray.length; i++) {
        if (detectCollision(o, selectArray[i])) {
            selectArray[i].style.visibility = 'hidden';
        }
    }
}

function showSelectBoxes(o) {
    var selectArray = document.getElementsByTagName('select');
    for (var i = 0; i < selectArray.length; i++) {
        selectArray[i].style.visibility = (selectArray[i].style.visibility == 'hidden') ? 'visible' : '';
    }
}

// author: slee@iconnicholson.com
// version: 1.0
// date: 2005-08-11
//
// collision detection theory
// for each pair of object, if one of their axis does not collide, then they do not collide
// implementation: loop through each axis and return false if they do not collide
// 
// method: detectCollision(a:Object, b:Object):Boolean
// a: document element object
// b: document element Object
// return: Boolean

function detectCollision(a, b) {

    // x-axis
    var xA = getAbsoluteLeft(a);
    var xB = getAbsoluteLeft(b);
    var wA = a.offsetWidth;
    var wB = b.offsetWidth;
    if (Math.max(xA + wA, xB + wB) - Math.min(xA, xB) > (wA + wB))
        return false;

    // y-axis
    var yA = getAbsoluteTop(a);
    var yB = getAbsoluteTop(b);
    var hA = a.offsetHeight;
    var hB = b.offsetHeight;
    if (Math.max(yA + hA, yB + hB) - Math.min(yA, yB) > (hA + hB))
        return false;

    return true;

}


// getAbsolutePosition.js (part of the SML vocabulary)
function getAbsoluteLeft(o) {
    var result = o.offsetLeft;
    var p = o.offsetParent;
    while (p != null) {
        result += p.offsetLeft;
        p = p.offsetParent;
    }
    return result;
}

function getAbsoluteTop(o) {
    var result = o.offsetTop;
    var p = o.offsetParent;
    while (p != null) {
        result += p.offsetTop;
        p = p.offsetParent;
    }
    return result;
}


function hideShowElement(elemId, show, tableRow) {
    if (show) {
        showElement(elemId, tableRow);
    }
    else {
        hideElement(elemId);
    }
}

// Hide an element using it's ID with javascript
// param elemId - Id of the element to hide
function hideElement(elemId) {
    hideElementObj(document.getElementById(elemId));
}

// Hide an element with javascript
// param elemId - Id of the element to hide
function hideElementObj(elem) {
    if (elem == null) {
        return;
    }
    elem.style.display = "none";
}

// Display an element using it's ID with javascript
// Note that table rows need a different command in IE and other browsers
// param elemId - Id of the element to show
// param tableRow - true if we are showing a tablerow TR element due to browser differences
function showElement(elemId, tableRow) {
    showElementObj(document.getElementById(elemId), tableRow);
}

// Display an element with javascript
// Note that table rows need a different command in IE and other browsers
// param elemId - element to show
// param tableRow - true if we are showing a tablerow TR element due to browser differences
function showElementObj(elem, tableRow) {
    if (elem == null) {
        return;
    }
    if (tableRow == null || isIE() || tableRow == false) {
        // IE
        elem.style.display = "block";
    }
    else {
        // OTHER
        elem.style.display = "table-row";
    }
}

function isElemVisible(elemId) {
    var elem = document.getElementById(elemId);
    if (elem == null) {
        return false;
    }
    return elem.style.display != "none";
}

function toggleElement(elemId, tableRow) {
    var elemObj = document.getElementById(elemId);
    if (elemObj == null) {
        return false;
    }
    if (isElemVisible(elemId)) {
        hideElement(elemId);
    }
    else {
        showElement(elemId, tableRow);
    }
    return true;
}