/*********************************************************************************
*  Code for use of bed and breakfast availability checker http://www.bed.gb.com  *
*  For information please contact Ben Gooding ben@site-designers.co.uk           * 
*********************************************************************************/

(function() {
    var Y = YAHOO.util,     
        getStyle,           
        setStyle,           
        id_counter = 0,     
        propertyCache = {}; 


    var ua = navigator.userAgent.toLowerCase(),
        isOpera = (ua.indexOf('opera') > -1),
        isSafari = (ua.indexOf('safari') > -1),
        isGecko = (!isOpera && !isSafari && ua.indexOf('gecko') > -1),
        isIE = (!isOpera && ua.indexOf('msie') > -1);


    var patterns = {
        HYPHEN: /(-[a-z])/i
    };


    var toCamel = function(property) {
        if ( !patterns.HYPHEN.test(property) ) {
            return property; 
        }

        if (propertyCache[property]) { 
            return propertyCache[property];
        }

        while( patterns.HYPHEN.exec(property) ) {
            property = property.replace(RegExp.$1,
                    RegExp.$1.substr(1).toUpperCase());
        }

        propertyCache[property] = property;
        return property;

    };


    if (document.defaultView && document.defaultView.getComputedStyle) { 
        getStyle = function(el, property) {
            var value = null;

            var computed = document.defaultView.getComputedStyle(el, '');
            if (computed) { 
                value = computed[toCamel(property)];
            }

            return el.style[property] || value;
        };
    } else if (document.documentElement.currentStyle && isIE) { // IE method
        getStyle = function(el, property) {
            switch( toCamel(property) ) {
                case 'opacity' :// IE opacity uses filter
                    var val = 100;
                    try { // will error if no DXImageTransform
                        val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;

                    } catch(e) {
                        try { // make sure its in the document
                            val = el.filters('alpha').opacity;
                        } catch(e) {
                        }
                    }
                    return val / 100;
                    break;
                default:
                    // test currentStyle before touching
                    var value = el.currentStyle ? el.currentStyle[property] : null;
                    return ( el.style[property] || value );
            }
        };
    } else { // default to inline only
        getStyle = function(el, property) { return el.style[property]; };
    }

    if (isIE) {
        setStyle = function(el, property, val) {
            switch (property) {
                case 'opacity':
                    if ( typeof el.style.filter == 'string' ) { // in case not appended
                        el.style.filter = 'alpha(opacity=' + val * 100 + ')';

                        if (!el.currentStyle || !el.currentStyle.hasLayout) {
                            el.style.zoom = 1; // when no layout or cant tell
                        }
                    }
                    break;
                default:
                el.style[property] = val;
            }
        };
    } else {
        setStyle = function(el, property, val) {
            el.style[property] = val;
        };
    }


    YAHOO.util.Dom = {

        get: function(el) {
            if (!el) { return null; } 

            if (typeof el != 'string' && !(el instanceof Array) ) { 
                return el;
            }

            if (typeof el == 'string') { // ID
                return document.getElementById(el);
            }
            else { // array of ID's and/or elements
                var collection = [];
                for (var i = 0, len = el.length; i < len; ++i) {
                    collection[collection.length] = Y.Dom.get(el[i]);
                }

                return collection;
            }

            return null; 
        },


        getStyle: function(el, property) {
            property = toCamel(property);

            var f = function(element) {
                return getStyle(element, property);
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        setStyle: function(el, property, val) {
            property = toCamel(property);

            var f = function(element) {
                setStyle(element, property, val);

            };

            Y.Dom.batch(el, f, Y.Dom, true);
        },


        getXY: function(el) {
            var f = function(el) {

            // has to be part of document to have pageXY
                if (el.parentNode === null || el.offsetParent === null ||
                        this.getStyle(el, 'display') == 'none') {
                    return false;
                }

                var parentNode = null;
                var pos = [];
                var box;

                if (el.getBoundingClientRect) { // IE
                    box = el.getBoundingClientRect();
                    var doc = document;
                    if ( !this.inDocument(el) && parent.document != document) {// might be in a frame, need to get its scroll
                        doc = parent.document;

                        if ( !this.isAncestor(doc.documentElement, el) ) {
                            return false;
                        }

                    }

                    var scrollTop = Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
                    var scrollLeft = Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);

                    return [box.left + scrollLeft, box.top + scrollTop];
                }
                else { // safari, opera, & gecko
                    pos = [el.offsetLeft, el.offsetTop];
                    parentNode = el.offsetParent;
                    if (parentNode != el) {
                        while (parentNode) {
                            pos[0] += parentNode.offsetLeft;
                            pos[1] += parentNode.offsetTop;
                            parentNode = parentNode.offsetParent;
                        }
                    }
                    if (isSafari && this.getStyle(el, 'position') == 'absolute' ) { // safari doubles in some cases
                        pos[0] -= document.body.offsetLeft;
                        pos[1] -= document.body.offsetTop;
                    }
                }

                if (el.parentNode) { parentNode = el.parentNode; }
                else { parentNode = null; }

                while (parentNode && parentNode.tagName.toUpperCase() != 'BODY' && parentNode.tagName.toUpperCase() != 'HTML')
                { // account for any scrolled ancestors
                    if (Y.Dom.getStyle(parentNode, 'display') != 'inline') { // work around opera inline scrollLeft/Top bug
                        pos[0] -= parentNode.scrollLeft;
                        pos[1] -= parentNode.scrollTop;
                    }

                    if (parentNode.parentNode) {
                        parentNode = parentNode.parentNode;
                    } else { parentNode = null; }
                }


                return pos;
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        getX: function(el) {
            var f = function(el) {
                return Y.Dom.getXY(el)[0];
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        getY: function(el) {
            var f = function(el) {
                return Y.Dom.getXY(el)[1];
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        setXY: function(el, pos, noRetry) {
            var f = function(el) {
                var style_pos = this.getStyle(el, 'position');
                if (style_pos == 'static') { // default to relative
                    this.setStyle(el, 'position', 'relative');
                    style_pos = 'relative';
                }

                var pageXY = this.getXY(el);
                if (pageXY === false) { // has to be part of doc to have pageXY
                    return false;
                }

                var delta = [ // assuming pixels; if not we will have to retry
                    parseInt( this.getStyle(el, 'left'), 10 ),
                    parseInt( this.getStyle(el, 'top'), 10 )
                ];

                if ( isNaN(delta[0]) ) {// in case of 'auto'
                    delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
                }
                if ( isNaN(delta[1]) ) { // in case of 'auto'
                    delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
                }

                if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
                if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }

                var newXY = this.getXY(el);

                // if retry is true, try one more time if we miss
                if (!noRetry && (newXY[0] != pos[0] || newXY[1] != pos[1]) ) {
                    this.setXY(el, pos, true);
                }

            };

            Y.Dom.batch(el, f, Y.Dom, true);
        },


        setX: function(el, x) {
            Y.Dom.setXY(el, [x, null]);
        },


        setY: function(el, y) {
            Y.Dom.setXY(el, [null, y]);
        },


        getRegion: function(el) {
            var f = function(el) {
                var region = new Y.Region.getRegion(el);
                return region;
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        getClientWidth: function() {
            return Y.Dom.getViewportWidth();
        },


        getClientHeight: function() {
            return Y.Dom.getViewportHeight();
        },


        getElementsByClassName: function(className, tag, root) {
            var method = function(el) { return Y.Dom.hasClass(el, className); };
            return Y.Dom.getElementsBy(method, tag, root);
        },


        hasClass: function(el, className) {
            var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');

            var f = function(el) {
                return re.test(el['className']);
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        addClass: function(el, className) {
            var f = function(el) {
                if (this.hasClass(el, className)) { return; } // already present


                el['className'] = [el['className'], className].join(' ');
            };

            Y.Dom.batch(el, f, Y.Dom, true);
        },


        removeClass: function(el, className) {
            var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', 'g');

            var f = function(el) {
                if (!this.hasClass(el, className)) { return; } // not present


                var c = el['className'];
                el['className'] = c.replace(re, ' ');
                if ( this.hasClass(el, className) ) { // in case of multiple adjacent
                    this.removeClass(el, className);
                }

            };

            Y.Dom.batch(el, f, Y.Dom, true);
        },


        replaceClass: function(el, oldClassName, newClassName) {
            if (oldClassName === newClassName) { // avoid infinite loop
                return false;
            }

            var re = new RegExp('(?:^|\\s+)' + oldClassName + '(?:\\s+|$)', 'g');

            var f = function(el) {

                if ( !this.hasClass(el, oldClassName) ) {
                    this.addClass(el, newClassName); // just add it if nothing to replace
                    return; // note return
                }

                el['className'] = el['className'].replace(re, ' ' + newClassName + ' ');

                if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
                    this.replaceClass(el, oldClassName, newClassName);
                }
            };

            Y.Dom.batch(el, f, Y.Dom, true);
        },


        generateId: function(el, prefix) {
            prefix = prefix || 'yui-gen';
            el = el || {};

            var f = function(el) {
                if (el) {
                    el = Y.Dom.get(el);
                } else {
                    el = {}; // just generating ID in this case
                }

                if (!el.id) {
                    el.id = prefix + id_counter++;
                } // dont override existing


                return el.id;
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },


        isAncestor: function(haystack, needle) {
            haystack = Y.Dom.get(haystack);
            if (!haystack || !needle) { return false; }

            var f = function(needle) {
                if (haystack.contains && !isSafari) { // safari "contains" is broken
                    return haystack.contains(needle);
                }
                else if ( haystack.compareDocumentPosition ) {
                    return !!(haystack.compareDocumentPosition(needle) & 16);
                }
                else { // loop up and test each parent
                    var parent = needle.parentNode;

                    while (parent) {
                        if (parent == haystack) {
                            return true;
                        }
                        else if (!parent.tagName || parent.tagName.toUpperCase() == 'HTML') {
                            return false;
                        }

                        parent = parent.parentNode;
                    }
                    return false;
                }
            };

            return Y.Dom.batch(needle, f, Y.Dom, true);
        },


        inDocument: function(el) {
            var f = function(el) {
                return this.isAncestor(document.documentElement, el);
            };

            return Y.Dom.batch(el, f, Y.Dom, true);
        },

        getElementsBy: function(method, tag, root) {
            tag = tag || '*';
            root = Y.Dom.get(root) || document;

            var nodes = [];
            var elements = root.getElementsByTagName(tag);

            if ( !elements.length && (tag == '*' && root.all) ) {
                elements = root.all; // IE < 6
            }

            for (var i = 0, len = elements.length; i < len; ++i) {
                if ( method(elements[i]) ) { nodes[nodes.length] = elements[i]; }
            }


            return nodes;
        },

        batch: function(el, method, o, override) {
            var id = el;
            el = Y.Dom.get(el);

            var scope = (override) ? o : window;

            if (!el || el.tagName || !el.length) { 
                if (!el) {
                    return false;
                }
                return method.call(scope, el, o);
            }

            var collection = [];

            for (var i = 0, len = el.length; i < len; ++i) {
                if (!el[i]) {
                    id = el[i];
                }
                collection[collection.length] = method.call(scope, el[i], o);
            }

            return collection;
        },


        getDocumentHeight: function() {
            var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;

            var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
            return h;
        },


        getDocumentWidth: function() {
            var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
            var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
            return w;
        },


        getViewportHeight: function() {
            var height = self.innerHeight; // Safari, Opera
            var mode = document.compatMode;

            if ( (mode || isIE) && !isOpera ) { // IE, Gecko
                height = (mode == 'CSS1Compat') ?
                        document.documentElement.clientHeight : // Standards
                        document.body.clientHeight; // Quirks
            }

            return height;
        },


        getViewportWidth: function() {
            var width = self.innerWidth;  // Safari
            var mode = document.compatMode;

            if (mode || isIE) { // IE, Gecko, Opera
                width = (mode == 'CSS1Compat') ?
                        document.documentElement.clientWidth : // Standards
                        document.body.clientWidth; // Quirks
            }
            return width;
        }
    };
})();

YAHOO.util.Region = function(t, r, b, l) {


    this.top = t;


    this[1] = t;


    this.right = r;


    this.bottom = b;


    this.left = l;


    this[0] = l;
};


YAHOO.util.Region.prototype.contains = function(region) {
    return ( region.left   >= this.left   &&
             region.right  <= this.right  &&
             region.top    >= this.top    &&
             region.bottom <= this.bottom    );

};


YAHOO.util.Region.prototype.getArea = function() {
    return ( (this.bottom - this.top) * (this.right - this.left) );
};


YAHOO.util.Region.prototype.intersect = function(region) {
    var t = Math.max( this.top,    region.top    );
    var r = Math.min( this.right,  region.right  );
    var b = Math.min( this.bottom, region.bottom );
    var l = Math.max( this.left,   region.left   );

    if (b >= t && r >= l) {
        return new YAHOO.util.Region(t, r, b, l);
    } else {
        return null;
    }
};


YAHOO.util.Region.prototype.union = function(region) {
    var t = Math.min( this.top,    region.top    );
    var r = Math.max( this.right,  region.right  );
    var b = Math.max( this.bottom, region.bottom );
    var l = Math.min( this.left,   region.left   );

    return new YAHOO.util.Region(t, r, b, l);
};


YAHOO.util.Region.prototype.toString = function() {
    return ( "Region {"    +
             "top: "       + this.top    +
             ", right: "   + this.right  +
             ", bottom: "  + this.bottom +
             ", left: "    + this.left   +
             "}" );
};


YAHOO.util.Region.getRegion = function(el) {
    var p = YAHOO.util.Dom.getXY(el);

    var t = p[1];
    var r = p[0] + el.offsetWidth;
    var b = p[1] + el.offsetHeight;
    var l = p[0];

    return new YAHOO.util.Region(t, r, b, l);
};


YAHOO.util.Point = function(x, y) {
   if (x instanceof Array) { // accept output from Dom.getXY
      y = x[1];
      x = x[0];
   }



    this.x = this.right = this.left = this[0] = x;


    this.y = this.top = this.bottom = this[1] = y;
};

YAHOO.util.Point.prototype = new YAHOO.util.Region();

