/**
 * $Id: DomUtils.js 31521 2006-11-02 00:32:16Z philip $
 * $Author: philip $
 * $Revision: 31521 $
 * $Name$
 * $Date: 2006-11-01 16:32:16 -0800 (Wed, 01 Nov 2006) $
 *
 * @jsRequire DomUtils
 * @jsRequire interfaces.Interface
 *
 *
 * @version    $Revision: 31521 $
 * @author     Philip Snyder <philip@pricegrabber.com>
 * @copyright  Copyright &copy; 2006, Philip Snyder, PriceGrabber.com
 * @see        interfaces.Interface
 */

/**
 * DomUtils function namespace
 *
 *
 * @access public
 * @since  v1.1
 */
var DomUtils = new Object;


/**
 * Browser detection function namespace
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser = new Object;

/**
 * RegEx definitions for browser detections based on property tested
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.regexes = {
    overflowX: new Array(/Firefox\/1\.0/),
    overflowY: new Array(/Firefox\/1\.0/)
};

/**
 * Determines if the browser supports CSS overflowX property correctly
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.supportsOverflowX = function() {
    for (var i=0; i<DomUtils.browser.regexes.overflowX.length; i++) {
        var regex = DomUtils.browser.regexes.overflowX[i];
        if (navigator.userAgent.match(regex)) {
            return false;
        }
    }
    return true;
}

/**
 * Determines if the browser supports CSS overflowY property correctly
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.supportsOverflowY = function() {
    for (var i=0; i<DomUtils.browser.regexes.overflowY.length; i++) {
        var regex = DomUtils.browser.regexes.overflowY[i];
        if (navigator.userAgent.match(regex)) {
            return false;
        }
    }
    return true;
}

/**
 * Determines if the browser supports the Document Object Model
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.supportsDom = function() {
    return (document.getElementById) ? true : false;
}

/**
 * Determines if the browser is Internet Explorer
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.isIE = function() {
    return (document.all && navigator.appName.indexOf('Microsoft Internet Explorer') > -1) ? true : false;
}

/**
 * Determines if the browser is Safari
 *
 * @access public
 * @since  v1.4.8.1.2.4
 */
DomUtils.browser.isSafari = function() {
    return (navigator.userAgent.toLowerCase().indexOf('safari') > -1) ? true : false;
}







/**
 * Fixes pseudo-leaks in Internet Explorer.
 *
 * Use this method anytime you need to remove an element
 * since it will do it in a memory clean manner for both
 * Internet Explorer and Firefox.
 *
 * @access public
 * @since  v1.4.8.1.2
 * @param  DomNode   elem
 * @return void
 */
DomUtils.removeElement = function(elem) {
    if (DomUtils.browser.isIE()) {
        var garbageBin = document.getElementById('IELeakGarbageBin');
        if (!garbageBin) {
            garbageBin = document.createElement('DIV');
            garbageBin.id = 'IELeakGarbageBin';
            garbageBin.style.display = 'none';
            document.body.appendChild(garbageBin);
        }
        // move the element to the garbage bin
        garbageBin.appendChild(elem);
        garbageBin.innerHTML = '';
    } else {
        elem.parentNode.removeChild(elem);
    }
}




/**
 * Returns the window width in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Window    win    Window object (optional)
 * @return integer
 */
DomUtils.getWindowWidth   = function(win) {
    win = (win) ? win : window;
    if (document.compatMode == 'CSS1Compat') return parseInt(win.document.body.parentNode.clientWidth);
    else if (DomUtils.browser.isIE())        return parseInt(win.document.body.clientWidth);
    else                                     return parseInt(win.innerWidth);
}


/**
 * Returns the window height in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Window    win    Window object (optional)
 * @return integer
 */
DomUtils.getWindowHeight  = function(win) {
    win = (win) ? win : window;
    if (document.compatMode == 'CSS1Compat') return parseInt(win.document.body.parentNode.clientHeight);
    else if (DomUtils.browser.isIE())        return parseInt(win.document.body.clientHeight);
    else                                     return parseInt(win.innerHeight);
}


