//window.__eval = function(script) {
//  return eval(script);
//}


/* jQuery Publixe environment plugin */
jQuery.extend({

/* init publixe window relation and share list of wnds */
  publixe: function(name) {
    if (window.opener && window.opener.__wnd) {
      window.__wnd = window.opener.__wnd;
    }
    else {
      window.__wnd = new Array();
    }
    window.name = name;
    window.__wnd[name] = window;
  },



/* get wnd handle by name */
  wnd: function(name) {
    if (window.__wnd[name])
      return window.__wnd[name];
    else
      alert('wnd handle ' + name + ' not in list');
  },



/* revive all presenters */
  revive: function(data, self) {
    var c = new Object();
    for (var i in data) {
      wnd = data[i][0];
      w = data[i][1];

//alert('revive WND:'+wnd+', W:'+w+', I:'+i);

 // accessory item
      if (typeof w == 'object') {
        for (a in w) {
          if (typeof w[a] == 'object') {
 // spacial accessory
alert('Special accessory not supported yet.');
          }
          else {
            this.wnd(wnd).eval(w[a]);
          }
        }
      }
 // wrapper properties
      else {
        p = data[i][2];
        html = data[i][3];
 // set wrapper inner code
        if (p) {
          o = this.wnd(wnd).document.getElementById(w);
          if (html != null) {
            o.innerHTML = html;
            if (c[wnd] == undefined) {
              c[wnd] = new Object();
            }
            c[wnd][w] = o;
          }

try {
//alert('ted updatuju properties '+w);
          o.__properties = p;
}
catch (e) {
  alert(e + '\n\n' + w);
}



        }
      }
    }
 // revive publixe environemnt
    if (!self) {
      for (var i in c) {
        for (var a in c[i]) {

// alert('REVIVE '+i+' => '+a+' => '+c[i][a]);

 // auto init modified presenters
//          this.wnd(wnd).$(c[i][a]).revive();
          this.wnd(i).$(c[i][a]).revive();
//          $(c[i][a]).revive();
        }
      }
    }
    else {
 // init new document window
      $(document).revive();
    }
  },



/* call server event and send registr */
  publixeEvent: function(event, args, sender) {
// build registr
    registr = new Object();
    rootNode = $('#' + event.split('::')[0]).parentNode;
    r = $("span[class$='Presenter']", rootNode);
    for (i = 0; i < r.length; i++) {
      p = r.eq(i).get(0);
      if (p.__registr != undefined) {
        for (key in p.__registr) { // achjo:( check empty object
          registr[p.id] = p.__registr;
          p.__registr = {}; //!!!! maybe after request
          break;
        }
      }
    }
// send request with registr
    document.__requestSuccess = false;  // Opera patch, it's ghost story :(
    $('#ajax_init').show();

    if (!document.__requestLock) {
      document.__requestLock = true;

      $.ajax({
        type: "POST",
        url: "index.php",
        data: {
          wnd: window.name,
          event: event,
          registr: $.toJSON(registr),
          args: args != undefined ? $.toJSON(args) : '',
          sender: sender
        },
        dataType: "json",
        error: function(xhr) {
          document.__requestLock = false;
          document.__requestSuccess = true;

          if (xhr.getResponseHeader('content-type').indexOf('text/javascript') != -1) { // possible debug mode
            eval(xhr.responseText);
          }
          else {
            alert('Error:\n\n' + xhr.responseText);
          }
          $('#ajax_init').hide();

        },
        success: function(data) {
          if (!document.__requestSuccess) {
            document.__requestLock = false;
            document.__requestSuccess = true;
            $('#ajax_init').hide();
            $.revive(data, false);
          }
        }
      });
    }
  },



/* alert dialog */
  alert: function(message) {
    alert(message);
  },



/* alert dialog */
  confirm: function(message, event) {
    if (confirm(message)) {
      this.publixeEvent(event, Array(), window.name);
    }
  },



/* window open */
  open: function(target, wnd, params) {
    var p = Array();

    if (params.width != undefined && params.height != undefined) {
      p.width = params.width;
      p.height = params.height;

      if (params.left == undefined) {
        p.left = (screen.width - p.width) / 2;
      }
      if (params.top == undefined) {
        p.top = (screen.height - p.height) / 2;
      }
    }
    p.status = 1;
    p.toolbar = 0;

    var r = '';
    for (i in p) {
      if (r != '') {
        r += ',';
      }
      r += i + '=' + p[i];
    }
    window.open(target, wnd, r);
  }

});


/* jQuery Publixe environment plugin for presenter wrappers */
jQuery.fn.extend({

/* revive presenter wrapper element */
  revive: function() {
    return this.each(function() {

 // revive node
      reviveNode = function(node) {
        if (node != undefined) {
          if (node.nodeType == 1) {
            if (node.tagName == 'SPAN' && node.className) {
 // try to construct presenter
              try {
                constructor = node.className.match(/([^ ]*)Presenter/i)[1];
                eval('$(node).' + constructor + 'Presenter();');
                node.__registr = {};
              }
              catch (e) {
//alert('constructor class of ' + constructor + ' not loaded. $e = ' + $(node).get(0));
              }
            }
          }
          for (i in node.childNodes) {
            reviveNode(node.childNodes[i]);
          }
        }
      }
 // revive all nodes in this
      reviveNode(this);
    });
  },



/* update presenter wrapper registr */
  publixeRegistrChange: function(key, value, multi) {
    return this.each(function() {

      if (value instanceof Array) {

        f = '__func';
        if (this.__registr[f] == undefined) {
          this.__registr[f] = {};
        }
//alert('key:'+key);
        if (multi) {
          if (this.__registr[f][key] == undefined) {
            this.__registr[f][key] = Array();
          }
          len = this.__registr[f][key].length;
          this.__registr[f][key][len] = value;
        }
        else {
          this.__registr[f][key] = Array(value);
        }
      }
      else {
        this.__registr[key] = value;
      }
    });
  },



/* call server event and send registr */
  publixeEvent: function(event, args) {
    return this.each(function() {
      jQuery.publixeEvent(event, args, this.id);
    });
  }


});

