


var iph={
   mouse:{x:0,y:0},
   preferences:{},
   fluxUri:function(action){
      action = action.replace(/^flx:\/\//,'');
      action = action.replace(/\s+/g, '%20');   
      return 'flx://' + (action.split('?'))[0];        
   },
   getUri: function(x) { 
      if(!x){return false;}
      if(x.state) { 
         x=flx(x).state[0];
      }
      try{ 
         x=x.split('?')[1];
         x=x.match('uri=.+');
         if(x) {
            x=x.toString().split('&')[0].replace('uri=','');
         }
         return x;
      }catch(e){flux.log(e);}
      return false;
   },
   getStartingPoint:function(container, useMouse){      
      useMouse = typeof useMouse == "undefined" ? true : useMouse;
      var d = {};
      if (useMouse && iph && iph.mouse) {
         d = {
            x: iph.mouse.x,
            y: iph.mouse.y
         };

      } else if (!useMouse) { 
         d = $(container).PagePos();
         flux.log(d);
         if (container.css('position') == 'fixed') { 
            d.x = $(container).attr('offsetLeft');
            d.y = $(container).attr('offsetTop');
         } else { 
            d.x = d.left;
            d.y = d.top;   
         }
      } else { 
         d = { x: 0, y: 0 };
      }
      flux.log("BEFORE Set StartingPoint (" + d.x + ", " + d.y + ") " + (useMouse ? ' useMouse ' : ' not usemouse'));

      var dim = { w: 300, h: 300 };
      var w_offset = 30;
      var screen = false;
      if (container && container.get(0)) {
         dim = {
            w: (container.get(0).offsetWidth), 
            h: (container.get(0).offsetHeight)
         };
         if (container.css('position') == 'fixed') { 
            flux.log("FIXED");
            screen = flux.screenFx();
         }
      }
      if (!screen) {
         screen = flux.screen();
      }

      if (screen.width < (d.x + dim.w + w_offset)) { 
         if (d.x > screen.width) { 
            d.x = Math.max(0, d.x-(0.5*dim.w));
         } else { 
            d.x = screen.width - dim.w - w_offset;
         }
      }
      if (screen.height < d.y + dim.h) { 
         //if (d.y > screen.height) { 
         //   d.y = Math.max(0, screen.height-dim.h);
         //} else { 
            d.y = screen.height - dim.h - 15;
         //}
      }
      d.x = Math.max(10, d.x);
      d.y = Math.max(d.y, 40);

      flux.log("Set StartingPoint (" + d.x + ", " + d.y + ")");

      return {
         left: d.x,   
         top: d.y
      };
   },
   setPrefDim:function(panel,uri){
      uri = uri.indexOf('://') === false ? 'flx://' + uri : uri;

      if(typeof iph !== "undefined" && typeof iph.preferences !== "undefined" && typeof iph.preferences[uri] !== "undefined") {
         var pref = iph.preferences[uri];
         if (typeof pref == "object" && typeof pref.preferences === "string") { 
            
            var lst = pref.preferences.split("\n");

            $(lst).each(function(){
               var val = this.toString().split('=');
               if (val.length == 2 && val[0] && val[1]) { 
                  panel.container.css(val[0],val[1]);
               }
            });
         }
      } else {
         flux.log("No DimPrefs for "  + uri);
      }
   },

   daemon: function(x,y) {
      var u,t,c;

      if (x.charAt(0) == '@') { 
         t = x.split(':');
         u=x;
         x=t[1];
         c=x.split("/");
      } else { 
         c=x.split("/");
         u=x;
      }
      if(typeof c[1] == "undefined") {
         c[1]="index";
      }     
    
      c[1] = c[1].split("?")[0];
      
      var f=".c-"+c[0]+".a-"+c[1];
      flux.log("IPHDAEMON FIND " + f + ": " + $(f).length);

      if($(f).length > 0) { 
         if (typeof y !== "undefined") {
            return flx(f).load(u,y).show();
         } else { 
            return flx(f).show();
         }
      } else {
         return iph.load(u,y).show();
      }
   },

   loadHidden: function (action, post) { 
      panel = iph.load (action, post);
      panel.container.hide();
      panel.onLoad = function () { 
         panel.container.show();
      };
      return panel;
   },

   load:function(action, post){
      try{post=post||false;}catch(e){post=false;}

      //flux.log(arguments.callee.caller);
      
      action = action.replace(/^flx:\/\//,'');
      action = action.replace(/\s+/g, '%20');
      if (action.charAt(0) == '@') { 
         // iph.load('@popup:url').
         action = action.split(':');
         var panel = flux.create(action.shift().substr(1));
         action = action.join(':');
      } else { 
         var panel = flux.create('univas_chrome');
      }
      if(post !== false) {
         if(typeof post.nodeType !== "undefined" && $(post).is("form")) { 
            post=gfd(post);
         }
         panel.load(action, post);
      } else {
         panel.load(action);
      }

      var listen_url = (action.split('?'))[0];

      panel.onLoad = function() { 
         this.container.find('input,textarea,select').eq(0).focus();
         if (this.find('div[mvcoord]').length>0) {
            var current_url = this.find('div[mvcoord]').attr('mvcoord');
            flux.log("MVCOORD FOUND AND " + listen_url + ", current_url = " + current_url);
            if (current_url !== listen_url) {
               iph.setPrefDim(this, 'flx://' + current_url);
            }
         } else { 
            flux.log("NO MVCOORD FOUND");
         }

         this.onLoad = function(){};
         
      };

      var uri = 'flx://' + (action.split('?'))[0];

      // set prefered window dimensions.

      iph.setPrefDim(panel, uri);
      if (panel.getPref('dimFit') == 1) {          
         panel.dimFit();
      }
   
      // set starting point (close to mouse).
      if (panel.atCursor) { 
         panel.atCursor();
      } else { 
         flux.log("PANEL GSP: " + panel.getUrl());
         panel.css(iph.getStartingPoint(panel.container));
      }
      // clear my menu bar!
      try { 
         panel.activate();
      } catch (e) { }

      return panel;
   },
   
   store_window_positions:function(flux_object){
      var obj = flux_object.container;
      var data = {
         /* top: $(obj).css('top'),
         left: $(obj).css('left'), */
         width: $(obj).css('width'),
         height: $(obj).css('height')
      };
      iph.presets[flux_object.state[0]] = data;
      //flux.log(data);
   },
   
   open:function(url) { 
      // look for an existing file first.
      flux.log("Open: "  + url);
      try { 
      url = encodeURI(decodeURI(url));

      var found = false;

      $(".flux-panel").each(function(){
         var tgt = flx(this);
         if(!!tgt && !!tgt.state && tgt.getUri()==url){
            tgt.activate();
            found = tgt;
         }
      });
      if(found) { 
         alert("Found a panel");
         return found; 
      } 
      var p = uo_identify(url);
      
      if(uos[p.type]){
         var r = uos[p.type];
         var r_open = r.actions.open || r.actions.Open;
         if(r.dblclick){
            return iph.load(r.dblclick.replace(/\$uri/g,url));
         } else if(r_open.defaultAction){
            var t = r_open.defaultAction;
            if(t.defaultAction){
               t=t.defaultAction;   
            }
            return iph.load(t.replace(/\$uri/g, url));
         } else { 
            alert("Dont know how to launch this " + p.type);
         }
      } else { 
         alert("Unknown object type " + p.type);
      }
      
      }catch(e) { alert("Error while opening: " + e); }
   },
   
   openWith:function(uri, event) {    
      event=event?event:{pageX:iph.mouse.x,pageY:iph.mouse.y};
      var o = uo_identify(uri);
      // read from applst
      if(applst[o.abs_type]) { 
         var html = '<div><b>Available programs for</b><br>'+
            '<span uo="' + o.uri + '">' + o.uri + '</span>'+
         '<br /><hr />';
         html += flux.ctx.createList(uo_parselize(o,applst[o.abs_type]));
         html += "<br>Or enter app: <input />";
         html += '<br /></div>';
         var panel = flux.create('univas_chrome').css({
            width:230, height: 250
         }).setContent(html).dim(event);
         $(panel.area).find('li').click(function(){
            panel.exit();
         });   
         $(panel.area).find('input').keydown(function(e){
            if(e.which == 13) { 
               iph.load($(this).val()+'?uri=' + o.uri);
            }
         });
         $(panel.area).find('ul').css({
            'margin-left' : '25px',
            'list-style-type':'bullit',
            'cursor' : 'pointer'
         });
      }
      event.cancelBubble=true;
   },

   getInitTrigger : function () { 
      // Flux InitScript Support
      var tmp;
      tmp='code[type=init]';
      return tmp ? tmp : 'script[type=init]';
   }, 

   
   serializeWorkspace:function(){
      location.hash = "#" + interface.serializer.output();
   },
      
   serializer:{
      output:function() {
         var lines = [];
         var readCss = function(x,y){
            var x=parseInt($(x.container).css(y));
            return x=="NaN" ? 0 : x;
         }
         $(".flux-panel").each(function(){
            var o = flx(this);
            if($(o.container).is(":visible") && o.state && o.state[0]) {
               lines.push(
                  o.state[0] +'-'+
                  readCss(o,'left')+'x'+readCss(o,'top')+'-'+
                  readCss(o,'width')+'x'+readCss(o,'height')
               );
            }
         });
         return lines.join('||');      
      },
      input:function(hash){
         $(hash.split("||")).each(function(){
            var bits = this.toString().split("-");
            var dims = bits.slice(-2);
            var url = bits.slice(0,-2).join("-");
            dims[0] = dims[0].split("x");
            dims[1] = dims[1].split("x");
            var p =flux.create('univas_chrome').load(url).css(c={
               'left' : dims[0][0]+'px',
               'top' : dims[0][1]+'px',
               'width' : dims[1][0]+'px',
               'height' : dims[1][1]+'px'
            });
   
         });     
      }
   },
   

   destruct : function() { }
};
try { interface = iph; } catch(e) { }

$(function(){
   $('body').bind('mousemove mousedown', function(e){
      interface.mouse={
         x:e.pageX,
         y:e.pageY
      };
   }).bind('selectionChanged',function(){
      var setpos = $('.c-default.a-selection').length==0;
      var dm = iph.daemon('default/selection');
      if(setpos){ 
         dm.css({
            left:null, 
            right:20, 
            top:40
         });
      }
      dm.css('z-index',2000);
   });

});

// Base
function _fluxalize(target, statement) {
   var _target = target;
   var stmt = statement;
   var panel=null;

   if(!stmt.match) { 
      stmt = stmt.toString();
   }
   if(stmt.match(/[,=]+/)) { 
      var params = {};

      $(stmt.split(",")).each(function(){
         var _this = this.split("=");
         params[_this[0]] = _this[1];
      });
      var panel_type = params.panel||'none';
      settings = {};
      if (!params.url) { 
         params.url = $(_target).attr('flux_url');
      }
      if (params.url) { 
         settings.state = [$(_target).attr('flux_url')];
      } 
      panel = flux.createPanel(panel_type,_target, settings);

      if (!params.url) { 
         params.url = $(_target).attr('flux_url');
      }
      if (!params.load) { 
         params.load = $(_target).attr('flux_load');
      } 
      if(params.url) {
         panel.state=[params.url];
      } else if(params.load) {
         panel.load(params.load);
      } else if ($(_target).attr('load') > '') { 
         panel.load($(_target).attr('load'));
      }
      if(params.modal) { panel.modal(); }
      if(params.dim) { panel.dim(params.dim.split("+")); }
   } else { 
      var baseUrl = statement;
      panel = flux.createPanel('none', _target);
      panel.state = [baseUrl];
   }

}

function fluxalize(target) {
   $(target).find("div[flux]:not(.fluxed)").each(
      function() { if($(this).attr("flux")) { 
         _fluxalize(this,$(this).attr("flux")); 
      } else { flux.log("Invalid FluxAttribute"); } }
   );
}

function flx(target) {
   var tgt = null;
   
   try {
      if(target && target.className && target.className.match(/fluxed/)) {
         tgt = target;
      } else if (target) {
         if(!$(target).is('.fluxed')) {
            tgt = $(target).closest('.fluxed').get(0);   
         } else {
            tgt = $(target).get(0);
         }
      }
   } catch(e){
      alert("FLX ERROR: " + e);
   }
   if(!!tgt && tgt.oFlux) {
      return tgt.oFlux;
   } else { 
      return new fluxStub();
   }
}

flux={};

// Flux Component Container
flux.comp={};

// Panel Instance
flux.panel={
   presets:{}
};

flux.state={
   serialize:function(){
      var windows=[];
      $('.flux-ubuntu').each(function(){
         var f = flx(this);
         if(f.state&&f.state[0]){
            windows.push({
               url: f.state[0],
               css: {
                  left: f.container.css('left'),
                  top: f.container.css('top'),   
                  width: f.container.css('width'),
                  height: f.container.css('height')
               }
            });
         }       
      });
      return windows;
   }
};

// Base Utils
function killEvent(x) {
   if (x && x.preventDefault) { 
      x.preventDefault();
      x.cancelBubble=true;
   }
   return false;
}
function parseQuery(query) {
   var vars = query.split("&");
   var res  = {};
   for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      res[pair[0]] = unescape(pair[1]);
   }
   return res;
} 
function parseQueryLong(query) {
   var vars = query.split("&");
   var res  = [];

   for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      res.push({name: pair[0], value: unescape(pair[1])});
   }
   return res;
} 
$.fn.toggleSelected = function (ctx, classname) { 

   ctx = ctx || $(this).parent();
   classname = classname || 'selected';

   $('.' + classname, ctx).removeClass(classname);
   $(this).addClass(classname);

   return $(this);

};