/**
 * Returns the window's scrolled position on the x-axis in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Window    win    Window object (optional)
 * @return integer
 */
DomUtils.getWindowScrollX = function(win) {
    win = (win) ? win : window;
    if (document.compatMode == 'CSS1Compat') return parseInt(win.document.body.parentNode.scrollLeft);
    else if (DomUtils.browser.isIE())        return parseInt(win.document.body.scrollLeft);
    else                                     return parseInt(win.scrollX);
}


/**
 * Returns the window's scrolled position on the y-axis in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Window    win    Window object (optional)
 * @return integer
 */
DomUtils.getWindowScrollY = function(win) {
    win = (win) ? win : window;
    if (document.compatMode == 'CSS1Compat') return parseInt(win.document.body.parentNode.scrollTop);
    else if (DomUtils.browser.isIE())        return parseInt(win.document.body.scrollTop);
    else                                     return parseInt(win.scrollY);
}


///**
// * Returns the element's width after css clipping
// *
// * @access public
// * @since  v1.1
// * @deprecated       Unnecessary -- I think. Keep the code just in case
// * @param  Element   elem  Element to get the clip width
// * @return integer
// */
//DomUtils.getElementClipWidth = function(elem) {
//    var currStyle = DomUtils.getCurrentStyle(elem);
//    var pre = document.createElement('pre');
//    var str = "current style props:\n";
//    for (var prop in currStyle) {
//        str += prop+": "+currStyle[prop]+"\n";
//    }
//    pre.appendChild(document.createTextNode(str));
//    document.body.appendChild(pre);
//}


/**
 * Returns the element width in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Element    elem    Element object
 * @return integer
 */
DomUtils.getElementWidth  = function(elem) {
    var eStyle, prop, width;
    var w = 0;
    if (elem.tagName == 'IMG')                    w = parseInt(elem.width);
    else if (document.compatMode == 'CSS1Compat') w = parseInt(elem.offsetWidth);
    else if (document.compatMode == 'BackCompat') {
        eStyle = DomUtils.getCurrentStyle(elem);
        width  = parseInt(eStyle.width);
        if (DomUtils.browser.isIE()) width = elem.offsetWidth;
        var bLeft  = parseInt(eStyle.borderLeft);
        var bRight = parseInt(eStyle.borderRight);
        var pLeft  = parseInt(eStyle.paddingLeft);
        var pRight = parseInt(eStyle.paddingRight);
        w  = parseInt(width);
        w += !isNaN(bLeft)  ? parseInt(bLeft)  : 0;
        w += !isNaN(bRight) ? parseInt(bRight) : 0;
        w += !isNaN(pLeft)  ? parseInt(pLeft)  : 0;
        w += !isNaN(pRight) ? parseInt(pRight) : 0;
    } else if (DomUtils.browser.isSafari()) {
        if (typeof(writeDebug) == 'function') writeDebug('browser is safari...');
        width = elem.offsetWidth;
        w = parseInt(width);
    }
    return w;
}


/**
 * Returns the element height in pixels (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Element    elem    Element object
 * @return integer
 */
DomUtils.getElementHeight = function(elem) {
    var h = 0;
    var eStyle, height;
    if (elem.tagName && elem.tagName == 'IMG')    h = parseInt(elem.height);
    else if (document.compatMode == 'CSS1Compat') h = parseInt(elem.offsetHeight);
    else if (document.compatMode == 'BackCompat') {
        eStyle  = DomUtils.getCurrentStyle(elem);
        height  = parseInt(eStyle.height);
        if (DomUtils.browser.isIE()) height = elem.offsetHeight;
        var bTop    = parseInt(eStyle.borderTop);
        var bBottom = parseInt(eStyle.borderBottom);
        var pTop    = parseInt(eStyle.paddingTop);
        var pBottom = parseInt(eStyle.paddingBottom);
        h  = parseInt(height);
        if (!DomUtils.browser.isIE()) {
            h += !isNaN(bTop)    ? parseInt(bTop)    : 0;
            h += !isNaN(bBottom) ? parseInt(bBottom) : 0;
            h += !isNaN(pTop)    ? parseInt(pTop)    : 0;
            h += !isNaN(pBottom) ? parseInt(pBottom) : 0;
        } else {
            h -= !isNaN(bTop) ? parseInt(bTop) : 0;
            h -= !isNaN(bBottom) ? parseInt(bBottom) : 0;
        }
    } else if (DomUtils.browser.isSafari()) {
        height = elem.offsetHeight;
        h = parseInt(height);
    }
    return h;
}


