/*	This work is licensed under Creative Commons GNU LGPL License.

	License: http://creativecommons.org/licenses/LGPL/2.1/

	Author:  Stefan Goessner/2005
	Web:     http://goessner.net/ 
*/

var global = this;

window.addListener = function(obj, type, listener, capture) {
   if (obj.addEventListener)   // W3C DOM ..
      obj.addEventListener(type, listener, capture);
   else if (obj.attachEvent) { // IE 5/6 ..
      if (!obj.eventListeners)
         obj.eventListeners = [];
      if (!obj.eventListeners[type]) {
         obj.eventListeners[type] = true;
         obj.attachEvent("on"+type, listener);
      }
   }
}
window.removeListener = function(obj, type, listener, capture) {
   if (obj.removeEventListener) // W3C DOM ..
      obj.removeEventListener(type, listener, capture);
   else if (obj.detachEvent) {  // IE 5/6 ..
      if (obj.eventListeners && obj.eventListeners[type]) {
         obj.eventListeners[type] = false;
         obj.detachEvent("on"+type, listener);
      }
   }
}
window.registerBehaviour = function(rules) {
   var register = function() {
      var elems;
      for (selector in rules) {
         if (elems = document.getElementsBySelector(selector))
            for (var i=0; i<elems.length; i++) {
               if (typeof(rules[selector]) == "object") // array of event listeners assumed ..
                  for (hdl in rules[selector])
                     window.addListener(elems[i], hdl, rules[selector][hdl]);
               else if (typeof(rules[selector]) == "function") // callback function ..
                  rules[selector](elems[i]);
            }
      }
   };
   window.addListener(window, "load", register, true);
}
window.remoteJson = function(listener) {
   if (listener && listener.uri) {
      var script = document.getElementById("remotejson");
      if (script) // script element may exist from previous call, so ..
         script.parentNode.removeChild(script);  // .. delete it.
      script = document.createElement("script");	// new 'script' element.
      script.setAttribute("type", "text/javascript");
      script.setAttribute("id", "remotejson");
      script.setAttribute("src", listener.uri);
      document.getElementsByTagName("head")[0].appendChild(script);
   }
   if (listener && listener.condition && listener.callback)
      var timer = setInterval(function(){
                                 if (eval(listener.condition)) {
                                    clearInterval(timer);
                                    listener.callback(listener.target);
                                 }
                              }, 
                              500);
}
window.toJson = function(o, tab, indent) {
   var ind = (tab=tab||"")?"\n"+(indent||"") : "";
   if (o != null && typeof(o.constructor) != "undefined")
      switch(o.constructor) { 
         case Boolean:
         case Number:
            return o.toString();
         case String:
            return "\"" + o.replace(/[\\]/g, "\\\\").replace(/["]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r') + "\"";
         case Array:
            var a = [];
            for (var i = 0; i < o.length; i++)
               a[i] = window.toJson(o[i], tab, !!tab?(indent||"")+tab:tab);
            return "[" + ind+tab + a.join("," + ind+tab) + ind + "]";
         default:  // object 
            var a = [];
            for (var p in o)
               if (typeof(o[p]) != "undefined" && typeof(o[p]) != "function")
                  a.push('"'+p+'"' + (!!tab?": ":":") + global.toJson(o[p], tab, !!tab?(indent||"")+tab:tab));
            return "{" + ind+tab + a.join("," + ind+tab) + ind + "}";
      }
   return "null";
}

global.jsonT = function (self, rules) {
   var T = {
      output: false,
      init: function() {
         for (var rule in rules)
            if (rule.substr(0,4) != "self")
               rules["self."+rule] = rules[rule];
         return this;
      },
      apply: function(expr) {
         var trf = function(s){ return s.replace(/{([A-Za-z0-9_\$\.\[\]\'@\(\)]+)}/g, 
                                  function($0,$1){return T.processArg($1, expr);})},
             x = expr.replace(/\[[0-9]+\]/g, "[*]"), res;
         if (x in rules) {
            if (typeof(rules[x]) == "string")
               res = trf(rules[x]);
            else if (typeof(rules[x]) == "function")
               res = trf(rules[x](eval(expr)).toString());
         }
         else 
            res = T.eval(expr);
         return res;
      },
      processArg: function(arg, parentExpr) {
         var expand = function(a,e){return (e=a.replace(/^\$/,e)).substr(0,4)!="self" ? ("self."+e) : e; },
             res = "";
         T.output = true;
         if (arg.charAt(0) == "@")
            res = eval(arg.replace(/@([A-za-z0-9_]+)\(([A-Za-z0-9_\$\.\[\]\']+)\)/, 
                                   function($0,$1,$2){return "rules['self."+$1+"']("+expand($2,parentExpr)+")";}));
         else if (arg != "$")
            res = T.apply(expand(arg, parentExpr));
         else
            res = T.eval(parentExpr);
         T.output = false;
         return res;
      },
      eval: function(expr) {
         var v = eval(expr), res = "";
         if (typeof(v) != "undefined") {
            if (v instanceof Array) {
               for (var i=0; i<v.length; i++)
                  if (typeof(v[i]) != "undefined")
                     res += T.apply(expr+"["+i+"]");
            }
            else if (typeof(v) == "object") {
               for (var m in v)
                  if (typeof(v[m]) != "undefined")
                     res += T.apply(expr+"."+m);
            }
            else if (T.output)
               res += v;
         }
         return res;
      }
   };
   return T.init().apply("self");
}

// elements can have multiple class names ..
global.hasClassName = function(elem, classname) {
   var classattr=elem.getAttribute("class");
   return !!classattr && classattr.indexOf(classname) >= 0;
}
global.setClassName = function(elem, classname) {
   if (!global.hasClassName(elem, classname)) {
      var classattr = elem.getAttribute("class");
      elem.setAttribute("class", classattr ? classattr + " " + classname : classname);
   }
}
global.removeClassName = function(elem, classname) {
   if (global.hasClassName(elem, classname))
      elem.setAttribute("class", elem.getAttribute("class").replace(classname, "").replace(/^ | $/, ""));
}
global.replaceClassName = function(elem, oldname, newname) {
   if (global.hasClassName(elem, oldname))
      elem.setAttribute("class", elem.getAttribute("class").replace(oldname, newname));
}

global.keylookup = [];
global.processkey = function(evt) {
   evt = evt || window.event;
   var key = evt.keyCode || evt.which;
   for (var cmd in global.keylookup) {
      if (key == cmd.key && (!!evt.ctrlKey == cmd.ctrl) && (!!evt.altKey == cmd.alt)) {
         cmd.callback(evt);
         if (evt.preventDefault) {
            evt.preventDefault();
            evt.stopPropagation();
         } 
         else
            evt.returnValue = false;
         return false;
      }
   }
   return true;
}

window.dump = function(o) {
   var s="";
   for (var p in o) s+=p+" ";
   return s;
}

document.getElementsByClassName = function(classname, tagname, parent) {
   var elems = (parent||document).getElementsByTagName(tagname||"*"), classattr = null, found = [];
   for (var i=0; i<elems.length; i++) {
      if ((classattr=(elems[i].attributes && elems[i].attributes["class"])) && classattr.nodeValue.match("\\b"+classname+"\\b"))
         found[found.length] = elems[i];
   }
   return found;
}
document.getElementByAttribute = function(tagname, attname, attvalue, parent) {
   var elems = (parent||document).getElementsByTagName(tagname||"*");
   for (var i=0; i<elems.length; i++) {
      if (elems[i].attributes && elems[i].attributes[attname] && (!attvalue || elems[i].attributes[attname].nodeValue == attvalue))
         return elems[i];
   }
   return null;
}

/*
   The following code is Copyright (C) Simon Willison 2004.

   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 
*/
document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }

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

  // 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 (!currentContext[0]){
    	return;
    }
    
    // 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
*/

/*
var Core = {
   // credits for listener methods go to Scott Andrew LePera (http://www.scottandrew.com/weblog/articles/cbs-events)
   addListener: function(obj, evtname, fnc, capture) {
      return obj ? (obj.addEventListener ? (obj.addEventListener(evtname, fnc, capture),true) :
                    obj.attachEvent ? obj.attachEvent("on"+evtname, fnc) : null)
                 : null;
   },
   removeListener: function(obj, evtname, fnc, capture) {
      return obj ? (obj.removeEventListener ? (obj.removeEventListener(evtname, fnc, capture),true) :
                    obj.detachEvent ? obj.detachEvent("on"+evtname, fnc) : null)
                 : null;
   },
   getChildByClassName: function(parent, classname, tagname) {
      var elems = parent.getElementsByTagName(tagname||"*"), classattr = null;
      for (var i=0; i<elems.length; i++)
         if ((classattr=(elems[i].attributes && elems[i].attributes["class"])) && classattr.nodeValue.match("\\b"+classname+"\\b"))
            return elems[i];
      return null;
   },
   hasClassName: function(elem, classname) {
      var classattr=elem.attributes["class"];
      return classattr && classattr.nodeValue.match("\\b"+classname+"\\b");
   },
   replaceClassName: function(elem, oldname, newname) {
      var classattr=elem.attributes["class"];
      if (classattr) classattr.nodeValue = classattr.nodeValue.replace(oldname, newname);
   },
   plusminus: function(img) {
      var node = img.parentNode,
          classattr = node && node.nodeType == 1 ? node.attributes["class"] : false, 
          imgsrc = img ? img.attributes["src"] : false,
          toggle = function(att, attval) { if (att && attval) att.nodeValue = attval.match(/plus/) ? attval.replace(/plus/, "minus") : attval.replace(/minus/, "plus"); };
      toggle(classattr, classattr ? classattr.nodeValue : false);
      toggle(imgsrc, imgsrc ? imgsrc.nodeValue : false);
   },
   abbr2span: function() {
      if (document.all) // necessary for ie only ..
        document.body.innerHTML = document.body.innerHTML.replace(/<abbr([^>]*)>([^<]*)<\/abbr>/ig, "<span class=\"abbr\" $1>$2</span>");
   },
   showHide: function(elem) {
      if (elem) elem.style.display = elem.style.display == "none" ? "block" : "none";
   },
   show: function(elem) { if (elem) elem.style.display = "block"; },
   hide: function(elem) { if (elem) elem.style.display = "none"; },
   nearest: function(parent, tagname) { 
      var elems = parent ? parent.getElementsByTagName(tagname) : null;
      return elems ? elems[0] : null;
   },
   formatDate: function(fmt, d) {
      var twodig = function(val) { return val < 10 ? ("0"+val) : val; }
      return fmt.replace(/%Y/, d.getFullYear())
                .replace(/%M/, twodig(d.getMonth()+1))
                .replace(/%D/, twodig(d.getDate()))
                .replace(/%h/, twodig(d.getHours()))
                .replace(/%m/, twodig(d.getMinutes()))
                .replace(/%s/, twodig(d.getSeconds()));
   },
   toJson: function(o, tab, indent) {
      var ind = (tab=tab||"")?"\n"+(indent||"") : "";
      if (o != null && typeof(o.constructor) != "undefined")
         switch(o.constructor) { 
            case Boolean:
            case Number:
               return o.toString();
            case String:
               return "\"" + o.replace(/[\\]/g, "\\\\").replace(/["]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r') + "\"";
            case Array:
               var a = [];
               for (var i = 0; i < o.length; i++)
                  a[i] = Core.toJson(o[i], tab, !!tab?(indent||"")+tab:tab);
               return "[" + ind+tab + a.join("," + ind+tab) + ind + "]";
            default:  // object 
               var a = [];
               for (var p in o)
                  if (typeof(o[p]) != "undefined" && typeof(o[p]) != "function")
                     a.push('"'+p+'"' + (!!tab?": ":":") + Core.toJson(o[p], tab, !!tab?(indent||"")+tab:tab));
               return "{" + ind+tab + a.join("," + ind+tab) + ind + "}";
         }
      return "null";
   }
};
*/
