
// 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);
      return false;
   } 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)';
      
      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() { 

var fixtgt = null;
if (!$(this).is('[vpane], [vpane] *')) { 
   var coord = {
      top: $(this).parent()[0].offsetTop,
      left: $(this).parent()[0].offsetLeft,
      width: $(this).parent()[0].offsetWidth
   };

   var scrollarea = $(this).closest('table').wrap('<div />').parent().css({
      position: 'absolute',
      top: coord.top,
      left: coord.left,
      overflow: 'auto',
      right: 0,
      bottom: 0
   });
   
   fixtgt = $(this);   
} else { 
   var scrollarea = $(this).closest('[vpane]').parent();
   if ($(this).find('.fluxfix').length == 0) { 
      fixtgt = $(this).find('thead:first');
   } else { 
      fixtgt = $(this).find('.fluxfix');
   }
}
 
if ($.browser.msie) {
   return;
}
  
$(fixtgt).after($(fixtgt).clone());

//fixtgt = $(fixtgt).clone().insertBefore(fixtgt);

fixtgt.css({
   position: 'absolute',
   display: 'block',
   zIndex: 500,
   top: 0,
   left: 0
});   

var children_float  = $(fixtgt).find('th,td');
var children_static = $(fixtgt).next().find('th,td');

if (children_float.length !== children_static.length) { 
   if (isWodan) { alert("fluxFix: aantallen children-float, children-static komen niet overeen"); }
}

var totalWidth = 0;
var gs = function (e,p) { 
   e=$(e).get(0);
   if (window.getComputedStyle) { 
      return getComputedStyle(e)[p];
   } else if (e.currentStyle){
      return e.currentStyle[p];
   }
}

$(children_float).each(function (i) {
   var mir = children_static.eq(i);
   var offsets = {
      pdl: pInt(mir.css('padding-left')),
      pdr: pInt(mir.css('padding-right'))
   }
   mir = mir.get(0);
   var usew = pInt(gs(mir,'width')); 

   $(this).width(usew).attr('title', 'width = ' + usew);

   totalWidth += usew;
});

$(fixtgt).css('width', $(fixtgt).closest('table').width());

var timer = null;

scrollarea.bind('mousewheel DOMMouseScroll', function (e) {
   if (!(e.target.scrollTop === 0 || e.target.scrollTop === e.target.scrollHeight)) { 
      $(fixtgt).hide();
   }

}).scroll(function (e) {
   //if (pInt($(fixtgt).css('top')) === e.target.scrollTop) { 
   //   return;
   //}
   $(fixtgt).css('width', $(fixtgt).closest('table').width());

   $(fixtgt).hide().delay(100, function () {

      $(fixtgt).css('top', e.target.scrollTop).stop(true,true).fadeIn();
   });
});

if (flx(fixtgt).container) { 
   flx(fixtgt).container.bind('resize', function () {
      $(children_float).each(function (i) {
         var mir = children_static.eq(i);
         var offsets = {
            pdl: pInt(mir.css('padding-left')),
            pdr: pInt(mir.css('padding-right'))
         }
         mir = mir.get(0);
         var usew = pInt(gs(mir,'width')); 

         $(this).width(usew).attr('title', 'width = ' + usew);
      });

      $(fixtgt).css('width', $(fixtgt).closest('table').width());
   });
}
}

(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 (url === '#') { 
         return this;
      }
      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,z) {var t = (x+'').indexOf(y, (z||0)); 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
               };
               

               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.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;
};
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 flxmodal(url, width, height) { 
   var panel = flux.create('simple').load(url)
      .css({
         width:width, 
         height:height,
         left:'50%',
         top:'50%',
         marginTop: (height*-0.5),
         marginLeft: (width*-0.5),
         position:'absolute'
      });

   panel.modal(true);

   panel.closeOnClick = function() { 
      $(panel.container).click(function(){ panel.exit(); });
   };
   return panel;
}