/**
 * Returns the element's left position in pixels (integer form)
 *
 * @todo   add error handling code -- find out what falls into catch code block
 * @access public
 * @since  v1.1
 * @param  Element    elem    Element object
 * @return integer
 */
DomUtils.getElementLeft   = function DomUtils_GetElementLeft(elem) {
    var left = 0;
    try {
        if (elem.offsetParent) {
            while (elem.offsetParent) {
                left += parseInt(elem.offsetLeft);
                elem  = elem.offsetParent;
            }
        } else if (elem.x) {
            left += parseInt(elem.x);
        }
        return left;
    } catch (e) {
        /**
         */
        return 0;
    }
}


/**
 * Returns the element's top position in pixels (integer form)
 *
 * @todo   add error handling code -- find out what falls into catch code block
 * @access public
 * @since  v1.1
 * @param  Element    elem    Element object
 * @return integer
 */
DomUtils.getElementTop    = function(elem) {
    try {
        var top = 0;
        if (elem.offsetParent) {
            while (elem.offsetParent) {
                top += parseInt(elem.offsetTop);
                elem = elem.offsetParent;
            }
        } else if (elem.y) {
            top += parseInt(elem.y);
        }
        return top;
    } catch (e) {
        return 0;
    }
}







/**
 * Centers an element inside its window.
 *
 * @access public
 * @since  v1.1
 * @param  Element    elem    Element object
 * @return void
 */
DomUtils.center = function(elem) {
    var wWidth  = parseInt(DomUtils.getWindowWidth());
    var wHeight = parseInt(DomUtils.getWindowHeight());
    var eWidth  = parseInt(DomUtils.getElementWidth(elem));
    var eHeight = parseInt(DomUtils.getElementHeight(elem));
    var xScroll = parseInt(DomUtils.getWindowScrollX());
    var yScroll = parseInt(DomUtils.getWindowScrollY());
    
    var left = parseInt(wWidth / 2) - parseInt(eWidth / 2) + xScroll;
    var top  = parseInt(wHeight / 2) - parseInt(eHeight / 2) + yScroll;
    elem.style.left = left+'px';
    elem.style.top  = top+'px';
}







/**
 * Returns the element's current style object
 *
 * @access public
 * @since  v1.1
 * @param  Element   elem   Element object
 * @return Style
 */
DomUtils.getCurrentStyle  = function(elem) {
    if (elem && elem.currentStyle) {
        return elem.currentStyle;
    } else if (document.defaultView && document.defaultView.getComputedStyle) {
        return document.defaultView.getComputedStyle(elem, '');
    }
}

/**
 * Copies the current style applied on element 1 to element 2.
 * 
 * @access public
 * @since  v1.8
 * @param  Element    elem1
 * @param  Element    elem2
 * @return void
 */
DomUtils.duplicateStyle = function(elem1, elem2) {
    var style1 = DomUtils.getCurrentStyle(elem1);
    //var str = 'style1: '+style1+"<br/>\n";
    for (prop in style1) {
        try {
            //elem2.style[prop] = style1[prop];
            eval('elem2.style.'+prop+' = style1.'+prop);
            //var span = document.createElement('span');
            //span.innerHTML = 'set style1.'+prop+': '+style1[prop]+"<br/>\n";
            //document.getElementsByTagName('body')[0].appendChild(span);
        } catch(e) {
            //var span = document.createElement('span');
            //span.innerHTML = 'failed setting style1.'+prop+': '+style1[prop]+"<br/>\n";
            //document.getElementsByTagName('body')[0].appendChild(span);
        }
    }
};


/**
 * Returns the element's zIndex attribute (integer form)
 *
 * @access public
 * @since  v1.1
 * @param  Element   elem   Element object
 * @return integer
 */
