//-----------------------------------------------------------------------
// Copyright (C) Motorwebs Corporation. All rights reserved.
//-----------------------------------------------------------------------
// Helper Class

Type.registerNamespace('Motorwebs.UI');

Motorwebs.UI._Helper = function() { }
Motorwebs.UI._Helper.prototype = {

    isNumber: function(s) {
        if (s == "") return false;
        var re = /^[-]?\d*\.?\d*$/;
        s = s.toString();
        if (!s.match(re)) {
            return false;
        }
        return true;
    },

    parseNumber: function(num) {
        num = num.toString().replace(/\$/, '').replace(/\%/, '').replace(/,/, '');
        return isNaN(parseFloat(num)) ? 0 : parseFloat(num);
    },

    formatCurrency: function(num, showCents) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num)) num = "0";
        var sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        var 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));
        }
        var ret = "";
        if (showCents)
            ret = (((sign) ? '' : '-') + '$' + num + '.' + cents);
        else
            ret = (((sign) ? '' : '-') + '$' + num);
        return ret;
    },

    addCommas: function(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },

    isNotEmpty: function(el) {
        var str = el.value;
        var re = /.+/;
        if (!str.match(re) || ((el.title) == el.value)) {
            alert("Please fill in the required " + el.title + " field.");
            setTimeout("$helper.focusElement('" + el.name + "')", 0);
            return false;
        } else {
            return true;
        }
    },

    isChosen: function(select) {
        if (select.selectedIndex == 0) {
            alert("Please make a choice from the required " + select.name + " dropdown.");
            select.focus();
            return false;
        } else {
            return true;
        }
    },

    isValidRadio: function(radio) {
        var valid = false;
        for (var i = 0; i < radio.length; i++) {
            if (radio[i].checked) {
                return true;
            }
        }
        alert("Make a choice from the required " + radio[0].name + " radio buttons.");
        radio[0].focus();
        return false;
    },

    isEmailAddr: function(el) {
        var str = el.value;
        var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
        if (!str.match(re)) {
            alert("Not a valid email address! \nPlease verify the e-mail address format.");
            setTimeout("$helper.focusElement('" + el.id + "')", 0);
            return false;
        } else {
            return true;
        }
    },

    isPhoneNumber: function(el) {
        var n = 0, i = 0;
        var format = "### ###-####";
        var input = el.value;
        if (input.length > 0) {
            var chr = "";
            var numbers = "";
            //remove non-numbers and spaces
            for (i = 0; i < input.length; i++) {
                chr = input.charAt(i);
                if (!(isNaN(chr) || chr == " ")) numbers += chr;
            }
            if (numbers.length < 10) {
                alert("Please include the area code.");
                setTimeout("focusElement('" + el.name + "')", 0);
                return false;
            }
            //assign numbers to chosen format
            var output = "";
            while (i < format.length && n < numbers.length) {
                chr = format.charAt(i);
                output += (chr == "#") ? numbers.charAt(n++) : chr;
                i++;
            }
            el.value = output; //output to form element
            return true;
        }
        else {
            alert("Please enter a phone number with area code.");
            setTimeout("focusElement('" + el.name + "')", 0);
            return false;
        }
    },

    focusElement: function(elname) {
        var el = document.getElementsByName(elname);
        if (el.length > 0) {
            el[0].focus();
            el[0].select();
        }
        else {
            el = $get(elname);
            if (el) {
                el.focus();
                el.select();
            }
        }
    },

    getNextSibling: function(startBrother) {
        endBrother = startBrother.nextSibling;
        while (endBrother.nodeType != 1) {
            endBrother = endBrother.nextSibling;
        }
        return endBrother;
    },

    getFirstChild: function(parent) {
        if (!parent.childNodes.length) return;
        var children = parent.childNodes.length;
        for (var i = 0; i <= children; i++) {
            if (parent.childNodes[i].nodeType == 1) {
                return parent.childNodes[i];
            }
        }
        return;
    },

    getCurrentStyle: function(element, attribute, defaultValue) {
        var currentValue = null;
        if (element) {
            if (element.currentStyle) {
                currentValue = element.currentStyle[attribute];
            } else if (document.defaultView && document.defaultView.getComputedStyle) {
                var style = document.defaultView.getComputedStyle(element, null);
                if (style) {
                    currentValue = style[attribute];
                }
            }

            if (!currentValue && element.style.getPropertyValue) {
                currentValue = element.style.getPropertyValue(attribute);
            }
            else if (!currentValue && element.style.getAttribute) {
                currentValue = element.style.getAttribute(attribute);
            }
        }

        if ((!currentValue || currentValue == "" || typeof (currentValue) === 'undefined')) {
            if (typeof (defaultValue) != 'undefined') {
                currentValue = defaultValue;
            }
            else {
                currentValue = null;
            }
        }
        return currentValue;
    },

    getLocation: function(element) {
        // workaround for an issue in getLocation where it will compute the location of the document element.
        // this will return an offset if scrolled.
        //
        if (element === document.documentElement) {
            return new Sys.UI.Point(0, 0);
        }

        // Workaround for IE6 bug in getLocation (also required patching getBounds - remove that fix when this is removed)
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7) {
            if (element.window === element || element.nodeType === 9 || !element.getClientRects || !element.getBoundingClientRect) return new Sys.UI.Point(0, 0);

            // Get the first bounding rectangle in screen coordinates
            var screenRects = element.getClientRects();
            if (!screenRects || !screenRects.length) {
                return new Sys.UI.Point(0, 0);
            }
            var first = screenRects[0];

            // Delta between client coords and screen coords
            var dLeft = 0;
            var dTop = 0;

            var inFrame = false;
            try {
                inFrame = element.ownerDocument.parentWindow.frameElement;
            } catch (ex) {
                // If accessing the frameElement fails, a frame is probably in a different
                // domain than its parent - and we still want to do the calculation below
                inFrame = true;
            }

            // If we're in a frame, get client coordinates too so we can compute the delta
            if (inFrame) {
                // Get the bounding rectangle in client coords
                var clientRect = element.getBoundingClientRect();
                if (!clientRect) {
                    return new Sys.UI.Point(0, 0);
                }

                // Find the minima in screen coords
                var minLeft = first.left;
                var minTop = first.top;
                for (var i = 1; i < screenRects.length; i++) {
                    var r = screenRects[i];
                    if (r.left < minLeft) {
                        minLeft = r.left;
                    }
                    if (r.top < minTop) {
                        minTop = r.top;
                    }
                }

                // Compute the delta between screen and client coords
                dLeft = minLeft - clientRect.left;
                dTop = minTop - clientRect.top;
            }

            // Subtract 2px, the border of the viewport (It can be changed in IE6 by applying a border style to the HTML element,
            // but this is not supported by ASP.NET AJAX, and it cannot be changed in IE7.), and also subtract the delta between
            // screen coords and client coords
            var ownerDocument = element.document.documentElement;
            return new Sys.UI.Point(first.left - 2 - dLeft + ownerDocument.scrollLeft, first.top - 2 - dTop + ownerDocument.scrollTop);
        }

        return Sys.UI.DomElement.getLocation(element);
    },

    setLocation: function(element, point) {
        Sys.UI.DomElement.setLocation(element, point.x, point.y);
    },

    getBounds: function(element) {
        var offset = $helper.getLocation(element);
        return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0);
    },

    getClientBounds: function() {
        var clientWidth;
        var clientHeight;
        switch (Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }
        return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);
    },

    parseUnit: function(value) {
        if (!value) {
            throw Error.argumentNull('value');
        }

        value = value.trim().toLowerCase();
        var l = value.length;
        var s = -1;
        for (var i = 0; i < l; i++) {
            var ch = value.substr(i, 1);
            if ((ch < '0' || ch > '9') && ch != '-' && ch != '.' && ch != ',') {
                break;
            }
            s = i;
        }
        if (s == -1) {
            throw Error.create(Motorwebs.UI.Resources.Common_UnitHasNoDigits);
        }
        var type;
        var size;
        if (s < (l - 1)) {
            type = value.substring(s + 1).trim();
        } else {
            type = 'px';
        }
        size = parseFloat(value.substr(0, s + 1));
        if (type == 'px') {
            size = Math.floor(size);
        }
        return {
            size: size,
            type: type
        };
    },

    getElementOpacity: function(element) {
        if (!element) {
            throw Error.argumentNull('element');
        }

        var hasOpacity = false;
        var opacity;

        if (element.filters) {
            var filters = element.filters;
            if (filters.length !== 0) {
                var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                if (alphaFilter) {
                    opacity = alphaFilter.opacity / 100.0;
                    hasOpacity = true;
                }
            }
        }
        else {
            opacity = this.getCurrentStyle(element, 'opacity', 1);
            hasOpacity = true;
        }

        if (hasOpacity === false) {
            return 1.0;
        }
        return parseFloat(opacity);
    },

    setElementOpacity: function(element, value) {
        if (!element) {
            throw Error.argumentNull('element');
        }

        if (element.filters) {
            var filters = element.filters;
            var createFilter = true;
            if (filters.length !== 0) {
                var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                if (alphaFilter) {
                    createFilter = false;
                    alphaFilter.opacity = value * 100;
                }
            }
            if (createFilter) {
                element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (value * 100) + ')';
            }
        }
        else {
            element.style.opacity = value;
        }
    },

    createHistoryObj: function(hash) {
        hash = hash.substring(1, hash.length)
        var urlArr = hash.split('&');

        var s = "{";
        for (var i = 0; i < urlArr.length; i++) {
            prmArr = urlArr[i].split('=');
            if (i > 0) s += ", ";
            s += prmArr[0] + ":\"" + unescape(prmArr[1]) + "\"";
        }
        s += "}";

        var ho = eval('(' + s + ')');
        return ho;
    }
}  

var $helper = Motorwebs.UI.Helper = new Motorwebs.UI._Helper();