// higuery.js
// License : MIT
// version : 0.1.1

// $('.class') or $('#id') or $('//xpath') or $('tagName');

function $$(sel) {
    var self = this;

    var type = /^#(\w+)$|^\/\/(.*?)$|^\.(\w+)$|^(\w+)$/;
    sel.replace(type, function($0, $1, $2, $3, $4) {
        if($1) {
            self.elm = [];
            self.elm.push(document.getElementById(sel.replace('#', '')))
        } else if($2) {
            self.elm = [];
            var x = document.evaluate(sel, document, null, XPath.ORDERED_NODE_SNAPSHOT_TYPE, null);
            for(var i = 0; i < x.snapshotLength; i++) {
                self.elm.push(x.snapshotItem(i));
            }
        } else if($3) {
            self.elm = [];
            var tmp = document.getElementsByTagName('*');
            var class = sel.replace(/^\./, "")
            for(var i = 0; i < tmp.length; i++) {
                if(tmp[i].className == class) {
                    self.elm.push(tmp[i]);
                }
            }
        } else if($4) {
            self.elm = document.getElementsByTagName(sel)
        }
    });

    this.e2a();
    return this;
}

$$.prototype.e2a = function() {
    this.length = this.elm.length;
    for(var i = 0, len = this.length; i < len; i++) {
        this[i] = this.elm[i];
    }

    this.first = this[0]
    this.end = this[this.length - 1]
}

$$.prototype.addEvent = function (type, callback) {
    for(var i = 0; i < this.length; i++) {
        this[i].addEventListener(type, callback, false);
    }
    return this;
}
$$.prototype.each = function(func) {
    for(var i = 0; i < this.length; i++) {
        func(this[i]);
    }
    return this;
}

$$.prototype.filter = function(func) {
    this.elm = [];
    for(var i = 0; i < this.length; i++) {
        if(func(this[i])) {
            this.elm.push(this[i]);
        }
    }
    this.e2a();
    return this;
}

var $ = function(x) {
    return $[x] || ($[x] = new $$(x));
}

function log() {
    var res = Array.apply(null, arguments).join(", ")
    if(window.opera) {
        opera.postError(res);
    } else if (window.console) {
        console.log(res);
    } else {
        alert(res);
    }
}