DomUtils.getZIndex = function(elem) {
    var eStyle = DomUtils.getCurrentStyle(elem);
    var zIdx   = 0;
    if (eStyle.zIndex && isNaN(eStyle.zIndex)) {
        if (elem.offsetParent) {
            while (elem.offsetParent) {
                zIdx   = (parseInt(eStyle.zIndex) > zIdx) ? parseInt(eStyle.zIndex) : zIdx;
                eStyle = DomUtils.getCurrentStyle(elem);
                elem   = elem.offsetParent;
            }
        }
    } else {
        zIdx = parseInt(eStyle.zIndex);
    }
    return zIdx;
}




///**
// * alerts an image's ready state if not complete
// *
// * @access public
// * @deprecated       I highly doubt this is used anywhere?
// * @since  v1.1
// * @param  Window    win    Window object (optional)
// * @return integer
// */
//DomUtils.checkImage = function() {
//    if (this.readyState != 'complete') {
//        alert(this.src+"\n"+this.readyState);
//    }
//}




/**
 * Returns a reference to the document's body tag
 *
 * @access public
 * @since  v1.1
 * @return Element
 */
DomUtils.getBody = function() {
    return document.getElementsByTagName('body')[0];
}





/**
 * Returns the window height in pixels (integer form)
 *
 * This should probably be deprecated / removed in favor
 * of net.RequestQueue
 *
 * @access public
 * @deprecated       Use net.RequestQueue instead
 * @since  v1.1
 * @return integer
 */
DomUtils.XmlHttp = function() {
    var request = null;
    try {
        ActiveXObject.prototype.jsonRequest = null;
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            ActiveXObject.prototype.jsonRequest = null;
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            try {
                XMLHttpRequest.prototype.jsonRequest = null;
                request = new XMLHttpRequest();
            } catch (e) {
                //request = new IframeHttpRequest();
                request = null;
            }
        }
    }
    return request;
}




















/**
 * Adds method function to Function objects
 *
 * @access public
 * @since  v1.1
 * @param  string    name   Name of the method to create
 * @param  Function  func   Function reference to assign to the method
 * @return Function
 */
Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
}

/**
 * Returns true if param is not a javascript object
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isAlien(a) {
   return isObject(a) && typeof a.constructor != 'function';
}

/**
 * Returns true if the param is an array
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isArray(a) {
    return isObject(a) && a.constructor == Array;
}

/**
 * Returns true if the param is a boolean data type
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean 
 */
function isBoolean(a) {
    return typeof a == 'boolean';
}

/**
 * Returns true if the param is empty (contains no value)
 *
 * @access public
 * @since  v1.1
 * @param  mixed     o      test this param
 * @return boolean
 */
function isEmpty(o) {
    var i, v;
    if (isObject(o)) {
        for (i in o) {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) {
                return false;
            }
        }
    }
    return true;
}

/**
 * Returns true if the param is a float
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isFloat(a) {
    return typeof a == 'number' && parseFloat(a) == a;
}

/**
 * Returns true if the param is a function
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isFunction(a) {
    return typeof a == 'function';
}

/**
 * Returns true if the param is an integer
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isInteger(a) {
    return typeof a == 'number' && parseInt(a) == a;
}

/**
 * Returns true if the param is null
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isNull(a) {
    return typeof a == 'object' && !a;
}

/**
 * Returns true if the param is a number
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/**
 * Returns true if the param is an object
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

/**
 * Returns true if the param is a string
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isString(a) {
    return typeof a == 'string';
}

/**
 * Returns true if the param is undefined
 *
 * @access public
 * @since  v1.1
 * @param  mixed     a      test this param
 * @return boolean
 */
function isUndefined(a) {
    return typeof a == 'undefined';
}




































/** BEGIN getElementsBySelector CODE ******************************************/

/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelect('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/
/** END getElementsBySelector CODE ********************************************/

// Alias old DomUtils.getElementsBySelector to this same function
// in order to maintain compatibility if anyone was using the old one
DomUtils.getElementsBySelector = document.getElementsBySelector;



