
var dom = {

  elById : function(id) {
    return (typeof id != "string") ? id : (document["getElementById"] ? document.getElementById(id) : false );
  },
  
  elsByTag : function(t, p) {
    p = p ? dom.elById(p) : document;
    return (p && p["getElementsByTagName"]) ? p.getElementsByTagName(t) : [];
  },
  
  elByTag : function(t, p) {
    var els = dom.elsByTag(t, p);
    return els.length ? els[0] : 0;
  },
  
  parentByTag : function(t, el, check_self) {
    el = dom.elById(el);
    if (check_self) {
      if (el['tagName'] && el.tagName.toLowerCase() == t) {
        return el;
      }
    }
    if (el.parentNode) {
      var p = el.parentNode;
      if (!p['tagName']) return 0;
      if (p.tagName.toLowerCase() == t) {
        return p;
      }
      return dom.parentByTag(t, p);
    }
    return 0;
  },

  isInTag: function(t, el) {
    el = dom.elById(el);
    if (el['tagName'] && el.tagName.toLowerCase() == t) return 1;
    return dom.parentByTag(t, el) ? 1 : 0;
  },
  
  parentByClass : function(c, el, check_self) {
    el = dom.elById(el);
    if (check_self && dom.hasClass(el, c)) return el;
    if (el.parentNode) {
      var p = el.parentNode;
      if (dom.hasClass(p, c)) {
        return p;
      }
      return dom.parentByClass(c, p);
    }
    return 0;
  },
  
  elsByClass : function(c, p, t) {
    var els = t ? dom.elsByTag(t, p) : dom.elsByTag("*", p);
    var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
    var r = [];
    for (var i = 0, i_max = els.length; i < i_max; i++) {
      if (els[i].className && els[i].className.match(re)) {
        r[r.length] = els[i];
      }
    }
    return r;
  },
  
  elByClass : function(c, p, t) {
    var els = dom.elsByClass(c, p, t);
    return els.length ? els[0] : 0;
  },
  
  hasClass : function(el, c) {
    var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
    return (el.className && el.className.match(re)) ? 1 : 0;
  },

  addClass : function(el, c) {
    if (!dom.hasClass(el, c)) {
      el.className += el.className ? " " + c : c;
    }
  },

  removeClass : function(el, c) {
    if (dom.hasClass(el, c)) {
      var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
      el.className = el.className.replace(re, '$1$2');
    }
  },
  
  prevNodeByClass: function(c, el) {
    while (el = el.previousSibling) {
      if (dom.hasClass(el, c)) return el;
    }
  },

  nextNodeByClass: function(c, el) {
    while (el = el.nextSibling) {
      if (dom.hasClass(el, c)) return el;
    }
  },

  elsByAttr : function(a_name, a, p) {
    var els = dom.elsByTag("*", p);
    var esc_a = a.replace(/([\.])/g, '\\$1');
    var re = new RegExp("(^|\\s)" + esc_a + "(\\s|$)");
    var r = [];
    var cur_a;
    for (var i = 0, i_max = els.length; i < i_max; i++) {
      cur_a = els[i].getAttribute(a_name);
      if (!cur_a) continue;
      if (a && !cur_a.match(re)) continue;
      r[r.length] = els[i];
    }
    return r;
  },

  elByAttr : function(a_name, a, p) {
    var els = dom.elsByAttr(a_name, a, p);
    return els.length ? els[0] : 0;
  },
  
  elsByPath : function(path, p) {
    p = p ? dom.elById(p) : document;
    var parts = path.split(" ");
    var part = parts.shift();
    var rest = parts.join(" ");
    var m, i;
    var r = [];
    var els = [];
    if ((m = part.match(/^[\.]([^\.]+)(.*)$/))) {/* .foo or .foo.bar */
      els = dom.elsByClass(m[1], p);
      if (m[2]) {
        sub_path = m[2].substr(1);
        pre_els = els;
        els = [];
        for (i = 0; i < pre_els.length; i++) {
          if (dom.hasClass(pre_els[i], sub_path)) els[els.length] = pre_els[i];
        }
      }
    }
    else if ((m = part.match(/^[\#](.*)$/))) {/* #foo */
      els = [dom.elById(m[1])];
    }
    else if ((m = part.match(/^([^\.]+)\.(.*)$/))) {/* foo.bar */
      els = dom.elsByClass(m[2], p, m[1]);
    }
    else {/* foo */
      els = dom.elsByTag(part, p);
    }
    if (rest) {
      for (i = 0, i_max = els.length; i < i_max; i++) {
        r.append(dom.elsByPath(rest, els[i]));
      }
    }
    else {
      r = els;
    }
    return r;
  },
  
  elByPath : function(path, p) {
    var els = dom.elsByPath(path, p);
    return els.length ? els[0] : 0;
  },
  
  attrVal : function(el, a_name) {
  	return(el && el["getAttribute"]) ? el.getAttribute(a_name) : false;
  },
  
  styleVal: function(el, s_name, default_val) {
    el = dom.elById(el);
    if (el['currentStyle']) 
      return el.currentStyle[s_name];
    if (window['getComputedStyle']) 
      return document.defaultView.getComputedStyle(el, null).getPropertyValue(s_name);
    return default_val ? default_val : '';
  },
  
  setEl : function(id, val) {
    var el = dom.elById(id);
    if (el) el.innerHTML = val;
  },
  
  appendEls : function(id, els) {
    var el = dom.elById(id);
    if (el) {
      for (var i = 0; i < els.length; i++) {
        el.appendChild((els[i].nodeType == 3) ? document.createTextNode(els[i].nodeValue) : els[i]);
      }
    }
  },

  toggleEl : function(id) {
    var el = dom.elById(id);
    if ((el.style.display == "none") || !dom.elDim(el).h) {
      el.style.display = 'block';
    }
    else {
      el.style.display = 'none';
    }
    window.focus();
  },
  
  removeEl : function(id) {
    var el = dom.elById(id);
    if (el) el.parentNode.removeChild(el);
  },
  
  getId : function(el) {
    el = dom.elById(el);
    if (!el) return 0;
    if (el.id) return el.id;
    if (!el.dom_id) {
      var pos = 0;
      var p;
      if ((p = el.parentNode)) {
        var cn = p.childNodes;
        while (cn[pos] != el) {
          pos++;
        }
      }
      el.dom_id = p ? dom.getId(p) + '.' + pos : pos;
    }
    return el.dom_id;
  },

  setHover: function() {
    dom.addClass(this, 'hover');
  },

  removeHover: function() {
    dom.removeClass(this, 'hover');
  },

  /* event stuff */

  event_registry : {'count' : 0},
  
  addEvent : function(el, e_type, fnc) {
    el = dom.elById(el);
    if (!el || (typeof el != "object")) return 0;
    /* dom_id */
    var dom_id = dom.getId(el);
    /* fnc key */
    var fnc_key = escape(dom_id + e_type + fnc);
    //console.log(fnc_key);
    /* already registered ? */
    if (dom.event_registry[fnc_key]) {
      if (dom.event_registry[fnc_key]["el"] == el) return 1;
      /* el changed, unregister */
      dom.removeEvent(el, e_type, fnc);
    }
    /* register */
    dom.event_registry[fnc_key] = { "el" : el, "e_type" : e_type, "fnc" : fnc };
    dom.event_registry.count++;
    /* add handler */
    if (el.addEventListener) el.addEventListener(e_type, fnc, false);
    else if (el.attachEvent) el.attachEvent('on' + e_type, fnc);
    else {
      var cur_fnc = el['on' + e_type];
      el['on' + e_type] = (typeof old_fnc == 'function') ? function() { cur_fnc(); fnc();} : fnc;
    }
    return true;
  },
  
  removeEvent : function(el, e_type, fnc) {
    el = dom.elById(el);
    if (!el || (typeof el != "object")) return 0;
    var dom_id = dom.getId(el);
    var fnc_key = escape(dom_id + e_type + fnc);
    if (!dom.event_registry[fnc_key]) return 0;
    var old_el = dom.event_registry[fnc_key]["el"];
    var old_fnc = dom.event_registry[fnc_key]["fnc"];
    if (old_el['removeEventListener']) {
      try {
        old_el.removeEventListener(e_type, old_fnc, false);
      } catch (e) {};
    }
    else if (old_el['detachEvent']) {
      try {
        old_el.detachEvent('on' + e_type, old_fnc); 
      } catch (e) {};
    }
    else try {
      old_el['on' + e_type] = null;
    } catch (e) {};
    dom.event_registry.fnc_key = null;
    dom.event_registry.count--;
  },
  
  cancelEvent : function(e) {
    if (e.preventDefault) {
      e.preventDefault();
      e.stopPropagation();
    }
    else {
      e.cancelBubble = true;
      e.returnValue = false;
    }
  },
  
  fireEvent: function(el, e_type){
    el = dom.elById(el);
    if (document['createEventObject']) {/* ie */
      var e = document.createEventObject();
      return el.fireEvent('on' + e_type, e);
    }
    if (document['createEvent']) {
      var e = document.createEvent("Events");
      e.initEvent(e_type, true, true);/* bubble, allow_cancel */
      return el.dispatchEvent(e);
    }
  },

  getEventPos : function(event) {
    var x, y;
    try {
      x = (event && event.pageX) ? event.pageX : ((event && event.x) ? event.x : 0);
      y = (event && event.pageY) ? event.pageY : ((event && event.y) ? event.y : 0);
      if(navigator.userAgent.indexOf('Safari') != -1) {
        //y += dom.scrollPos().y;
      }
    } catch(e){}
    return {'x' : x,  'y' : y};
  },

  ePos: function(e) {
    return dom.getEventPos(e);
  },

  eventButton: function(e) {
    e = e || window.event;
    if(e && (typeof(e["button"]) != "undefined")) return e.button;
    if(e && (typeof(e["which"]) != "undefined")) return e.which;
  },

  eButton: function(e) {
    return dom.eventButton(e);
  },

  eTarget: function(e) {
    e = e || window.event;
    return e['target'] ? e.target : e.srcElement;
  },

  /* pos */
  
  scrollPos: function() {
    var x, y;
  	var ua = navigator.userAgent.toLowerCase();
  	if (document.body && document.body.scrollTop && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		y = document.body.scrollTop;
  	}
    else if(document.documentElement && document.documentElement.scrollTop && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		y = document.documentElement.scrollTop;
    }
    else {
      y = window.pageYOffset;
    }
    return {'x' : 0,  'y' : parseInt(y)};
  },

  elPos : function(el, abs_pos) {
    el = dom.elById(el);
    if (dom.styleVal(el, 'position').match('fixed|absolute')) {
      abs_pos = true;
    }
    var r = {
      'x': el.offsetLeft - el.scrollLeft,
      'y': el.offsetTop - el.scrollTop,
      'z': el.style['zIndex'] ? parseInt(el.style.zIndex) : 0
    };
    if (el.offsetParent) {
      var sub_r = dom.elPos(el.offsetParent, abs_pos);
      r = { 'x' : r.x + sub_r.x, 'y' : r.y + sub_r.y, 'z': r.z };
    }
    /* safari */
    else if (abs_pos && navigator.userAgent.indexOf('Safari') != -1) {
      r.y += dom.scrollPos().y;
    }
    return r;
  },
  
  setPos: function(el, pos, y) {
    pos = y ? {'x': pos, 'y': y} : pos;
    var x = "" + pos.x;
    y = "" + pos.y;
    try {
      el.style.top = y.match("%") ? y : y + 'px';
      el.style.left = x.match("%") ? x : x + 'px';
    }
    catch(e) {};
  },
  
  elDim: function(el) {
    return {'w': el.offsetWidth, 'h': el.offsetHeight};
  },
  
  setDim: function(el, dim, h) {
    dim = h ? {'w': dim, 'h': h} : dim;
    this.setW(el, dim.w);
    this.setH(el, dim.h);
  },

  setW: function(el, w) {
    el = dom.elById(el);
    w = "" + w;
    el.style.width = w.match(/(\%|auto)/) ? w : w + 'px';
  },

  setH: function(el, h) {
    el = dom.elById(el);
    h = "" + h;
    el.style.height = h.match(/(\%|auto)/) ? h : h + 'px';
  },

  isOver: function(over_el, under_el, fixed_under) {
    var o_pos = dom.elPos(over_el);
    var o_dim = dom.elDim(over_el);
    var u_pos = dom.elPos(under_el);
    var u_dim = dom.elDim(under_el);
    if (fixed_under) {
      u_pos.y += dom.scrollPos().y;
    }
    if (o_pos.x > (u_pos.x + u_dim.w)) return 0;
    if (o_pos.y > (u_pos.y + u_dim.h)) return 0;
    if ((o_pos.x + o_dim.w) < u_pos.x) return 0;
    if ((o_pos.y + o_dim.h) < u_pos.y) return 0;
    return 1;
  },

  winHeight : function() {
    var ua = navigator.userAgent.toLowerCase();
  	if(document.body && document.body.clientHeight && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		return parseInt(document.body.clientHeight);
  	}
    else if(document.documentElement && document.documentElement.clientHeight && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		return parseInt(document.documentElement.clientHeight);
    }
    return parseInt(window.innerHeight);
  },
  
  winWidth : function() {
    var ua = navigator.userAgent.toLowerCase();
  	if(document.body && document.body.clientWidth && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		return parseInt(document.body.clientWidth);
  	}
    else if(document.documentElement && document.documentElement.clientWidth && (ua.indexOf("msie") != -1) && (ua.indexOf("opera")==-1)){
  		return parseInt(document.documentElement.clientWidth);
    }
    return parseInt(window.innerWidth);
  }
  
};

if (!window.trice_libs) {trice_libs = {};}

trice_libs["ajax"] = {
  run : function() {
    ajax.activateLinks();
    ajax.activateForms();
  }
}

var ajax = {

  activateLinks: function() {
    var els = dom.elsByPath('a.ajax');
    for (var i in els) {
      ajax.activateLink(els[i]);
    }
  },

  activateLink: function(el) {
    if (!el['href']) return 0;
    if (!el.href.match(/^([^\$]*)\$[^\?]+(\?.*)?$/)) return 0;
    if (el.ajax_href) return 0;
    el.ajax_href = el.href;
    el.href = el.href.replace(/^([^\$]*)\$[^\?]+(\?.*)?$/, '$1$2');
    dom.addEvent(el, 'click', function(e){dom.cancelEvent(e); ajax.callLink(el);});
    if (dom.hasClass(el, 'auto-load')) {
      ajax.callLink(el);
    }
  },

  /*  */

  activateForms: function() {
    var els = dom.elsByPath('form.ajax');
    for (var i = 0, i_max = els.length; i < i_max; i++) {
      ajax.activateForm(els[i]);
    }
  },

  activateForm : function(el) {
    var href = el.action;
    var id = ajax.getCallID(href, 'form');
    var div = dom.elById('div' + id);
    if (!div) {
  		div = document.createElement("div");
      div.id = 'div' + id;
      div.className = 'form-request';
  		div.innerHTML = '<iframe id="win' + id + '" name="win' + id +'" src="javascript:;"></iframe>';
      try { dom.elById('trice-ajax-area').appendChild(div); } catch(e){}
    }
    el.target = (el.target == 'debug') ? 'debug' : 'win' + id;
    dom.addEvent(el, 'submit', ajax.wait);
  },

  /*  */

  callLink : function(el, connection_id) {
    ajax.wait()
    var href = el["ajax_href"] ? el.ajax_href : el.href;
    var id = connection_id ? ajax.getCallID(connection_id, 'link') : ajax.getCallID(href, 'link');
    /* POST */
    if (dom.hasClass(el, 'post')) {
      var div = dom.elById('div' + id);
      if (!div) {
        div = document.createElement("div");
        div.id = 'div' + id;
        div.innerHTML = ''+
          '<iframe id="win' + id + '" name="win' + id +'" src="javascript:;"></iframe>'+
          '<form id="form' + id + '" target="win' + id + '" method="post" enctype="application/x-www-form-urlencoded"></form>'+
        '';
        dom.elById('trice-ajax-area').appendChild(div);
      }
  		var form = dom.elById('form' + id);
      form.action = "javascript:;";
  		form.action = href;
  		//form.target = "debug";
  		form.submit();
    }
    /* GET */
    else {
      /*
  		var win = dom.elById('win' + id);
  		win.src = "javascript:;";
  		win.src = href;
      */
      if (!ajax['xhrs']) ajax.xhrs = {};
      try { ajax.xhrs[id].abort() } catch(e) {}
      ajax.xhrs[id] = ajax.getXHR();
      ajax.xhrs[id].id = id;
      ajax.xhrs[id].open('GET', href, true);
      ajax.xhrs[id].onreadystatechange = ajax.xhrDone;
      ajax.xhrs[id].send(null);
    }
    if (window.contextmenu) contextmenu.hide();
    if (window.form) window.form.hideSuggestions();
  },

  getXHR: function() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
    return false;
  },

  xhrDone: function() {
    if (this.readyState != 4) return false;
    if (this.status != 200) return false;
    if (this !== ajax.xhrs[this.id]) return false;
    var r = this.responseText;
    r = r.substring(r.indexOf('<!-- trice ajax result start '), r.indexOf('<!-- trice ajax result end '));
    var div = document.createElement("div");
    div.innerHTML = r;
    var cbs = dom.elsByClass('callback', div, 'form');
    for (var i = 0; i < cbs.length; i++) {
      var cb = cbs[i];
      var call = cb.call.value;
      var args = dom.elsByClass('argument', cb, 'textarea');
      var arg_code = '';
      for (var j = 0; j < args.length; j++) {
        arg_code += arg_code ? ', ' : '';
        arg_code += 'args[' + j + '].value';
      }
      try {
        eval(call + '(' + arg_code + ');');
      }
      catch(e) {alert(e)}
    }
    /* apply js to new html */
    trice.loaded();
    if (!top['request_count']) top.request_count = 0;
    top.request_count++;
    top.location.hash = '#' + top.request_count;
    ajax.done();
    return true;
  },

  /*  */

  wait : function() {
  },

  done : function() {
  },

  getCallID : function(val, type) {
    var r = 0;
    for (var i in val) {
      r += (1 * val.charCodeAt(i));
    }
    return type + r;
  },

  updateEl : function(val) {
    if (val) {
      var tmp_el = document.createElement('div');
      tmp_el.innerHTML = val.replace(/^\s+/, '');
      dom.setEl(tmp_el.firstChild.id, tmp_el.firstChild.innerHTML);
      if (window.fx) fx.flash(tmp_el.firstChild.id);
    }
  },

  appendEls : function(val) {
    if (val) {
      var tmp_el = document.createElement('div');
      tmp_el.innerHTML = val.replace(/^\s+/, '');
      dom.appendEls(tmp_el.firstChild.id, tmp_el.firstChild.childNodes);
    }
  },

  /*  */

  redirectTo : function(url, delay) {
    if (!delay) delay = 1;
    setTimeout("location.href = '" + url + "';", delay);
  },

  /*  */

  buildURL: function(method, url) {
    if (!url) url = location.href;
    if (url.match(/^\?/)) url = location.href.replace(/[\?\#].*$/, '') + url;
    return url.replace(/(\?|\#|$)/, '$' + method + '$1');
  },

  get: function(method, url, connection_id) {
    return this.getURL(this.buildURL(method, url), connection_id);
  },

  getURL: function(url, connection_id) {
    var el = document.createElement("a");
    el.ajax_href = url;
    ajax.callLink(el, connection_id);
  },

  post: function(method, url, connection_id) {
    return this.postURL(this.buildURL(method, url), connection_id);
  },

  postURL: function(url, connection_id) {
    var el = document.createElement("a");
    el.ajax_href = url;
    el.className = 'post';
    ajax.callLink(el, connection_id);
  }

}

/* microdata/RDF utils */

var micrordf = {

  getItemURI : function(el) {
    var about_el = this.getAboutEl(el);
    if (!about_el) return 0;
    var r;
    if ((r = about_el.getAttribute('content'))) return r;
    if ((r = about_el.getAttribute('href'))) return r;
    if ((r = about_el.getAttribute('src'))) return r;
    return about_el.innerHTML();
  },

  getPropEl: function(item_el, prop) {
    item_el = dom.elById(item_el);
    var els = dom.elsByAttr('itemprop', prop, item_el);
    for (var i = 0, i_max = els.length; i < i_max; i++) {
      if (item_el == this.getParentItem(els[i])) return els[i];
    }
    return false;
  },

  getPropValue: function(item_el, prop) {
    var el = this.getPropEl(item_el, prop);
    if (!el) return false;
    if ((r = el.getAttribute('content'))) return r;
    if ((r = el.getAttribute('href'))) return r;
    if ((r = el.getAttribute('src'))) return r;
    return el.innerHTML();
  },

  getAboutEl: function(el) {
    el = dom.elById(el);
    var p_el = this.getParentItem(el, 1);
    if (!p_el) return 0;
    var els = dom.elsByAttr('itemprop', 'about', p_el);
    for (var i = 0, i_max = els.length; i < i_max; i++) {
      if (p_el == this.getParentItem(els[i])) return els[i];
    }
  },

  getParentItem: function(el, check_self) {
    el = dom.elById(el);
    if (check_self && el['getAttribute'] && el.getAttribute("item")) return el;
    if (el.parentNode) return this.getParentItem(el.parentNode, 1);
    return 0;
  }
  
};

if (!window.trice_libs) {trice_libs = {};}

/* core tweaks */
Array.prototype.append = function(ar) {
  for (var i = 0, i_max = ar.length; i < i_max; i++) {
    this[this.length] = ar[i];
  }
};

/* trice */
var trice = {

  loading : 1,

  init : function() {
    try {
      if (dom.elById('trice-ajax-area')) return trice.loaded();
      var body = dom.elByTag('body');
      var el = document.createElement('div');
      el.id = 'trice-ajax-area';
      if (body['appendChild']) {
        body.appendChild(el);
        trice.loaded();
      }
      else if (trice.loading) {
        trice.runTO = setTimeout("trice.init()", 100);
      }
    }
    catch (e) {
      if (trice.loading) {
        trice.runTO = setTimeout("trice.init()", 100);
      }
    }
  },
  
  loaded : function() {
    trice.loading = 0;
    try {clearTimeout(window.trice_runTO)} catch(e) {}
    for (var i in trice_libs) {
      if (trice_libs[i]['run']) {
        trice_libs[i].run();
      }
    }
  },

  getURL : function (qs_args, url) {
    url = url ? url : location.href;
    url = url.replace(/\#.*$/, '');
    var qs = (url.indexOf('?') != -1) ? url.substring(url.indexOf('?')+1) : '';
    var base = (url.indexOf('?') != -1) ? url.substring(0, url.indexOf('?')) : url;
    return qs_args ? base + trice.getQS(qs_args, qs) : base;
  },
  
  getQS : function(a, qs) {
  	qs = qs ? qs : (location.search ? location.search.substring(1) : '');
    for (var i in a) {
      var re = "/(^|\\?|\\&)("+i+"=)([^\\&]*)/";
      /* remove old args */
      qs = qs.replace(eval(re), "");
      /* add new */
      if (a[i]) {
        qs += qs.length ? "&" : "";
        qs += i + "=" + a[i];
      }
    }
    return qs ? '?' + qs : '';
  },
  
  p : function(name, qs) {
    var qs = qs ? qs : (location.search ? location.search.substring(1) : '');
    qs = qs.replace(/\?/, '&');
    alert(qs);
    var re, m;
    re = '/\&' + name + '=([^\&]*)/';
    return (m = qs.match(eval(re))) ? m[1] : false;
  }


};