$.fn.serializeArrayForced = function() { 
   var params = [];
   var fields = [
      "input[checked]",
      "input[type=text]",
      "input[type=hidden]",
      "input[type=password]", 
      "input[type=submit]:checked", 
      "option[selected]", 
      "textarea"
   ];
   $(this).find(fields.join(",")).each(function() {    
      var key = this.name || this.id || this.parentNode.name || this.parentNode.id;
      if(!key) { key = this.parentNode.parentNode.name || this.parentNode.parentNode.id; }
      params.push({
         name: key,
         value: $(this).val()
      });
   });
   return params;
};
function getFormDataCompat(targ) { 
   targ = $(targ);
   var params = {}; 
   var fields = [
      "input[checked]",
      "input[type=text]",
      "input[type=hidden]",
      "input[type=password]", 
      "input[type=submit]:checked", 
      "option[selected]", 
      "textarea"
   ];
   $(targ).find(fields.join(",")).each(function() {
      var key = this.name || this.id || this.parentNode.name || this.parentNode.id;
      if(!key) { key = this.parentNode.parentNode.name || this.parentNode.parentNode.id; }
      if(key && key.match && key.match(/\[\]$/)) { 
         //flux.log("KEY = " + key);
         if(params[key]) { 
            //flux.log("PUSH");
             params[key].push(this.value);
          } else { 
             params[key]=[this.value];
          }
      } else { 
         if(this.FCK) { 
            var oe = FCKeditorAPI.GetInstance(this.FCK.InstanceName);
            params[key] = oe.GetHTML();
         } else { 
            params[ key ] = this.value; 
         }
      }
   }); 
   return params;
}
function getFormData(targ) { 
   targ = $(targ);
   var params = {}; 
   var fields = [
      "input[checked]",
      "input[type=text]",
      "input[type=hidden]",
      "input[type=password]", 
      "input[type=submit]:checked", 
      "option[selected]", 
      "textarea"
   ];
   $(targ).find(fields.join(",")).each(function() {
      var key = this.name || this.id || this.parentNode.name || this.parentNode.id;
      if(!key) { key = this.parentNode.parentNode.name || this.parentNode.parentNode.id; }
      if ($(this).is('textarea')) { 
         try { 
            if (typeof $.fn.tinymce !== "undefined" && typeof $(this).tinymce() !== "undefined") {
               $(this).tinymce().save();
            }
         } catch (e) { } 
      }
      if(key && key.match && key.match(/\[\]$/)) { 
         //flux.log("KEY = " + key);
         
         if(params[key]) { 
            //flux.log("PUSH");
             params[key].push(this.value);
          } else { 
             params[key]=[this.value];
          }
      } else { 
         if(this.FCK) { 
            var oe = FCKeditorAPI.GetInstance(this.FCK.InstanceName);
            params[key] = oe.GetHTML();
         } else { 
            params[ key ] = this.value; 
         }
      }
   }); 
   return params;
}


// Utility Function
flux.url = function(url){
   if(url.match(/^https*:\/\//)) {
      //flux.log("FULL URL, EXIT");
      return url;  
   }
   var base = flux.root.match(/https*:\/\/[^\/]+\//);
   if(typeof url === "string") { 
      var tmp = url.split('?');
      tmp[0] = tmp[0].replace(flux.root,"").replace(base,"");
      url = tmp.join('?');
   } else { 
      url = "";
   }
   var r = (flux.root + url)
      .replace(/:\/\//g,':scheme:')
      .replace(/\/\//g,"/")
      .replace(/:scheme:/g,'://')
   ;
   /* 
   if(0>=r.indexOf("?")) { 
      r+="?"; 
   }
   r+="&__ts="+(new Date().getTime());
   */
   return r;
};
flux.relUrl = function(url) {
   // strip host.
   // tryout:
   return url.replace(flux.root,"");
};

flux.isMobile = function () { 
   return (window.isMobile) || false;
};

flux.kbIsEnter = function (e) { 
   if (typeof e == "object") { 
      e = e.which || e.keyCode || e.charCode;
   }
   return e == 13;
}
flux.kbIsAlnum = function (e) { 
   if (typeof e == "object") { 
      e = e.which || e.keyCode || e.charCode;
   }
   return !(e < 38 || e > 90);
}
flux.onsuggest = function (target, e, fn) { 
   //flux.log('keydown is triggered');
   if (flux.kbIsEnter(e)) { 
      //flux.log('onsuggest: enter triggered');
      $(target).each(typeof fn == "string" ? new Function(fn) : fn);
   } else if(flux.kbIsAlnum(e)) { 
      //flux.log('onsuggest: alnum delay..');
      $(target).delay(333, function () { 
         flux.log('onsuggest: alnum triggered');
         $(this.target).each(typeof fn == "string" ? new Function(fn) : fn);
      });
   } else { 
      $(target).delay(-1);
   }
}
flux.screen = function() {
   if (document.body && document.body.scrollTop) { 
      var b = document.body;
   } else { 
      var b = document.documentElement;
   }
   // return available width and available width
   // keep in mind scrollTop, we dont to be able to 
   // popup things within the visible region!
   return {
      width: window.innerWidth||b.clientWidth,
      height: (b.scrollTop) + (window.innerHeight||b.clientHeight)
   };
};
flux.screenFx = function () { 
   var b=document.documentElement||document.body;
   return {
      width: window.innerWidth||b.clientWidth,
      height: window.innerHeight||b.clientHeight
   };
};
flux.tooltip = function (tgt, content, height) { 
   $(tgt).css('cursor','help');
   if (tgt.tooltip) { 
      tgt.tooltip.show();
   } else {
      var mode;
      if (typeof content == "string" && !$(content).is('body *')) { 
         mode = 'inline';
         tgt.tooltip = flux.create('simple',$('<span />').appendTo(tgt)).setContent(content);
      } else { 
         mode = 'standalone';
         tgt.tooltip = flux.create('simple').setContent($(content).show()).atCursor();
      }
      tgt.tooltip.css({
         marginLeft: 30,
         width: 150,
         '-moz-box-shadow': '0 0 15px rgba(0,0,0,0.4)',
         '-webkit-box-shadow': '0 0 15px rgba(0,0,0,0.4)',
         height: (height || 200),
         overflow: 'hidden'         
      });
   }
   
   $(tgt).hover(function(){}, function () { 
      tgt.tooltip.hide();
   }); 
   return tgt.tooltip;
};

function dump() {return;}
clear=function(){
   $('.ielog').empty();
};
flux.log = function(message, force) { 
   if (typeof force !== 'undefined') { 

      switch (typeof message) { 
      case 'object':
         var str = [];
         for (var x in message) { 
            str.push (x + ': ' + message[x]);
         }
         alert (str.join("\n"));
      break;
      default:
         alert (str);   
      break;
      }
   }
   if(window.console && window.console.log) { 
      window.console.log(message);
   } 
   if($('.ielog').length > 0) { 
      var t = $('.ielog');
      var mt = typeof message;
      mt=$.isArray(message)?'array':mt;
      if(message === null || mt == 'undefined') { 
         return;
      }
      if(mt == 'array' || mt == 'object') { 
         $('<pre />').hide().prependTo(t).text(dump(message));         
         $('<pre style="font-weight:bold;">[+] ' + mt + '</pre>').prependTo(t).click(function(){
            flux.create('ubuntu',$(this).next().clone().show())
            .css({width:300, height: 300}).css(iph.getStartingPoint());
         });
      } else { 
         message += "";
         m = $('<pre />').prependTo(t).text(message);
         if((/ajax/i).test(message)) { m.css('color','#aaa'); } 
         if((/error/i).test(message)) { m.css('color','red'); }
      }
   }
};
$(function(){
   window.onerror = function(e,x,l){
      flux.log('Javascript Error: ' + e + '(' + x + ', ' + l + ')');
   };
   /* 
   $('body').ajaxSend(function(e,e2,xhr){
      try{
      var message = "Ajax: " + flux.relUrl(xhr.url);
      xhr.elem = $('<pre style="font-weight:bold;" />').prependTo('.ielog').text(message+"");
      }catch(ex){}
   });
   $('body').ajaxComplete(function(e,e2,xhr){
      try{
      var stat = e.status + ': ' + e.statusText;
      xhr.elem.addClass('done').css({fontWeight:'normal'})
         .prepend('<div style="float:right">[' + stat + ']</div>')
      ;
      flux.delay(5###000, function(){
         $(xhr.elem).remove();
      });
      }catch(ex){}
   });   
   */
   $('body').ajaxError(function() {
      flux.log('Ajax Error: some server error occured.');
   });
});
flux.clone = function(x){
   return $(x).clone().hide().appendTo("body");
};

// Flux Grid On or Off
flux.grid = true;

pInt = function(x){
   x = parseInt(x,10);
   return isNaN(x) ? 0 : x;
};

calculateMargin = function(target, reference) {
   target = $(target).get(0);
   reference = $(reference).get(0);

   return {
      marginTop : reference.offsetTop - target.offsetTop,
      marginLeft : reference.offsetLeft - target.offsetLeft
   };
};

function fluxalize_overlay(ctx) { 
   $(ctx).find("*[flux_overlay]").each(function(){
      var target = this;
      var spacer = 'url(img/spacer.gif)';
      var spacer2 = 'url(img/spacer.gif)';
      spacer = spacer2 = 'url(res/img/spacer.gif)';
      var wrapper = $(target).wrap('<span />').parent().css({
         position: 'relative',
         backgroundImage: spacer,
         width: 'auto',
         height: 'auto',
         padding: $(target).css('padding'),
         margin: $(target).css('margin')
      });
      var overlay = $('<div />').prependTo(wrapper).css({
         position: 'absolute',
         backgroundImage: spacer2,
         width: '100%',
         height: '100%'
      });
      if($(target).is('select')) { 
         $(overlay).css('padding','3px 0').css('top','-2px');
      }
      $(overlay).click(function(){
         $(target).click();
      });
   });
}

function flux_thead_fix_apply() { 
// history captured in Base.Utils
// bugfix: meerdere theads... 
var settings = $.extend({}, {
   fixScrollbar: true
}, $(this).data('fixOptions'));

var coord = {
   top: $(this).parent()[0].offsetTop,
   left: $(this).parent()[0].offsetLeft,
   width: $(this).parent()[0].offsetWidth
};
var copy = $(this).parent().clone();
$(copy).insertAfter($(this).parent()).find('tbody').remove();

var css = {
   position: 'absolute',
   'overflow-y' : 'auto',
   'overflow-x' : 'hidden',
   top: coord.top,
   left: coord.left,
   right: 0,
   // dit zorgt ervoor dat de scrollbalk niet meegenomen wordt in de width..
   // width: pInt(coord.width) - pInt(coord.left),
   bottom: 0
};

var css2 = {
   left: coord.left, 
   position: 'absolute',   
   top: coord.top,
   overflow: 'hidden'
};

if ($(this).parent().attr('offsetWidth') < $(this).parent().parent().attr('offsetWidth')) { 
   css.right = 0;
   css2.right = 0;
} else { 
   css2.width = $(this).parent().attr('offsetWidth');
}
var scroller = $(this).parent().wrap('<div />').parent().css(css);

var cells = $(this).closest('table').find('thead th,thead td');
var cells_copy = $(copy).find('th,td');


var src, dest;
for (var i = 0; i < cells.length; i++){
   src = cells.get(i);
   dest = cells_copy.eq(i);
   var paddingWidth = pInt($(src).css('padding-left'))+pInt($(src).css('padding-right'));
   var paddingHeight = pInt($(src).css('padding-top'))+pInt($(src).css('padding-bottom'));
   //flux.log("Cell " + i + " ow: " + src.offsetWidth + " pad: " + paddingWidth);
   $(src).attr('title', 'WIDTH ' + src.offsetWidth);
   dest.css('width', src.offsetWidth - paddingWidth).attr('title', 'WIDTH ' +src.offsetWidth - paddingWidth);
   dest.css('height', src.offsetHeight - paddingHeight);
}

var copywrap = $(copy).wrap('<div />').parent().css(css2);
//flux.log(scroller.attr('offsetHeight') + ' - ' + scroller.attr('scrollHeight'));
if (settings.fixScrollbar && scroller.attr('offsetHeight') < scroller.attr('scrollHeight')) { 
   if (css2.width) { 
       copywrap.css({width: (css2.width - 12)});
   }
   copywrap.css({marginRight: 14});
}
$(window).resize(function () { 
   copywrap.css({width: '', marginRight: 12});
   for (var i = 0; i < cells.length; i++){
      src = cells.get(i);
      dest = cells_copy.eq(i);
      var paddingWidth = pInt($(src).css('padding-left'))+pInt($(src).css('padding-right'));
      var paddingHeight = pInt($(src).css('padding-top'))+pInt($(src).css('padding-bottom'));
      //flux.log("Cell " + i + " ow: " + src.offsetWidth + " pad: " + paddingWidth);
      $(src).attr('title', 'WIDTH ' + src.offsetWidth);
      dest.css('width', src.offsetWidth - paddingWidth).attr('title', 'WIDTH ' +src.offsetWidth - paddingWidth);
      dest.css('height', src.offsetHeight - paddingHeight);
   }   
});
}

(function($){
$.unserialize = function(serializedString){
var str = decodeURI(serializedString);
var pairs = str.split('&');
var obj = {}, p, idx, val;
for (var i=0, n=pairs.length; i < n; i++) {
p = pairs[i].split('=');
idx = p[0];

if (idx.indexOf("[]") == (idx.length - 2)) {
// Eh um vetor
var ind = idx.substring(0, idx.length-2)
if (obj[ind] === undefined) {
obj[ind] = [];
}
obj[ind].push(p[1]);
}
else {
obj[idx] = p[1];
}
}
return obj;
};
})(jQuery);

// Base Aux
var tab = '   ';
function insertAtCursor(o, txt) { 
   var oS = o.scrollTop;
   if (o.setSelectionRange) {
      var sS = o.selectionStart;
      var sE = o.selectionEnd;
      o.value = o.value.substring(0, sS) + txt + o.value.substr(sE);
      o.setSelectionRange(sS + txt.length, sS + txt.length);
      o.focus();
   }
   else if (o.createTextRange) {
      document.selection.createRange().text = txt;
      e.returnValue = false;
   }
   o.scrollTop = oS;
   e.mId = true;
   if (e.preventDefault) {  e.preventDefault(); }
   return false;
}
function insertTab(o, e){
   var kC = e.which;

   if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.mId) {         
      var oS = o.scrollTop;
      if (o.setSelectionRange) {
         var sS = o.selectionStart;
         var sE = o.selectionEnd;
         o.value = o.value.substring(0, sS) + tab + o.value.substr(sE);
         o.setSelectionRange(sS + tab.length, sS + tab.length);
         o.focus();
      }
      else if (o.createTextRange) {
         document.selection.createRange().text = tab;
         e.returnValue = false;
      }
      o.scrollTop = oS;
      e.mId = true;
      if (e.preventDefault) {  e.preventDefault(); }
      return false;
   }  return true; 
}


aux = {
   easy:function(e){
      if(aux.qsave(e)) {
         return insertTab(e.target,e);
      } else { 
         return false;
      }
   },
   qsave:function(e){
      if(e.which == 83 && e.ctrlKey) {
         if(!e.target.form) { 
            flux.log("aux.qsave unable to quick-save, textarea outside of FORM");
            return;
         } else {
            flux.log('aux.qsave quick-saving');
         }

         if(e.target.form.onsubmit) {
            var res = e.target.form.onsubmit();
            if(!(res === false)) {
            flux.log("jquery submit");
               $(e.target.form).submit();
            } else { 
               flux.log(res);
               flux.log("DOING NOTHING");
            }
         } else {
            flux.log("jquery submit");
            $(e.target.form).submit();
         }
         e.preventDefault();
         return false;
      } 
      return true;
   }
};

// Object Stub

fluxStub = function(){
   var meth = [
      'onLoad','onInactivate','title',
      'isAlive','onTerminate','modal',
      'formHandler','dim','css','setContent','load',
      'activate','onActivate','exit',
      'loadIntoArea'
   ];

   var props=['container','area'];
   var instance = this;
   $(meth).each(function(){
      instance[this.toString()]=function(){return instance;};
   });
   $(props).each(function(){
      instance[this.toString()]=null;
   });
   this.area=$('<div />');
   this.getUrl = function() {
      return 'Stub';  
   };
   this.isAlive = function(){ return false; }
};

// Object Flux
function fluxInstance (settings){
   settings = settings || {};
   $(settings.container).addClass("fluxed");
   $(settings.container)[0].oFlux = this;
   var ref = this;

   this._age = 0;
   this.state = [''];

   this.onLoad = function() {};
  
   this.isAlive = function() {
      x = $(this.container).is("body *");
      return x;
   };
   this.onTerminate = function(){
      $(this.area).trigger('terminate.flux');
      return true;
   };
   this.getState = function () { 
      return this.state;
   };
   this.setState = function (a) { 
      this.state = a;
   };
   this.setUrl = function (url) {
      if (!this.state) { 
         this.state = [];
      }
      if (this.area.children().eq(0).attr('url')) { 
         this.area.children().eq(0).attr('url','');
      }
      this.state[0] = url;
      return this;
   };
   this.hide = function () { 
      this.css('display','none');
      return this;
   };
   this.show = function () { 
      this.css('display','block');
      return this;
   };
   this.getUrl = function(){
      var state = this.getState();
      if (this.area.children().eq(0).attr('url')) {    
         return this.area.children().eq(0).attr('url');
      }
      return state&&state[0]?state[0]:'';
   };
   this.find = function (x) { 
      return this.container.find(x);
   };

   this.modal = function(mode){ 
      mode = typeof mode == "undefined" ? true : mode;
      if(mode) { 
         if(!$('#flux-modal').length){
            $("body").append('<div id="flux-modal" style="display:none;" />');
         }
         if (!$(this.container).css('z-index')) { 
            $(this.container).css('z-index', 200);
         }
         $(this.container).addClass("modal");
         $('#flux-modal').show();
      } else { 
         $('#flux-modal').hide();
         $(this.container).removeClass('modal');
      }
      return this;
   };

   this.formHandler = function(t) { 
      $(ref.container).removeClass("flux-status-updating");

      if(t) {   
         var exit = false;
         var match = t.match(/<flux-trigger.+?\/>/); 
         if (match) { 
            match = match.toString().replace("<flux-trigger ","").replace("/>","");
            match = $.trim(match.split("=")[1]);
            flux.log("Signal: " + match);
            ref.container.trigger(match);
         }
         if(t.match(/<flux-hide \/>/)) {    
            ref.container.hide();
         }
         if(t.match(/<flux-close \/>/)) { 
            exit = true;
            ref.exit();
         } 
         if(t.match(/<flux-refresh-page \/>/)) {
            location.href = location.href;
         }
         if(t.match(/<flux-unflux \/>/)) {
            exit = true;
            $(ref.container).removeClass("fluxed");
            $(ref.container).html($(this.area));
         }
         if(t.match(/<flux-update-parent \/>/)) { 
            flx($(ref.container).parent()).load();
            exit = true;
         }
         if(exit) { return false; } 
      }

      $(ref.container).find(".hoverable, .hvr").removeClass("hoverable").hover(
         function() { $(this).addClass("hover"); },
         function() { $(this).removeClass("hover"); }
      );

      var title = $(ref.container).find(".flx-canvas .box-title, .flx-canvas h1.boxt");
      //flux.log("Flx.FormHandler find title: " + title.length);
      $(title).each(function(){
         flx(this).title(this);
         //$(this).remove();
      });
      fluxalize(ref.container);



      $(ref.area).find('form:not(.handled)').addClass("handled").submit(function(){

         var target = $(this).attr('target');
         var _target = this;
         flx(_target).area.trigger('BeforeSubmit')

         if(target == 'none') { _target = '<div />'; }
         else if(target > '') { _target = target; } 
         var form_data = getFormData(this);
         var _action = $(this).attr('action');
         if (_action.match(' ')) { 
            // partial-document section (`url #section`).
            _action = _action.split(' ');
            _action = flux.url(_action[0]) + ' ' + _action[1];
         } else { 
            _action = flux.url(_action);
         }
         flux.log("FLOAD: " + _action);
         flux.log("REMOVECLASS FROM ");
         flux.log(this);
         $(this).removeClass('changed');
         $(this).find('.changed').removeClass('changed');

         flx(_target).loadIntoArea(_action, form_data, flx(_target).formHandler);
         /* 
         flx(_target).area.load(
            _action, 
            form_data, 
            flx(_target).formHandler
         );
         */
         return false;
      });


      $(ref.area).trigger('updateContent');
      if(ref.onLoad) { 
         ref.onLoad();
      }
      if (ref && ref.getPref && ref.getPref('dimFit') == '1') { 
         ref.dimFit();
      }

   };

   this.css = function(x,y) { 
      this.container.css(x,y);
      if(x == 'width' || x == 'height' || x['width'] || x['height']){
         $(this.container).trigger('resized');
      }
      return this;
   };

   this.setContent = function(html) {
      flux.log("Flx.SetContent");
      this.area.html(html);
      this._age = 0;
      this.formHandler();
      return this;
   };
   this.parent = function (search) { 
      if (typeof search !== "undefined") { 
         return flx(this.container.parent().find(search));
      } else { 
         return flx(this.container.parent());
      }
   }; 
   this.post = function (data, init) { 
      this.load(null, data, init);
      this.state[1] = {};
      return this;
   };

   this.load = function(url, data, init){
      if(jQuery.isFunction(data)) { 
         init = data;
         data = null;
      }
      if (url && url.match) { 
         /* Getest door:
            iph.load('post:eenadres?test=1');
            iph.load('post:eenadres?test[]=0&test[]=1&test[]=2');
         */
         if (url.match(/^post:/)) { 
            url = url.split('?');
            data = parseQueryLong(url[1]);
            url = url[0].replace('post:','');
         }
      }
      var state = this.getState();

      if (typeof url == "undefined") {   
         data=state[1];
         init=state[2];
      }
      if(!(url)) {
         url = this.getUrl();  
         
      }
      if(typeof url !== "string") {
         init = data;
         data = url;
         url = state[0];
      }
      flux.log("Set State: " + url);
      flux.log(data);
      if (data && typeof data.state !== "undefined" && data.state == false) { 
         this.setState([url,{},init]);
      } else { 
         this.setState([url,data,init]);
      }

      var ref = this;
      
      $(this.container).addClass("flux-status-updating");
      //flux.log(this.area);
      this._age = 0;
      if ((url+'').match(' ')) { 
         flux.log("jQuery Load Section");
         url = url.split(' ');   
         url = flux.url(url[0]) + ' ' + url[1];
      } else { 
         url = flux.url(url);
      }
      
      this.loadIntoArea(url,data,function(t){  
         ref.formHandler(t);       
         try { if (ref.state && ref.state[2] && $.isFunction(ref.state[2])) { ref.state[2](); } } catch(e){}
      });   
      return this;
   };
   this.loadIntoArea = function (url, data, cb) { 
      $(this.area).load(url, data, cb);
   }
   this._autoRefreshRegister = function(){
      UpdateDaemon.register(this);        
      this._autoRefreshRegister = function(){};
   };

   this.autoRefreshCycles = 100;
   this.autoRefresh = function(cycles) {
      try { 
         this.autoRefreshCycles = cycles || 5;
         this._autoRefreshRegister();
      } catch(e) {
         if(typeof UpdateDaemon == "undefined") { 
            flux.log("Error: UpdateDaemon not found, so no auto-refresh for " + this.getUrl());
         }
      }
      return this;
   };

   this.enrich = function(){};
   settings = settings || {};
   for(var setting in settings) {
      if(setting){this[setting] = settings[setting];}
   }

   this.formHandler();

   this.activate = function(){
      var tgt = $(this.container);
      if (this.isEmbedded()) {
         // no: only floating windows may be activated.
         // yes: only standalone windows may be activated.
         // and dont forget to return this.
         return this;
      }
      if (!tgt.is(".flux-status-active")) { 
         $(".flux-status-active").each(function(){
            flx(this).onInactivate();
            $(this).removeClass("flux-status-active");
         });
         $(this.area).trigger('activate.flux');
         this.onActivate();
         tgt.addClass("flux-status-active");
      }
      return this;
   };
   this.isEmbedded = function () { 
      return $(this.container).is('.fluxed.ui-draggable .fluxed');
   };
   this.exit = function() { 
      if ($(this.container).is(".modal")) {
         this.modal(false);
      } 
      // if this is embedded in a floating flux, close its parent.
      if (this.isEmbedded()) {
         if (false !== this.onTerminate()) { 
            return flx(this.container.parent()).exit();
         }
      }     
      var status = this.onTerminate();
      if(status) { 
         $(this.container).remove();
      } 
      return this;
   };

   this.viewState = function(){
      //$(this.area).css('overflow','hidden');
      var state={
         url: this.state ? flux.relUrl(this.state[0]) : '',
         pos: (
            $(this.container).attr("offsetLeft")+"x"+
            $(this.container).attr("offsetTop")
         ),
         dim: (
            $(this.area).attr("offsetWidth") + "x" +
            $(this.area).attr("offsetHeight")
         ),
         scroll: (
            'width:' + $(this.area)[0].scrollWidth + 'px;' +
            'height:' + $(this.area)[0].scrollHeight + 'px;'
         )
      };
      //$(this.area).css('overflow','auto');
      alert(
         "Url: " + state.url + "\n" + 
         "Pos: " + state.pos + "\n" +
         "Dim: " + state.dim + "\n" + 
         "Bookmark: " + (state.url+"|"+state.pos+"|"+state.dim) + "\n" +
         "Scroll: " + (state.scroll)
      );
      return this;
   };

   if(this.container){
      $(this.container).bind('contextmenu', function(e){
         flux.log("Ext.Ctx contextmenu-event on FluxContainer");
         if(!e.ctrlKey) { 
            if($(this.container).contextmenu_handler) { 
               $(this.container).attr('contextmenu_handler')();
               return false;
            }
            flux.log(e.target.contextmenu);
            if (flux.ctx) { flux.ctx.render(e, e.target.contextmenu); }
            return false;            
         }
      }).mouseup(function(e){
         if(e.which == 1 && e.ctrlKey) {
            if($(this.container).attr('contextmenu_handler')) { 
               $(this.container).attr('contextmenu_handler')();
               return false;
            }
            flux.log("MouseDowning vanuit FluxContainer");   
            flux.log($(e.target).attr('contextmenu'));
            flux.ctx.render(e, $(e.target).attr("contextmenu"));
            //return false; 
         } 
         flx(this).activate();
      });
   }

   this.ref = false;

   this.setReference = function (ref) { 
      this.ref = ref;
      return this;
   };

   this.getReference = function (how) { 
      if (typeof how == "undefined") {
         return this.ref;
      } else if (how == "flx") { 
         if (typeof this.ref.getReference !== "undefined") { 
            return this.ref;
         } else {
            return flx(this.ref);
         }
      } else if (how == true) { 
         return $(this.ref);
      } else { 
         return this.ref;
      }
   };
   this.isFixed = function () { 
      return this.container.css('position') == 'fixed';
   };

   this.setPref = function (x, y) { 
      if (typeof iph == "undefined") { return false; }

      var flxaddr = 'flx://' + this.getUrl().split('?')[0];
      var prefs = this.getPref();
      if (y === "toggle") {   
         y = prefs[x] !== "0" ? 0 : 1;
      }
      prefs[x] = y;
      flux.log(flxaddr + ' set ' + x + ' to ' + y);
      iph.preferences[flxaddr].preferences=$.param(prefs).replace(/&/g,"\n");

      return this;
   };

   this.savePref = function () { 
      var flxaddr = 'flx://' + this.getUrl().split('?')[0];

      $.post('default/storepref',{
         uri:flxaddr,
         pref:iph.preferences[flxaddr].preferences
      });
      return this;
   };

   this.getPref = function (x) { 
      if (typeof iph == "undefined" || typeof iph.preferences == "undefined") { return false; }

      var flxaddr = 'flx://' + this.getUrl().split('?')[0];
      if (typeof iph.preferences[flxaddr] == "undefined") {
         iph.preferences[flxaddr] = {preferences:''};
      }
      var prefs = iph.preferences[flxaddr].preferences;
      prefs = $.unserialize(prefs.replace(/\n/g,"&"));
   
      if (typeof x == "undefined") { 
         return prefs;  
      } else { 
         return prefs[x];
      }
   };

   this.atCursor = function (pos) { 
      var dim = iph.getStartingPoint(this.container);
      if (this.isFixed()) { 
         dim = {
            top: iph.mouse.y,
            left: dim.left
         };
         // dit moet natuurlijk flux.screenFx zijn (voor fixed situaties).
         var screen = flux.screenFx();
         dim.top -= pInt($(window).scrollTop());
         if ((dim.top + pInt(this.container.css('height'))) > screen.height) { 
            dim.top = screen.height - pInt(this.container.css('height')) - 30;
         }
         dim.top = Math.max(0, dim.top);
         flux.log("Flux.atCursor: Height: " + dim.top + ' x ' + screen.height);
      } 
      if (pos) {
         if (pos.indexOf('center') !== -1) { 
            dim.top -= pInt(this.container.css('height')) / 2;
            dim.left -= pInt(this.container.css('width')) / 2;
         } 
      }
      return this.css(dim);
   };
   this.title = function (x) { 
      flux.log("Flx.Title() is called");
      if(typeof x == "undefined") {
         return $(this.container).find(".flx-title");
      } else { 
         $(this.container).addClass("flx-with-title").find(".flx-title").html(x);
      }
   };


   this.egolink = function ($x,$y,$z){
      var is_scalar = function (mixed_var) {
         return (/boolean|number|string/).test(typeof mixed_var);
      };
      var strpos = function (x,y) {var t = (x+'').indexOf(y); return t === -1 ? false : t; };
      var strlen = function ($x) { return $x.length; };
      var substr = function ($x,$y,$z) { return $x.substr($y,$z); };
      var urlencode = function (str) {
         str = (str + '').toString();
         return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
         replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
      }
      var _egolink = function ($REQUEST_STRING, $k,$v, $quit){
         if($k===null && $v===null) { 
            return $REQUEST_STRING;
         } else if(is_scalar($k)) {
            var d = {};
            d[$k]=$v;
            return arguments.callee($REQUEST_STRING, d,null,$quit);
         } else {
            var $str = $REQUEST_STRING;
            if(strpos($str, '?')===false) { $str += '?'; }
            var $ok = $k;
            var $o1,$o2;
            for($k in $ok){if ($ok.hasOwnProperty($k)) { $v=$ok[$k];
               if (strpos($v, '://')===false) { 
                  $v = urlencode($v);
               }
               if(false !== ($o1 = strpos($str, $k + '='))) {
                  $o1+=strlen($k)+1;
                  $o2 = ($o2 = strpos($str, '&',$o1))===false?strlen($str) : $o2;
                  // insert substring
                  $str = substr($str, 0, $o1) + $v + ($quit ? '' : substr($str,$o2));
               } else if(false !== ($o1 = strpos($str, $k + ':'))) {
                  $o1+=strlen($k)+1;
                  $o2 = ($o2 = strpos($str, '/'))===false?strlen($str) : $o2;
                  // insert substring
                  $str = substr($str, 0, $o1) + $v + ($quit ? '' : substr($str,$o2));
               } else { 
                  $str += '&' + $k + '=' + $v;
               }
            } 
         }}
         return $str.replace('?&', '?');
      };
      var $RC = this.getUrl();
      this.load(_egolink($RC, $x, $y, $z));
   };


};

fluxInstance.prototype.onActivate=function(){};
fluxInstance.prototype.onInactivate=function(){};

// Panel

flux.createPanel=function(x,y){
   return flux.panel.create(x,y);
};
flux.create = function(x,y){
   return flux.panel.create(x,y);
};
flux.definePanel=function(name, constructor) { 
   flux.panel.presets[name] = constructor;
};

flux.panel.create = function(type, target, settings) {
   var settings = settings || {};

   if(!flux.panel.presets[type]) {
      alert("Preset " + type + " does not exist.");
      return false;
   }
   if(!target) { 
      target = $('<div style="width:450px;height:250px;" />').appendTo('body');
   }
   if(!$(target).is("body *")) { 
      $(target).appendTo("body");
   }
   var preset = new flux.panel.presets[type]();
   if(target) { 
      var html = $(target).html();
      var _target = $(target).get(0);

      if(preset.getHtml) {
         $(target).html(preset.getHtml(target));   
      } else if(preset.html) {
         $(target).html(preset.html);
      }
      if(preset.containerCss) { 
         $(target).css(preset.containerCss);
      }      

      _target.oFlux = new fluxInstance($.extend(true, settings, {
         panelPreset:preset.type || type,
         container:$(target),
         area:($(target).is(".flx-canvas") ? $(target) : $(target).find(".flx-canvas"))
      }));

      _target.flux = _target.oFlux;

      if(preset.html && html > '') { 
         _target.oFlux.setContent(html);
      }
      if(preset.bind) {  
         preset.bind(target, _target.oFlux);
      }

      _target.oFlux.activate();
      _target.oFlux.enrich();
      return _target.oFlux;
   } else { 
      return $('');
   }

/*      width:expression(this.parentNode.offsetWidth - 10);
   height:expression(this.parentNode.parentNode.offsetHeight - 10); */
};

// Panels (Chrome, Simple, None)

flux.panel.presets.chrome = function() {
   this.type = "chrome";
   this.containerCss = {position:"absolute"};
   this.html = 
   '<div class="flux-panel flux-chrome">'+
      '<div class="flx-top">'+
         '<div class="flx-left" />'+
         '<div class="flx-center fluid-width flx-title" />'+
         '<div class="flx-right" />'+
      '</div>' +
      '<div class="flx-middle fluid-height">'+
         '<div class="flx-left" />'+
         '<div class="flx-center fluid-height fluid-width flx-canvas" />'+
         '<div class="flx-right" />'+
      '</div>' +
      '<div class="flx-bottom">'+
         '<div class="flx-left" />'+
         '<div class="flx-center fluid-width" />'+
         '<div class="flx-right" />'+
      '</div>' +
   '</div>'
   ;
   this.bind = function(object){
      var ref = this;
      if($.fn.draggable) {
         var handle = '.flx-top';
         $(object).draggable({
            handle:handle,
            delay: 150,
            start: function () {
               var css_overlay = {
                  height:'100%', width:'100%',
                  left:0, top:0,
                  position:'fixed',
                  backgroundImage: 'url(img/spacer.gif)',
                  zIndex:3000
               };
               css_overlay.backgroundImage = "url(res/img/spacer.gif)";

               var overlay = $('<div id="dragOverlay">').appendTo('body').css(css_overlay);

               $(object).css('z-index', 3500);

            }, 
            stop: function () { 
               $(object).css('z-index','');
               $('#dragOverlay').remove();
               //test
            }
         });
         
      }
      if($.fn.resizable) {
         $(object).resizable({
            containment:'document',
            ghost:true,
            //grid:[10,10],
            stop:function(e,u){
               //flx(object).liquid();
            }
         });      
      } else { 
         flux.log('PanelChrome: $.fn.resizable missing');
      }
   };
};

flux.panel.presets.simple = function(){
   this.type = "simple";
   this.containerCss = {position:"absolute"};
   this.html = 
   '<div class="flux-panel flux-simple flx-canvas">'+
   '<div class="flx-canvas"></div>'+
   '</div>'
   ;
};

flux.panel.presets.none = function() {
   this.type = 'none';
   this.html = false;
   this.getHtml = function(target) {
      $(target).addClass("flx-canvas");
   };
   this.bind = function (x,flux) { 
      flux.onTerminate = function () { return false; };
   };
};

fluxInstance.prototype.liquid = function(){
   var pi = function(x) { return pInt(x); };
   var c = this.container;   
   if(!$.browser.msie) { return this; }
   var log=[];

   $(c).find(".fluid-height").each(function(){ 
      var offset = 
         pi($(this).css('top')) +
         pi($(this).css('bottom')) + 
         pi($(this).css('padding-top')) + 
         pi($(this).css('padding-bottom'))
      ;

      var height = pi($(this).parent().attr("offsetHeight"));
      log.push("Liquid: Height " + height + " Offset " + offset);
      if((height - offset) !== "NaN") { 
         $(this).css("height", (height - offset) + "px");
      }
   });
   
   $(c).find(".fluid-width").each(function(){ 
      var d1,d2;
      var offset = 
         pi($(this).css("left")) + 
         pi($(this).css("right")) +
         pi($(this).css('padding-left')) + 
         pi($(this).css('padding-right'))
      ;
      var width = pi($(this).parent().attr("offsetWidth"));
      log.push('Liquid: Width: ' + width + ' offset ' + offset);
      $(this).css("width", (width - offset) + "px");
   });
   if(log.length>0){ 
      flux.log('{' + log.join("\n") + '}');
      $(c).unbind('resized.liquid');   
      $(c).bind('resized.liquid',function(){
         flx(this).liquid();
      });
   }
   return this;
};

fluxInstance.prototype.dim = function(type){
   flux.log("Called dim: " + type);
   var ref = this;
   
   var screen = this.isFixed() ? flux.screenFx() : flux.screen();

   if(typeof type == "number") { 
      type = [type,type];
   }
   if(typeof type == "object") { 
      if(type.pageX && type.pageY) {
         var x,y, 
            wc = $(this.container).attr('offsetWidth'),
            ws = screen.width
         ;
         x = type.pageX; y=type.pageY;
         if((x + wc) > ws) {
            x = ws - wc - 20;
         }
         $(this.container).css({
            'left' : x+ 'px',
            'top' : y + 'px'
         });  
      } else {
         $(this.container).css({
            'width': type[0]+'px',
            'height': type[1] + 'px'
         });
      }
      return this;
   }
   var dim = {
      width:$(ref.container)[0].offsetWidth,
      height:$(ref.container)[0].offsetHeight
   };
   if(typeof type == "object") {

      $(type).each(function(){
         ref.dim(this.toString());   
      });
      return this;
   }
   switch(type){
   case 'random':
      var off_x = Math.round((Math.random() * 100) - 50);
      var off_y = Math.round((Math.random() * 100) - 50);
      var css = {};
      if(off_x < 0) { 
         css.left=""; css.right=(50 + off_x)+"%";
      } else { 
         css.left=off_x+"%";css.right="";
      }
      if(off_y < 0) { 
         css.top=""; css.bottom=(50 + off_y)+"%";
      } else { 
         css.top=off_y+"%";css.bottom="";
      }
      css.margin="";
      $(ref.container).css(css);
   break;
   case 'expand':
      var delta = {
         width:$(ref.area)[0].scrollWidth-$(ref.area)[0].offsetWidth + 4,
         height:$(ref.area)[0].scrollHeight-$(ref.area)[0].offsetHeight + 4
      };

      $(ref.container).css({
         width:(dim.width + delta.width)+"px",
         height:(dim.height + delta.height)+"px"
      }); 
   break;
   case 'center':
      var extra = 0;
      if (!this.isFixed()) { 
         extra = window.scrollY;
      }
      $(ref.container).css(y={
         left: Math.max(0, Math.round((screen.width - dim.width)/2)),
         top: extra + Math.max(0, Math.round((screen.height - dim.height)/2))
      });
      flux.log(screen);
      flux.log(y);
   break;
   case 'left':
      $(ref.container).css({
         left:0,
         right:'',
         margin:''
      });
   break;

   case 'right':
      $(ref.container).css({
         left:'',
         right:0,
         margin:''
      });
   break;
   case 'grid':
      /* 
      var gridalize=function(x){ 
         return Math.round(x / 10)*10;
      };
      var object = ref.container;
      $(object).css({
         left: gridalize($(object).attr("offsetLeft")),
         top:  gridalize($(object).attr("offsetTop")),
         width: gridalize($(object).attr("offsetWidth")),
         height: gridalize($(object).attr("offsetHeight")) - 3,
         marginLeft: "",
         marginTop: ""
      });
      */
   break;
   }

   return this;
};

fluxInstance.prototype.dimRel = function(target, position){
   if(typeof position == "undefined") { 
      position = 'left,top';       
   }
   var xvals=[],yvals=[];

   if(position.match('left')) {
      xvals = ['offsetLeft'];   
   } else if(position.match('right')) {
      xvals = ['offsetLeft', 'offsetWidth'];
   }
   flux.log(position);
   if(position.match('top')){
      yvals = ['offsetTop'];
   } else if(position.match('bottom')) { 
      yvals = ['offsetTop', 'offsetHeight'];
   }
   var xpos=0,ypos=0;

   var pi = function(x) {return pInt(x);};

   var descendCalc = function(ref, attr){
      var val = 0;
      while(ref && $(ref).is("body *")) {
         val += ( pi($(ref)[0][attr]) );
         ref = $(ref)[0].offsetParent;
      }
      return val;
   };

   $(xvals).each(function(){
      var y = this.toString();
      if(y == 'offsetLeft') { 
         xpos += (descendCalc($(target),y));
      } else { 
         xpos += pi($(target).attr(y));
      }
   });
   $(yvals).each(function(){
      var y = this.toString();
      if(y == 'offsetTop') { 
         ypos += (descendCalc($(target),y));
      } else { 
         ypos += pi($(target).attr(y));
      }
   });   

   if(position.match('right') && position.match('align')) {
      xpos -= $(this.container).attr('offsetWidth');      
   }      

   $(this.container).css({
      'position' : 'absolute',
      'left' : xpos + 'px',
      'top' : ypos + 'px'
   });   
   return this;
};

fluxInstance.prototype.closeOnClick = function(){
   $(this.container).click(function() { 
      flx(this).exit();      
   });
   return this;
};  
fluxInstance.prototype.expand = function(){
   this.dim('expand');
   return this;
};
fluxInstance.prototype.switchLayout = function(layout) {
   var content = $(this.area).html();
   flux.log(this.container);
   var myFlux = flux.panel.create(layout, this.container).setContent(content); 
   return this;
};


fluxInstance.prototype.unlock=function(){};
fluxInstance.prototype.lock = function(text) { 
   var item = $('<div>').appendTo(this.container)
      .css({
         'position':'absolute',
         'z-index':500,
         'width':'100%',height:'100%'
      });
   if(!text) {
      item.css({ backgroundColor:'black',opacity:0.1 });
   } else { 
      $(item).append('<center><span style="background-color:white;padding:10px;border:1px solid black;">' + text + '</span></center>');
   }
   this.unlock = function() { $(item).remove(); };
   return this;
};

fluxInstance.prototype.snapshot = function(){
   var html = this.area[0].innerHTML; //.html();
   var strflux = 'panel=' + this.panelPreset;
   flux.log(
      '<div flux="' + strflux + '">' + html + '</div>'
   );
};
fluxInstance.prototype.flash=function(message, timeout) {
   timeout = typeof timeout == 'undefined' ?1500:timeout;

   if(typeof message == "string") { 
      message = $('<div>' + message + '</div>');
   }
   var reference = this;
     
   try{
   if(message.find('.flx-popup').length) { 
      $(message).find('.flx-popup').each(function(){
         var width=$(this).css('width');
         var height=$(this).css('height');
         $(this).css('width',null);
         $(this).css('height',null);

         var panel = flux.create('univas_chrome')
            .css({width:width, height:height})
            .setReference(reference)
            .setContent($(this).removeClass('flx-popup'))
            .atCursor()
         ;
      });
   }
   }catch(e){}

   if(this.area.find('.flx-flash:visible').length) { 
      message = this.area.find('.flx-flash').html(message);
      $(message)[0].className="flx-flash";
   }
   flux.log("Flash: " + $(message).html());
   
   var msg = $(message).insertBefore(this.area).addClass('flx-flash');
   if($(message).text().match(/error:/i)) { 
      $(message).addClass('error');
      timeout=false;
   } else if($(message).text().match(/success:/i)) { 
      var newmsg = $(message).html().replace('success:','');
      $(message).html(newmsg).addClass('success');            
   }

   var close = $('<a>[x]</a>')
      .css('float','right')
      .prependTo(msg)
   ;
   $(msg).find('input[type=submit]').click(function(){
      this.checked=true;
      $(this.form).submit();
      return true;
   });
   if(!$(msg).is('.persist')) { 
      $(msg).click(function() { var t = this; flux.delay(1, function() { $(t).remove(); }); });   
   } else { 
      $(msg).unbind('click');
      $(msg).find('form').submit(function(){
         $(msg).remove();
         return true;
      });
      $(close).click(function() { var t = this; flux.delay(1, function() { $(t).parent().remove(); }); });   
   }
   $(msg).css({position:'absolute',display:'none',left:0,right:50});
   $(msg).fadeIn();

   if(timeout !== false && !$(msg).is('.persist')) { 
      flux.delay(timeout, function(){
         $(msg).fadeOut('slow', function(){
            $(msg).remove();
         });
         
      });   
   }
};

fluxInstance.prototype.center = function(){
   this.area.wrapInner('<div class="fluid-width fluid-height" />').children().eq(0).css({
      'text-align':'center',
      'vertical-align':'middle',
      'display' : 'table-cell',
      'height': this.area.css('height'),
      'width': this.area.css('width')
   });

   return this;
};
fluxInstance.prototype.dimFit = function(){
   // height
   var diff, newValue;
   var screen;

   screen=flux.screenFx();

   var positioned=false;

   $(this.area).find('>div').each(function () {
      var p = $(this).css('position');
      
      if (p == 'absolute') { 
         positioned = true;
      }
   });

   if (positioned) { 
      flux.log("DIMFITTING CANCELLED, FOUND POSITIONED ITEM");
      this.css(iph.getStartingPoint(this.container, false));
      return;
   }

   // horizontal dimfitting
   diff = pInt(this.area.attr('scrollWidth')) - pInt(this.area.attr('offsetWidth'));
   
   flux.log("DIMFIT DIFF " + diff + " (USING AREA SCROLLWIDTH)");
   if (diff > 0) { 
      newValue = pInt(this.container.attr('offsetWidth')) + diff;
      this.css('width', Math.min(screen.width - 60, newValue));
   }
   
   // reset the height to remove redundant space...
   // this.area.css('overflow','hidden');
   this.css('height', 50);

   // vertical dimfit
   diff = pInt(this.area.attr('scrollHeight')) - pInt(this.area.attr('offsetHeight')) + 8;

   /* 
   if (diff < 0) { 
      flux.log("DIFF < 0 - " + diff);
   } else { 
      flux.log("DIFF > 0 - " + diff);
   }
   */

   // hij mag niet buiten beeld geraken..... 
   newValue = pInt(this.container.attr('offsetHeight')) + diff;

   this.css('height', Math.min(screen.height - 60, newValue));
   flux.log(this.container);
   flux.log("DIMFITTED SET HEIGHT TO " + newValue);
 
   this.area.css('overflow',pInt(this.area.attr('scrollHeight')) - pInt(this.area.attr('offsetHeight')) > 0 ? 'auto' : 'auto');
   
   this.css(iph.getStartingPoint(this.container, false));

   return this;
};
flux.ctx = { 
   _options:{
      'close' : 'this.flux.exit();',
      'refresh' : 'this.flux.load();',
      'snapshot' : 'this.flux.snapshot();',
      'view state' : 'this.flux.viewState();'
   },
   _presets:{
     'default' : ['refresh','close'],
     'dev' : ['view state','snapshot']
   },
   register:function(name, callback) {
      flux.ctx._options[name] = callback;
   },
   registerPreset:function(name,callback) {
      flux.ctx._presets[name] = callback;
   },
   createList:function(selection, ref) {
      var namedOptions = flux.ctx._options;
      var namedPresets = flux.ctx._presets;
      var _htmlString = [];   
      var _caption = '', _value = "",extra = '';
      for (var x in selection) { 
         if (x == 'defaultAction') {
            continue;
         }
         _item = selection[x];
         if(_item == "refresh" && (ref) && !(ref.getUrl() > '')) {
            continue;
         }
         if(typeof _item == "object") { 
            extra = '';
            if(_item.defaultAction){
               extra = 'onclick="'+_item.defaultAction+'"';
            }
            var _tmpRes = flux.ctx.createList(_item, ref);
            if (_tmpRes == '<ul></ul>') { 
               _tmpRes = '';
            } else { 
               _tmpRes =  '<span style="position:relative;">'+_tmpRes+'</span>';
            }
            _htmlString.push('<li ' + extra + '>'+
               x + _tmpRes + 
               '</li>'
            );
         } else {
            if(x.match(/^[0-9]+$/)) {
               _value = namedOptions[_item];
            } else { 
               _item = x;
               _value = selection[x];
            }
            _htmlString.push('<li onclick="' + _value + '">' + _item + '</li>');
         }
      }
      _htmlString = '<ul>' + _htmlString.join('') + '</ul>';   
      //flux.log(_htmlString);

      return _htmlString;
   },
   createDomList: function(selection, ref) { 
      var namedOptions = flux.ctx._options;
      var namedPresets = flux.ctx._presets;
      var _htmlString = document.createElement('ul');
      var _caption = '', _value = "",extra = '';
      for (var x in selection) { 
         if (x == 'defaultAction') {
            continue;
         }
         _item = selection[x];
         if (jQuery.isFunction(_item)) { 
            _item = _item();
         }
         if(_item == "refresh" && (ref) && !(ref.getUrl() > '')) {
            continue;
         }
         if(x.match(/^[0-9]+$/)) {
            if (typeof namedOptions[_item] == "object") { 
               _item = namedOptions[_item];
               x = selection[x];
            }
         } 
         if (typeof _item == "object" && _item && _item.htmlNode) { 
            $(_htmlString).append(_item.htmlNode);
         } else if(typeof _item == "object" && _item) { 
            if(_item.defaultAction){
               extra = 'onclick="'+_item.defaultAction+'"';
            }
            var _tmpRes = flux.ctx.createDomList(_item, ref);
            if ($(_tmpRes).find('>li').length>0) { 
               $('<li ' + extra + '><span style="position:relative;" />' + x + '</li>').appendTo(_htmlString).addClass('hasChildren').find('>span').append(_tmpRes);
            } else { 
               $(_htmlString).append('<li ' + extra + '>'+ x + '</li>');
            }
         } else {
            if(x.match(/^[0-9]+$/)) {
               _value = namedOptions[_item];
            } else { 
               _item = x;
               _value = selection[x];
            }
            $(_htmlString).append('<li onclick="' + _value + '">' + _item + '</li>');
         }
      }


      //_htmlString = '<ul>' + _htmlString.join('') + '</ul>';   
      //flux.log(_htmlString);
      return _htmlString;
   },
   render:function(event, options) { 
      var css = {
         "left" : event.pageX + "px",
         "top" : event.pageY + "px",
         "opacity" : 0.0,
         "display" : "block",
         'visible' : 'visible' //,
         //"z-index" : 2000
      };
      var css_reset = {
         "opacity" : 1.0,
         "display" : 'none'
      };

      var namedOptions = flux.ctx._options;
      var namedPresets = flux.ctx._presets;
      var ref = flx(event.target);

      if(typeof options == "undefined") { 
         var tgt = false;
         ref.area.find('script[type=context],code[type=context]').each(function () {
            if (flx(this).area === ref.area) { 
               tgt = $(this);
            }
         });
         if(tgt && tgt.length > 0) {
            var html = $(tgt).html();
            html=html.replace("<!--","").replace("-->","");
            options = eval(html);
         } else { 
            options = ['default'];
         }
      } else if(typeof options == "string") { 
         options = options.split(',');
      }

      //flux.log(options + " :: " + options.length);
      if(options && options.length === 0) { options=['default']; }
      selection = options;
      var _preset = null, _offset = 0;
      var built = [];
      for(var x in selection) {
         _preset = selection[x];
         if(typeof namedPresets[_preset] !== 'undefined') {
            for(var y in namedPresets[_preset]) {
               built.push({key:y,action:namedPresets[_preset][y]});
            }
         } else { 
            built.push({key:x,action:selection[x]});
         }
         //flux.log(built);
      }  
      selection={};
      var _action = false;
      for(x in built) {
         if(built[x].key.match(/^[0-9]+$/)) {
            _action = namedOptions[built[x].action];
            built[x].key = built[x].action;
            //flux.log(_action);
            //flux.log(namedOptions);
         } else { 
            _action = built[x].action;
         }
         if(jQuery.isFunction(_action)) {
            _action = _action(event.target);
            flux.log(x + ' hallo ' + _action);
            if (built[x].key == 'condition') {
               if (_action) { 
                  _action = false;
               } else { 
                  flux.log("Ctx mainCondition not met");
                  return false;
               }
            }
            //flux.log("DynaNode");
         }
         if(_action !== false) {   
            //flux.log("DYNANODE");
            //flux.log(_action);
            selection[built[x].key]=_action;
         }
      }
      //selection=built;
      /* 
      if(selection.join) { 
         //flux.log("Ctx: " + selection.join(",") + " (" + selection.length + ")");
      } else {
         //flux.log("Ctx: Custom selection");
      }
      */
      var createList = flux.ctx.createDomList;
      var _htmlString = createList(selection, ref);
      if(!$('#flux-contextmenu').length) {
         $('<div id="flux-contextmenu" />').appendTo('body');
      }

      var ctxmenu = $('#flux-contextmenu').css(css).html(_htmlString);

      var screen = flux.screen();
      var d = {
         x: pInt(ctxmenu.css('left')),
         y: pInt(ctxmenu.css('top')),
         w: ctxmenu[0].offsetWidth,
         h: ctxmenu[0].offsetHeight
      };
      var x_outside = false, y_outside = false;
      var offset = 12;
      if (screen.width < d.x + d.w + offset) {
         x_outside = true;
         ctxmenu.css('left', screen.width - d.w - offset);
      }
      if (screen.height < d.y + d.h + offset) {
         y_outside = true;
         ctxmenu.css('top', screen.height - d.h - offset);
      }
      
      ctxmenu
         .css(css_reset)
         .fadeIn('fast')
         .find("li")
         .each(function () {
            this.flux = ref;
            this.eventTarget = event.target;
         })
         .click(function (e) {
            $('#flux-contextmenu').hide();
            e.stopPropagation();
            e.preventDefault();
            return false;
         })
      ;
      ctxmenu
         .find('li')
         .mouseenter(function () {
            var menu = $(this).find('>span>ul').css('visibility','visible').fadeIn('fast');
            if (!menu || !menu[0]) { return; } 

            if ($.browser.msie) { 
               menu.css('margin-left', $(this)[0].offsetWidth - 10);
               return; 
            } 


            var screen = flux.screen();
            var d = {
               x: pInt(ctxmenu.css('left')),
               y: pInt(ctxmenu.css('top')),
               w: menu[0].offsetWidth,
               h: menu[0].offsetHeight
            };

            var pos = d.x+d.w;
            var x = $(this).parent();
            
            // make sure the popup doesnt exit the visible
            // region (x-coord)
            var x_outside = false;

            while (x.length == 1 && !x.is('#flux-contextmenu')) {
               if(x.is('ul')) {
                  pos += pInt($(x).css('margin-left')) + d.w;
               }
               x = $(x).parent();
            } 
            x_outside = (screen.width < pos + offset);
            if (x_outside) { 
               menu.css('margin-left', (-1* d.w - offset + 2)+'px');
            } else { 
               menu.css('margin-left', ($(this).attr('offsetWidth') - offset) + 'px');
            }

            // y_outside is more simple, if the main-context-menu
            // was adjusted, all submenu's will be set to bottom: 0
            // relative to span[relative].
            var y_offset = 6;
            if (y_outside) {
               menu.css({ top: null, bottom: 0 - y_offset });
            }
            $(this).addClass('hover');
         })
         .hover(function () {}, function () { 
            $(this).find('>span>ul').fadeOut('fast');
            $(this).removeClass('hover');
         })
      ;
      
   },

   clickableItem: function (title, onclick) { 
      return function (x) { return {htmlNode: $('<li />').click (function () {
         onclick.apply(x.target);
      })}; };   
   },

   positionNode: function (tgt) { 
      
   }
};
flux._timers = [];
flux.timer = function(timeout, action){  
   var id = flux._timers.length;
   var constructor = function(){
      this.timeout = timeout || 1000;
      this.executions = 0;
      this._timeout = null;
      this.id = id;
      this.callback = action || function(){ };

      this.setTimeout = function(timeout){
         this.clear();
         timeout = typeof timeout === "undefined" ? this.timeout : timeout;
         var script = 'var inst = flux._timers[' + this.id + '];' +       
                      'inst.executions++;' + 
                      'inst.callback();' + 
                      'inst.setTimeout();'
         ;
         script = 'if (flux._timers[' + this.id + ']){' + script + '}';

         this._timeout = setTimeout(script, timeout);
      };

      this.clear = function(){
         clearTimeout(this._timeout);
      };

      this.destroy = function() { 
         this.clear();
         delete flux._timers[this.id];
      };

      if (timeout) { 
         this.setTimeout();
      }
   };
   var obj = new constructor();
   flux._timers[flux._timers.length] = obj;
   return obj;
};
flux.delay = function(time, callback) { 
   //flux.log("A delay-timer (@" + time + ") is inited");
   var timer = flux.timer(false,callback);
   timer.setTimeout = function() {
      this.clear();

      var script = 'var inst = flux._timers[' + this.id + '];' +          
                   'inst.executions++;' + 
                   'inst.callback();'
      ;
      script = 'if (flux._timers[' + this.id + ']){' + script + '}';


      this._timeout = setTimeout(script, this.timeout);      
   };
   timer.timeout = time;
   timer.setTimeout();
   return timer;
};


$.fn.timer = function (timeout, callback, once) { 
   var _this = $(this).get(0) || false;
   if (!_this) { 
      return false;
   }

   once = typeof once === "undefined" ? false : once;

   if (typeof _this.timer !== "object" || !_this.timer.target) { 
      _this.timer = flux.timer(timeout, callback);
      _this.timer.clear();
      //flux.log("$.timer: Created new timer #" + _this.timer.id);
      _this.timer.target = _this;

      _this.timer.setTimeout = function(){
         this.clear();
         var script = 'var inst = flux._timers[' + this.id + '];' +  
                      'if (!inst.target || !$(inst.target).is(\'body,body *\')) {' +
                         'delete flux._timers[' + this.id + '];' + 
                         'delete inst;' +
                         //'flux.log(\'Timer: clear '+this.id+'\');' +
                      '}' +  
                      'inst.executions++;' + 
                      'inst.callback();'
         ;
         if (once) { 
            if (once !== 'persist') { 
               //script += 'inst.destroy();';
               //script += 'flux.log(\'Timer: once\');';
            }
         } else { 
            script += 'inst.setTimeout();';
         }
         script = 'if (flux._timers[' + this.id + ']){' + script + '}';
         this._timeout = setTimeout(script, this.timeout);
      };

      _this.timer.destroy = function() { 
         this.clear();
         if (this.target) { 
            this.target.timer = false;   
            this.target = false;
         }
         delete flux._timers[this.id];
      };
      _this.timer.isActive = function () { 
         return !(!this.target || !$(this.target).is('body,body *'));
      }
      _this.timer.setTimeout();
      return _this.timer;
   } else { 
      //flux.log("$.timer: Reuse timer #" + _this.timer.id + ' ' + _this.timer.timeout);
      _this.timer.target = _this;
      _this.timer.callback = $.isFunction(callback) ? callback : function () {};
      _this.timer.timeout = timeout;
      _this.timer.setTimeout();
      return _this.timer;
   }
};
$.fn.delay = function (x, y, persist) { 
   persist = typeof persist === 'undefined' ? true : persist;
   return $(this).timer(x,y, persist);
};
$.fn.delayex = function (x, y) { 
   var timer = $(this).timer(x,y,'persist');
   if (!timer) { 
      return false; 
   } 
   timer.clear();
   timer.setTimeout = function(){
      this.clear();
      this.timeout = ActivityMonitor.intellival(x);

      var script = 'var inst = flux._timers[' + this.id + '];' +  
                   'if (!inst.target || !$(inst.target).is(\'body,body *\')) {' +
                      'delete flux._timers[' + this.id + '];' + 
                      'delete inst;' +
                      //'flux.log(\'Timer: clear '+this.id+'\');' +
                   '}' +  
                   'inst.executions++;' + 
                   'inst.callback();'
      ;
      script = 'if (flux._timers[' + this.id + ']){' + script + '}';
      this._timeout = setTimeout(script, this.timeout);
   };

   var ns = 'Reactivate.delayex_' + timer.id;

   $('body').unbind(ns).bind(ns, function () { 
      if (timer.isActive()) { 
         timer.callback();
         timer.setTimeout();
      } else { 
         $(this).unbind(ns);
      }
   });   
   timer.setTimeout();
   return timer;
}
flux.timer(10000, function () { 
   if (typeof ActivityMonitor !== "undefined") { 
      flux.log("TimerChk: " + flux._timers.length + " Timers, Inactive4: " + ActivityMonitor.getInactivity() );
   }
});
function uo_identify(object) {
   var uo_uri = typeof object == "string" ? object : $(object).attr('uo');
   var uo_pieces = uo_uri.split('://');
   var uo_abs_type = uo_pieces[0];
   if(uo_aliases[uo_pieces[0]]){
      uo_abs_type=uo_aliases[uo_pieces[0]];
   }
   return {
      uri:uo_uri, 
      type: uo_pieces[0], 
      object: uo_pieces[1],
      abs_type: uo_abs_type,
      target: object
   };
}

function uo_parselize(_uo, arr) {
   var result={}, tmp;
   var tpl = '$tpl';
   if(arr.template) {
      tpl=arr.template;
      arr.template=false;
   }
   for(var x in arr){
      if(typeof arr[x] == "object") {
         result[x] = uo_parselize(_uo, arr[x]);
      } else if(jQuery.isFunction(arr[x])) {
         tmp = arr[x](_uo);
         if (!!tmp) { 
            result[x] = tmp;
         } 
      } else {
         if(arr[x].match && arr[x].match('notpl:')) { 
            arr[x] = arr[x].replace('notpl:','');
         } else if(arr[x]) { 
            arr[x] = tpl.replace('$tpl', arr[x]);
         }
         if(arr[x] && arr[x].match && arr[x].match(/\$/)) {
            result[x] = arr[x].replace(/\$uri/g, _uo.uri);
            result[x] = result[x].replace(/\$id/g,_uo.object);

            if(result[x].match(/^exec:/)) {
               result[x] = result[x].replace('exec:','');
            } else {
               result[x] = 'iph.load(\'' + result[x] + '\').setReference(this.eventTarget);';
            }
         } else if(arr[x]) { 
            result[x] = arr[x];
         }
      }
   }
   return result;
}
function uo_handle(e){
   if(e.type == "mouseup") { return; }
   
   var _uo = uo_identify(e.target);
   
   if(!_uo.type || !uos[_uo.type]){ 
      return flux.log("uo_handle: Invalid scheme " + _uo.uri); 
   }
   
   log=['uo_handle:'];

   var parselize= uo_parselize;
   
   if(e.type == "mousedown" && e.which == 1 &&  e.shiftKey) {
      var tmp = e.target;
      if ($(tmp).is('.uo-master *')) { 
         tmp = $(tmp).closest('.uo-master');
      }
      if($(tmp).is('.uo-selected')) {
         $(tmp).removeClass('uo-selected');
      } else {
         $(tmp).addClass('uo-selected');
      }
      $(tmp).trigger('selectionChanged');
      killEvent(e);
      return false;
   }
   var bCtx = (e.type == "mousedown" && e.which == 3) ||
              (e.type == "mousedown" && e.which == 1 && e.ctrlKey);

   if(bCtx) { 
      log.push('bctx=true');
      e.target.contextmenu = null;
      var actions =  uos[_uo.type].actions;
      if(typeof actions.open == "string") { 
         actions.open = {
            defaultAction : actions.open,
            'with' : 'exec:interface.openWith(\'$uri\', event);'
         };
      }
      log.push('actions-before ' );
      log.push(actions);

      actions = parselize(_uo,actions);
      if (uos[_uo.type].extensions) {
         var fn = uos[_uo.type].extensions.determine;
         var tmp = window[fn](_uo.object);
         if (tmp) {
            var caption = tmp;
            var t = caption.charAt(0).toUpperCase();
            caption = t + caption.substr(1);
            caption += ' Options';
            tmp=uos[_uo.type].extensions[tmp]; // load extensions
            if (tmp) { 
               // prepend extension options to list.
               var prep = {};
               prep[caption] = parselize(_uo, tmp);
               actions = $.extend({}, prep, actions);
            }
         }
      }
      //actions.properties = parselize(_uo, uos[_uo.type].properties);
      if(e.which == 1) { 
         try { 
         e.target.oncontextmenu = function(){
            flux.ctx.render(e, actions);
            return false;
         };
         }catch(ex){alert(ex); }
      } else { 
         e.target.contextmenu = actions;
      }
      log.push('actions: ');
      log.push(actions);
   } else { 
      log.push('bctx=false');
   }
   if(e.type == "dblclick") {
      if($(e.target).is("input")) {
         return;
      }
      if(uos[_uo.type].dblclick) {
         var parsed = parselize(_uo, {x:uos[_uo.type].dblclick});
         e.target.eventTarget=e.target;
         $(e.target).each(new Function(parsed.x));
      }
   }
   return true;
}

flux.uo = {
   find: function (target) {
      if (typeof target == "string") { 
         return $('*[uo=' + target + ']');
      } else { 
         return $(target);
      }
   },
   
   highlight: function (target) { 
      var mode = false;
      var count = 0;
      var thresh = [
         500,
         2000,
         3000
      ];

      flux.timer (20, function () { 
         mode = !mode; 
         var elem = flux.uo.find(target);
         var pos = this.executions * this.timeout;
         var p;
         
         if (pos < thresh[0]) { 
            // to yellow
            p = Math.min(255,Math.round(((thresh[0] - pos) / thresh[0]) * 255));
            $(elem).css('background-color', 'rgb(255,255,' + p + ')');
         } else if (pos < thresh[1]) { 
            // remain
         } else if (pos < thresh[2] + 50) { 
            // to fade...
            p = 255 - Math.round(((thresh[2] - pos) / (thresh[2]-thresh[1])) * 255);
            $(elem).css('background-color', 'rgb(255,255,' + p + ')');
         } else { 
            $(elem).css('background-color', '');
            this.destroy();
         }
      });
   }
}
//>>Import <JS> Ext.UpdateDaemon.Object
ActivityMonitor = flux.timer(500, function(){
   this.tick = true;
   // lock screen after 5 minutes.
   if(this.getInactivity() > 300) {
      if(!this.locked) { 
         this.lock();
      }
   }
   // Session has expired (after 30 minutes).
   if(this.getInactivity() == 1800) { 
      /* this.interfaceLocker.css({height:"60px"}).area.append('<div style="color:red;font-size:12px;">Your session has expired.</div>');
      */
   }
});
// Intelligent Interval
ActivityMonitor.intellival = function (base) { 
   var ina = ActivityMonitor.getInactivity();
   if (ina < 10) { 
      return base;
   } else { 
      var ina2 = Math.min(base + Math.round(((ina - 10)/3) * 1000), 5*60*1000);
      //flux.log("Intelligent Interval: " + (ina2/1000) + " for " + (ina));
      return ina2;
   }
};

ActivityMonitor._lastMovedOn = 0;
// returns inactivity in seconds.
ActivityMonitor.getInactivity = function(){
   if(this.executions > (this._lastMovedOn + 5)) { 
      return (this.executions - this._lastMovedOn) / 2;
   }
   return 0;
};

ActivityMonitor.lock = function(){
   this.locked = true;
   if(typeof lockInterface !== "undefined") {
      lockInterface();
   } 
};

ActivityMonitor.unlock = function(){
   if(this.locked) { 
      this.locked = false;
      if(typeof unlockInterface !== "undefined") {
         unlockInterface();
      }

   }
};

ActivityMonitor.distance = 0;
ActivityMonitor.prev = [0,0];
ActivityMonitor.ticker = function(){
   var t = this.tick;   
   this.tick = false;
   return t;
};
ActivityMonitor.hasFocus = function () { 
   return ActivityMonitor.wndFocussed;
};
$(function(){

$('body').mousedown(function(e){
   // van altresize
   var css={
      helper:{
         position:'absolute',
         backgroundColor:'#aaa',
         opacity:0.5,
         zIndex:2000,
         overflow:'visible',
         color:'black',
         fontWeight: 'bold',
         fontSize: '20px',
         'text-shadow':'0px 0px 10px white',
         textAlign: 'center'
      },
      overlay:{
         height:'100%', width:'100%',
         left:0, top:0,
         position:'fixed',
         backgroundImage: 'url(img/spacer.gif)',
         zIndex:3000
      },
      handle:{ cursor: 'ne-resize' }
   };
   css.overlay.backgroundImage = 'url(res/img/spacer.gif)';
   if(e.type == 'mousedown' && e.ctrlKey && e.altKey) { 
      flux.log("Start Measurement");
      var overlay = $('<div id="overlay">').appendTo('body').css(css.overlay);
      var start = [e.pageX, e.pageY];
      var item = $('<div>').appendTo('body')
         .css(css.helper)
      ;   
      $('body').bind('mouseup.measure',function(){
         $(this).unbind('mouseup.measure');
         flux.log('End Measure');
         flux.delay(1,function(){ 
            $('#overlay').remove();    
            $(item).fadeOut('fast',function(){$(this).remove();});
         });
      });
      $(overlay).mousemove(function(e){ 
         var ct = [Math.min(start[0],e.pageX),Math.min(start[1],e.pageY)];
         var cb = [Math.max(start[0],e.pageX),Math.max(start[1],e.pageY)];
         var d = {left: ct[0], top: ct[1], width: (cb[0]-ct[0]), height: (cb[1] - ct[1])};
         $(item).css(d);
         $(item).html('<div style="position:absolute;top:43%;left:50%;margin-left:-50px;">' + 
            d.width + ' x ' + d.height + 
         '</div>');
      });
      return false;
   }
});

});

$.fn.copyCss = function(source, attr) { 
   attr = typeof attr == "string" ? attr.split(",") : attr;
   for(var x in attr){
      $(this).css(attr[x],$(source).css(attr[x]));
   }
   return $(this);
}; 
$.fn.altResizable = function(handle,reference) {
   var positioning = flx(this).isFixed() ? 'fixed' : 'absolute';

   reference = reference || 'body';

   var css={
      helper:{
         position: positioning,
         backgroundColor:'#aaa',
         opacity:0.5,
         zIndex:2000
      },
      overlay:{
         height:'100%', width:'100%',
         left:0, top:0,
         position:'fixed',
         backgroundImage: 'url(img/spacer.gif)',
         zIndex:3000
      },
      handle:{ 
         cursor: 'se-resize'
      }
   };
   css.overlay.backgroundImage = 'url(res/img/spacer.gif)';
   $(this).each(function(){
      var target = this;
      $(target).find(handle).mousedown(function(e){   
         // set some attrs
         $(target).css({
            //left: $(target).attr('offsetLeft'),   
            //top: $(target).attr('offsetTop'),
            bottom: null,
            right: null,
            width: $(target).css('width') || $(target).attr('offsetWidth'),
            height: $(target).css('height') || $(target).attr('offsetHeight')
         });
         var cpyAttr = 'position,left,top,width,height,-moz-border-radius,border';
         var item = $('<div>').appendTo(reference)
            .copyCss(target, 'left,top,width,height,padding')
            .css(css.helper)
         ;
         //flux.log(reference);
         var overlay = $('<div>').appendTo('body').css(css.overlay);
         var start = [e.pageX, e.pageY];
         var inidim = [
            $(item).attr('offsetWidth') , 
            $(item).attr('offsetHeight') 
         ];
         var inipos = [
            $(item).attr("offsetLeft") + pInt($(item).css('margin-left')), 
            $(item).attr("offsetTop") + pInt($(item).css('margin-top'))
         ];
         var controlStart = start;

         $(overlay).mousemove(function(e){
            var offset = [start[0] - e.pageX, start[1] - e.pageY];
            if(!e.ctrlKey) { 
               var i1,i2;
               var ndim = [inidim[0]-offset[0],inidim[1]-offset[1]];
               if(ndim[0] * ndim[1] < 1000) { return; }
               $(item).css({
                  width:(i1=Math.floor(ndim[0]/10)*10)+"px",
                  height:(i2=Math.floor(ndim[1]/10)*10)+"px"
               });
               controlStart = [e.pageX,e.pageY];
            } else { 
               offset = [controlStart[0]-e.pageX,controlStart[1]-e.pageY];
               $(item).css({
                  left:(inipos[0]-offset[0])+"px",
                  top:(inipos[1]-offset[1])+"px"
               });
            }
         }).mouseup(function(e){
            $(target).copyCss(item, 'top,left,width,height');
            flux.delay(1,function(){
               $(item).remove();
               $(overlay).remove();   
            });
            $(target).trigger('resized');
            $(target).trigger('resized_user');
            $(target).trigger('mouseup');
            return false;
         });
         return false;
      }).css(css.handle);
   });
};

flux.definePanel('univas_chrome',function(){
   var parent = new flux.panel.presets.chrome();
   for(var x in parent) {
      this[x]=parent[x];
   }
   this.type = 'univas_chrome';
   this.html = this.html.replace("flux-panel", "flux-panel flux-univas-chrome");
   this.bind = function(html, oflux){ 
      parent.bind(html);
      $(html).resizable('destroy');      
      $(html).altResizable([
         '.flx-middle .flx-right',
         '.flx-bottom > div'
      ].join(','));
   };
});
flux.dlgtype = 'simple';
flux.dlg = function(target,y,dlgtype) { 
   dlgtype = dlgtype||flux.dlgtype||'simple';
   target = $(target)[0];   
   if(!target.dialog || !$(target.dialog).isAlive()) {
      target.dialog = flux.create(dlgtype).dimRel(target);
      if(iph&&iph.mouse) { 
         target.dialog.css('top', iph.mouse.y);
      } 
      target.dialog.onTerminate = function(){
         target.dialog=false;
         return true;
      };
      target.dialog.feedback = function (value, caption) { 
         var item;
         caption=caption||value;
         if($(target).is("select")) { 
            if($(target).find("option[value=" + value + "]").length == 0){
               item = $('<option selected=true />').appendTo(target);
               item.attr('value',value);
               item.html(caption);
            } else { 
               $(target).val(value);
            }
         } else { 
            $(target).val(value);
         }
         target.dialog.exit();
      };
      $(target.dialog.container).click(function(e){
         if($(e.target).is("*[dlgval]")) {
            var value = $(e.target).attr("dlgval");
            var caption = $(e.target).attr('dlgcaption');
            target.dialog.feedback(value, caption);
         }
      }); 
   }
   $(target.dialog.container).show();
   return target.dialog.activate();
};
$(function(){
   fluxalize_overlay(this);
});

flux.definePanel('popup', function (tgt) { 
   var parent = new flux.panel.presets.chrome();
   for(var x in parent) {
      this[x]=parent[x];
   }
   this.type = "popup";
   this.containerCss = {position: 'fixed'};
   this.html = 
   '<div class="flux-panel flux-popup">' +
      '<div class="flx-top">' + 
         '<a onclick="flx(this).exit();" title="Sluiten" style="font-size:20px;float:right;margin-top:-4px;">&#8855;</a>' +       

         '<div class="flx-title"></div>' + 
      '</div>' + 
      '<div class="flx-canvas"></div>' +
      '<div class="flx-bottom"></div>' + 
   '</div>'
   ;      
});

$(function(){
   //flux.log("Flux Build %' + 'XGenerator.Date%");
   //START HIER
   fluxalize("body");
   
   $.ajaxSetup({cache: false});
   
   $('body').mousedown(function(e){
      if(!$(e.target).is('#flux-contextmenu *')) {
         $('#flux-contextmenu').hide();
      }
   }).click(function(e){
      var tgt = e.target;
      if($(tgt).is(".fluxed a[href] *")) {
         tgt = $(tgt).closest("a");
      }
      if($(tgt).is(".fluxed a[href]:not(.handled)")) {  
         var _tgt = $(tgt).attr("target");
         var href= $(tgt).attr("href");
         if(href.match("(mailto:|javascript:)")) {
            return true;
         } 
         if(_tgt.match(/^[#|\.]/)) { 
            if($(tgt).is(".scoped")) {
               flx(flx(tgt).area.find(_tgt)).load(href);
            } else { 
               flx($(_tgt)).load($(tgt).attr("href"));
            }
         } else if(_tgt.match("flux:")) { 
             _tgt = _tgt.replace("flux:","");
            _fluxalize(null, "load="+$(tgt).attr("href")+","+_tgt);
         } else if(!_tgt) { 
            flx(tgt).load($(tgt).attr("href"));
         } else if(_tgt.match(/(_top|_self)/)) {
            return true;
         } else if(_tgt > "") { 
            window.open(flux.url($(tgt).attr("href")));
         } 
         return false;
      } else if ($(tgt).is('.fluxed a[param]')) { 
         var ftgt = flx(tgt);
         url = ftgt.state && ftgt.state[0] ? ftgt.state[0] : ftgt.getUrl();
         data = ftgt.state && ftgt.state[1] ? ftgt.state[1] : {};
         data[$(tgt).attr('param')] = $(tgt).attr('value');
         ftgt.load(url, data);
         return false;
      }
   }).bind('contextmenu', function(e){
      flux.log("Ext.Ctx contextmenu-event on body - Control? " + e.ctrlKey);
      if(!e.ctrlKey) { 
         flux.log(' --> ' + e.target + ' ctx: ' + e.target.contextmenu);
         if(e.target.contextmenu) { 
            flux.ctx.render(e, e.target.contextmenu);
            return false;               
         }
      }
   });
   $('*[onsuggest]').keydown(function (e) { 
      flux.onsuggest(this, e, $(this).attr('onsuggest'));
   });
   //VPANE, HPANE support
   if (typeof vpane !== "undefined" && $('[vpane]').length) {
      //alert("TRIGGER VPANE");
      vpane($('[vpane]'));
   }
   if (typeof hpanels !== "undefind" && $('[hpane]').length) { 
      //alert("TRIGGER HPANE");
      //var rd=flx(e.target).getUrl().split('?')[0];
      var rd = flux.relUrl(location.href).split('?')[0];
      var hp = {
         draggableSeparator: false,
         rememberDimensions: false,
         items: []
      };
      $('[hpane]').each (function () {
         var n = {node: this};
         var a = {};
         $($(this).attr('hpane').split(';')).each(function(i,j) { 
            var x = j.split(':');
            if (x[0]) { 
               if (x[0] == 'draggable') {
                  hp.draggableSeparator=true;
                  return true;
               } 
               if (x[0] == 'remember') { 
                  hp.rememberDimensions = rd;
                  return true;
               }
               n[$.trim(x[0])]=$.trim(x[1]);
            }
         });
         hp.items.push(n);
      });
   
      flux.log(hp);
      hpanels(hp);
   }
   //>>ImportAll <JS> Ext.*.Init
   
      $('body').bind("dblclick click mouseup mousedown", function(e) {
         
         if(typeof $(e.target).attr('uo') !== "undefined") { 
            return e.preventUo ? null : uo_handle(e);
         } else {
            var closest_uo = $(e.target).closest('*[uo]').addClass('uo-master').attr('uo');
            if(closest_uo) { 
               $(e.target).attr('uo', closest_uo);
               return e.preventUo ? null : uo_handle(e);
            } else if(e.type == 'mousedown' && e.target.className.match(/toggle-next/)) {
               $(e.target).next().toggle();
            }
         }
      });


   //EINDIG HIER

   var script_type_init = function(){
      if (!$(this).is('.handled')) { 
         //flux.log("Handling inittrigger");
         var html = $(this).addClass('handled').html();
         html=html.replace("<!--","").replace("-->","");
         var fn = new Function(html);
         $(this).parent().each(fn);
      } else { 
         flux.log("Ignoring inittrigger");
      }
   };

   $(iph.getInitTrigger()).each(script_type_init);

   $('body').bind('updateContent', function(e) { 
      // Flux Popup Support
      if($(e.target).find('.flx-popup').length) { 
         $(e.target).find('.flx-popup').each(function(){
            var panel = flux.create('univas_chrome')
               .setContent($(this).removeClass('flx-popup'))
               .css(iph.getStartingPoint())
               .css({marginLeft:5,marginTop:5})
               .css({
                  width: pInt($(this).css('width')) + 20, 
                  height: pInt($(this).css('height')) + 50
               })
            ;
            if($(this).hasClass('flx-coc')) { 
               panel.closeOnClick();
            }
         });
      }
      
      // Flux Flash Support
      if($(e.target).find('.flx-flash').length) { 
         // place and go...
         $(e.target).find('.flx-flash').each(function(){
            flx(e.target).flash($(this).removeClass('flx-flash'));
         });
      }
      $(e.target).find('input[type=submit]').click(function(){
         this.checked=true;
      });
      // Flux InitScript Support
      flux.log("UPDATECONTENT");
      flux.log(e.target);
      var tmp;
      tmp='code[type=init]';
      $(e.target).find(tmp).each(script_type_init);
   });

   $('body').bind("dblclick mousedown", function(e) {
      if(e.target.className.match(/toggle-next/)) {
         $(e.target).next().toggle();
      }
   });
   $('body').click(function(e) { 
      var tgt = e.target;
      if($(tgt).is("a[launch]")) {
         var p = iph.load($(tgt).attr('launch'));
         if ($(tgt).is('.fluxed a')) { 
            p.setReference(flx(tgt).area);
         }
         return false;
      } else if($(tgt).is('a[launch_transfer]')) {
         iph.load($(tgt).attr('launch_transfer')).setReference(flx(tgt).getReference());
         flx(tgt).exit();
         return false;
      } else if ($(tgt).is('a[post]')) { 
         var form = $(tgt).closest('form');
         var data = $.unserialize($(tgt).attr('post'));
         var i;
         for (i in data) { if (data.hasOwnProperty(i)) { 
            $('<input type=hidden />').attr('name', i).val(data[i]).appendTo(form);
         }}
         $(form).submit();
      }
   });
   $('body').bind('resized_user',function(e){
      var mflx = flx(e.target);
      var dim={
         width:$(e.target).css('width'),
         height:$(e.target).css('height')
      };
      if(mflx.state && mflx.state[0]) { 
         if (mflx.setPref) { 
            mflx.setPref('width', dim.width);
            mflx.setPref('height', dim.height);
            mflx.savePref();
         } else { 
            var str = "width="+dim.width+"\n"+"height="+dim.height;
            var flxaddr = 'flx://' + mflx.state[0].split('?')[0];
            iph.preferences[flxaddr]={preferences:str};
            $.post('default/storepref',{uri:flxaddr,pref:str});
         }
      }
      //report
      var w = $(e.target).css('width');
      var h = $(e.target).css('height');
      flux.log("Resized window to " + w + " x " + h);

      return killEvent(e);
   });
});


flux.panel.presets.ubuntu = function(){
   var parent = new flux.panel.presets.chrome();
   for(var x in parent) {
      this[x]=parent[x];
   }
   this.type = "ubuntu";
   this.html = 
   '<div class="flux-panel flux-ubuntu">' +
   '<div class="flx-top">' +
      '<div class="flx-left"></div>' +
      '<div class="flx-xright">' + 
         //'<a title="Help" onclick="iph.load(\'default/info\',{url:flx(this).getUrl()})">?</a>' + 
         '<a onclick="flx(this).load();" title="Ververs" class="sprite ico-reload-white">&nbsp;</a>' + 
         '<a onclick="flx(this).exit();" title="Sluiten" class="sprite ico-close-white">&nbsp;</a>' + 
      '</div>' +
      '<div class="flx-center flx-title">' + 
         'Dyflexis' +
      '</div>' +
   '</div>' +
   '<div class="flx-middle">' +
      '<div class="flx-canvas"></div>' +
      '<div class="flx-right"></div>' +
   '</div>' + 
   '<div class="flx-bottom">' +
      '<div class="flx-left"></div>' +
      '<div class="flx-right"></div>' +
      '<div class="flx-center"></div>' +
   '</div>' +
   '</div>'
   ;      
   this.bind = function(html, oflux){ 
      parent.bind(html);
      $(html).bind('updateContent',function(t){
         var area = flx(this).area;
         if(area.find('.flx-no-padding, .col2').length>0){ 
            area.removeClass('padded');
         } else {
            area.addClass('padded');
         }
         //flux.log(t);
      });
      extractCss=function(elem,attr){
         var res = {};
         if(typeof attr == "string") { attr = attr.split(","); }
         for(var x in attr){
            res[attr[x]] = $(elem).css(attr[x]);
         }
         flux.log(res);
         return res;
      };
      //$(html).find(".flx-top .flx-left").html('&bull;');
      //$(html).draggable('option','grid',[10,10]);
      $(html).resizable('destroy');      
      $(html).altResizable([
         '.flx-middle .flx-right',
         '.flx-bottom'
      ].join(','));
      oflux.dim('grid');

      $(html).find('.flx-bottom .flx-right').css({
         'background-image' : 'url(res/css/images/ui-icons_222222_256x240.png)',
         'background-position' : ' -80px -224px',
         'width' : '20px',
         'height' : '15px',
         position: 'absolute',
         right: 0,
         bottom: 0
      });
   };
   
};

flux.definePanel('univas_chrome', function(){
   var parent = new flux.panel.presets.ubuntu();
   for(var x in parent) {
      this[x]=parent[x];
   }
});

$(function() { 
   $('body').unbind('selectionChanged');
});
uos={};
uo_aliases={};
$(function(){
   
      $('body').bind("dblclick click mouseup mousedown", function(e) {
         
         if(typeof $(e.target).attr('uo') !== "undefined") { 
            return e.preventUo ? null : uo_handle(e);
         } else {
            var closest_uo = $(e.target).closest('*[uo]').addClass('uo-master').attr('uo');
            if(closest_uo) { 
               $(e.target).attr('uo', closest_uo);
               return e.preventUo ? null : uo_handle(e);
            } else if(e.type == 'mousedown' && e.target.className.match(/toggle-next/)) {
               $(e.target).next().toggle();
            }
         }
      });
});
