/**
 * Element visualizer
 */
var ElementVisualizer = Class.create({
	isOpen:null,
	appearElementId:null,
	triggerElementId:null,
	options:null,

    initialize: function(name, triggerName, options) {

		this.appearElementId = name;
        this.triggerElementId = triggerName;
        this.setOptions(options);
		
        this.isOpen = false;
        Element.setStyle($(this.appearElementId),{
            position: "absolute",
            top: "0px",
            left: "0px",
            display: "none"
        });

        this.setOptions = this.setOptions.bind(this);
        this.applyOffset = this.applyOffset.bind(this);
        this.open = this.open.bind(this);
        this.close = this.close.bind(this);
    },

    open: function() {
        this.isOpen = true;
        this.applyOffset();
        Effect.Appear($(this.appearElementId), {duration : this.options.effectDuration});
    },

    close: function() {
        this.isOpen = false;		
        Effect.Fade($(this.appearElementId), {duration : this.options.effectDuration});
    },
	
	applyOffset: function() {
    	var offsets;
    	if(this.options.usePositionedOffset) {
            offsets = Element.positionedOffset($(this.triggerElementId));
    	} else {
    	    offsets = Element.cumulativeOffset($(this.triggerElementId));
    	}

		if(this.options.fixedPosition) {
			Element.setStyle($(this.appearElementId),{
                left: this.options.leftFixedPosition + 'px',
                top: this.options.topFixedPosition + 'px'
            });
		}
		else {

        if(this.options.rightAlign) {
            Element.setStyle($(this.appearElementId),{
                left: offsets[0] - $(this.appearElementId).getWidth() + $(this.triggerElementId).getWidth() + this.options.leftExtraOffset + 'px',
                top: offsets[1] + $(this.triggerElementId).getHeight() + this.options.topExtraOffset + 'px'
            });
        }
        else {
            Element.setStyle($(this.appearElementId),{
                left: offsets[0] + this.options.leftExtraOffset + 'px',
                top: offsets[1] + $(this.triggerElementId).getHeight() + this.options.topExtraOffset + 'px'
            });
        }
		}
	},

    setOptions: function(options) {
        this.options = Object.extend({
		    rightAlign: false,
		    effectDuration: 0.3,
		    topExtraOffset: 2,
	 	    leftExtraOffset: 0,
			fixedPosition: false,
			leftFixedPosition: 0,
			topFixedPosition: 0,
			usePositionedOffset: false
	    }, options || {});
	}
});

var ElementVisualizerManager = {
	visualizers : null,
	
	addVisualizer: function(visualizerId, triggerId, options) {
	    var visualizer = new ElementVisualizer(visualizerId, triggerId, options);

	    if(!ElementVisualizerManager.visualizers) {
			ElementVisualizerManager.visualizers = new Hash();
		}
		ElementVisualizerManager.visualizers.set(triggerId, visualizer);
	},
	
	closeVisualizer: function(triggerId) {
		if(ElementVisualizerManager.visualizers) {
			var visualizer = ElementVisualizerManager.visualizers.get(triggerId);
			if(visualizer && visualizer.isOpen) {
				visualizer.close();
			}
		}
	},
	
	removeVisualizer: function(triggerId) {
		if(ElementVisualizerManager.visualizers) {
			ElementVisualizerManager.visualizers.unset(triggerId);
		}
	},

	observe: function() {
		Event.observe(document,'click', ElementVisualizerManager.clickManager);
		Event.observe(window, 'resize', ElementVisualizerManager.refreshVisualizersPosition);
	},
	
	refreshVisualizersPosition: function() {
		if(ElementVisualizerManager.visualizers) {
			ElementVisualizerManager.visualizers.each(function(visualizer){
				if(visualizer.value && visualizer.value.isOpen) {
					visualizer.value.applyOffset();
				}
			});
		}
	},
	
	stopObserving: function() {
		Event.stopObserving(document,'click', ElementVisualizerManager.clickManager);
		Event.stopObserving(window, 'resize', ElementVisualizerManager.refreshVisualizersPosition);
	},
	
	clean: function() {
		ElementVisualizerManager.visualizers = null;
	},
	
	clickManager: function(event) {
		if(Event.element(event) && Event.element(event).id) {
			if(ElementVisualizerManager.visualizers) {	
				var triggerId = Event.element(event).id;
				ElementVisualizerManager.visualizers.each(function(visualizer){
					if(triggerId == visualizer.key && visualizer.value && !visualizer.value.isOpen) {
						visualizer.value.open();
					} else if(visualizer.value && visualizer.value.isOpen && !Event.element(event).descendantOf(visualizer.value.appearElementId)) {
						visualizer.value.close();
					}
				});
			}
		}
	}
};


/**
 * Shadedborders scripts
 */

/**
 * RUZEE.ShadedBorder 0.6.1
 * (c) 2006 Steffen Rusitschka
 *
 * RUZEE.ShadedBorder is freely distributable under the terms of an MIT-style license.
 * For details, see http://www.ruzee.com/
 */

var RUZEE = window.RUZEE || {};

RUZEE.ShadedBorder = {

create: function(opts) {
  var isie = /msie/i.test(navigator.userAgent) && !window.opera;
  var isie6 = isie && !window.XMLHttpRequest;
  function sty(el, h) {
    for(k in h) {
      if (/ie_/.test(k)) {
        if (isie) el.style[k.substr(3)]=h[k];
      } else el.style[k]=h[k];
    }
  }
  function crdiv(h) {
    var el=document.createElement("div");
    el.className = "sb-gen";
    sty(el, h);
    return el;
  }
  function op(v) {
    v = v<0 ? 0 : v;
    if (v>0.99999) return "";
    return isie ? " filter:alpha(opacity=" + (v*100) + ");" : " opacity:" + v + ';';
  }

  var sr = opts.shadow || 0;
  var r = opts.corner || 0;
  var bor = 0;
  var bow = opts.border || 0;
  var boo = opts.borderOpacity || 1;
  var shadow = sr != 0;
  var lw = r > sr ? r : sr;
  var rw = lw;
  var th = lw;
  var bh = lw;
  if (bow > 0) {
    bor = r;
    r = r - bow;
  }
  var cx = r != 0 && shadow ? Math.round(lw/3) : 0;
  var cy = cx;
  var cs = Math.round(cx/2);
  var iclass = r > 0 ? "sb-inner" : "sb-shadow";
  var sclass = "sb-shadow";
  var bclass = "sb-border";
  var edges = opts.edges || "trlb";
  if (!/t/i.test(edges)) th=0;
  if (!/b/i.test(edges)) bh=0;
  if (!/l/i.test(edges)) lw=0;
  if (!/r/i.test(edges)) rw=0;

  var p = { position:"absolute", left:"0", top:"0", width:lw + "px", height:th + "px", 
            ie_fontSize:"1px", overflow:"hidden", margin:"0", padding:"0" }; var tl = crdiv(p);
  delete p.left; p.right="0"; p.width=rw + "px"; var tr = crdiv(p);
  delete p.top; p.bottom="0"; p.height=bh + "px"; var br = crdiv(p);
  delete p.right; p.left="0"; p.width=lw + "px"; var bl = crdiv(p);

  var tw = crdiv({ position:"absolute", width:"100%", height:th + "px", ie_fontSize:"1px",
                   top:"0", left:"0", overflow:"hidden", margin:"0", padding:"0" });
  var t = crdiv({ position:"relative", height:th + "px", ie_fontSize:"1px",
                  margin:"0 "+ rw + "px 0 " + lw + "px", overflow:"hidden", padding:"0" });
  tw.appendChild(t);

  var bw = crdiv({ position:"absolute", left:"0", bottom:"0", width:"100%", height:bh + "px", 
                   ie_fontSize:"1px", overflow:"hidden", margin:"0", padding:"0" });
                   
  var b = crdiv({ position:"relative", height:bh + "px", ie_fontSize:"1px",
                  margin:"0 "+ rw + "px 0 " + lw + "px", overflow:"hidden", padding:"0" });
                  
  bw.appendChild(b);

  var mw = crdiv({ position:"absolute", top:(-bh)+"px", left:"0", width:"100%", height:"100%",
                   overflow:"hidden", ie_fontSize:"1px", padding:"0", margin:"0" });

  function corner(el,t,l) {
    var w = l ? lw : rw;
    var h = t ? th : bh;
    var s = t ? cs : -cs;
    var dsb = []; var dsi = []; var dss = [];
    
    var xp=0; var xd=1; if (l) { xp=w-1; xd=-1; }
    for (var x=0; x<w; ++x) {
      var yp=h-1; var yd=-1; if (t) { yp=0; yd=1; }
      var finished=false;
      for (var y=h-1; y>=0 && !finished; --y) {
        var div = '<div style="position:absolute; top:' + yp + 'px; left:' + xp + 'px; ' +
                  'width:1px; height:1px; overflow:hidden; margin:0; padding:0;';

        var xc = x - cx; var yc = y - cy - s;
        var d = Math.sqrt(xc*xc+yc*yc);
        var doShadow = false;

        if (r > 0) {
          // draw border
          if (xc < 0 && yc < bor && yc >= r || yc < 0 && xc < bor && xc >= r) {
            dsb.push(div + op(boo) + '" class="' + bclass + '"></div>');
          } else
          if (d<bor && d>=r-1 && xc>=0 && yc>=0) {
            var dd = div;
            if (d>=bor-1) {
              dd += op((bor-d)*boo);
              doShadow = true;
            } else dd += op(boo);
            dsb.push(dd + '" class="' + bclass + '"></div>');
          }
          
          // draw inner
          var dd = div + ' z-index:2;' + (t ? 'background-position:0 -' + (r-yc-1) + 'px;' : 'background-image:none;');
          var finish = function() {
            if (!t) dd = dd.replace(/top\:\d+px/, "top:0px");
            dd = dd.replace(/height\:1px/, "height:" + (y+1) + "px");
            dsi.push(dd + '" class="' + iclass + '"></div>');
            finished = true;
          };
          if (xc < 0 && yc < r || yc < 0 && xc < r) {
            finish();
          } else
          if (d<r && xc>=0 && yc>=0) {
            if (d>=r-1) {
              dd += op(r-d);
              doShadow = true;
              dsi.push(dd + '" class="' + iclass + '"></div>');
            } else {
              finish();
            }
          } else doShadow = true;
        } else doShadow = true;
        
        // draw shadow
        if (sr > 0 && doShadow) {
          d = Math.sqrt(x*x+y*y);
          if (d<sr) {
            dss.push(div + ' z-index:0; ' + op(1-(d/sr)) + '" class="' + sclass + '"></div>');
          }
        }
        yp += yd;
      }
      xp += xd;
    }
    el.innerHTML = dss.concat(dsb.concat(dsi)).join('');
  }
  
  function mid(mw) {
    var ds = [];

    ds.push('<div style="position:relative; top:' + (th+bh) + 'px; height:2048px; ' +
            ' margin:0 ' + (rw-r-cx) + 'px 0 ' + (lw-r-cx) + 'px; ' +
            ' padding:0; overflow:hidden;' +
            ' background-position:0 ' + (th > 0 ? -(r+cy+cs) : '0') + 'px;"' +
            ' class="' + iclass + '"></div>');

    var dd = '<div style="position:absolute; width:1px;' +
        ' top:' + (th+bh) + 'px; height:2048px; padding:0; margin:0;';
    if (sr>0) {
      for (var x=0; x<lw-r-cx; ++x) {
        ds.push(dd + ' left:' + x + 'px;' + op((x+1.0)/lw) + 
            '" class="' + sclass + '"></div>');
      }

      for (var x=0; x<rw-r-cx; ++x) {
        ds.push(dd + ' right:' + x + 'px;' + op((x+1.0)/rw) + 
            '" class="' + sclass + '"></div>');
      }
    }

    if (bow > 0) {
      var su = ' width:' + bow + 'px;' + op(boo) + '" class="' + bclass + '"></div>';
      ds.push(dd + ' left:' + (lw-bor-cx) + 'px;' + su);
      ds.push(dd + ' right:' + (rw-bor-cx) + 'px;' + su);
    }

    mw.innerHTML = ds.join('');
  }

  function tb(el, t) {
    var ds = [];
    var h = t ? th : bh;
    var dd = '<div style="height:1px; overflow:hidden; position:absolute; margin:0; padding:0;' +
        ' width:100%; left:0px; ';
    var s = t ? cs : -cs;
    for (var y=0; y<h-s-cy-r; ++y) {
      if (sr>0) ds.push(dd + (t ? 'top:' : 'bottom:') + y + 'px;' + op((y+1)*1.0/h) + 
          '" class="' + sclass + '"></div>');
    }
    if (y >= bow) {
      ds.push(dd + (t ? 'top:' : 'bottom:') + (y - bow) + 'px;' + op(boo) +
          ' height:' + bow + 'px;" class="' + bclass + '"></div>');
    }

    ds.push(dd + (t ? 'background-position-y:0; top:' : 
                      'background-image:none; bottom:') + y + 'px;' +
        ' height:' + (r+cy+s) + 'px;" class="' + iclass + '"></div>');

    el.innerHTML = ds.join('');
  }

  corner(tl, true, true); corner(tr, true, false);
  corner(bl, false, true); corner(br, false, false);
  mid(mw); tb(t, true); tb(b, false);

  return {
    render: function(el) {
      if (typeof el == 'string') el = document.getElementById(el);
      if (el.length != undefined) {
        for (var i=0; i<el.length; ++i) this.render(el[i]);
        return;
      }
      el.className += " sb";
      sty(el, { position:"relative", background:"transparent" });

      // remove generated children
      var node = el.firstChild;
      while (node) {
        var nextNode = node.nextSibling;
        if (node.nodeType == 1 && node.className == 'sb-gen')
          el.removeChild(node);
        node = nextNode;
      }

      var iel = el.firstChild;

      var twc = tw.cloneNode(true);
      var mwc = mw.cloneNode(true);
      var bwc = bw.cloneNode(true);
      
      el.insertBefore(tl.cloneNode(true), iel); el.insertBefore(tr.cloneNode(true), iel);
      el.insertBefore(bl.cloneNode(true), iel); el.insertBefore(br.cloneNode(true), iel);
      el.insertBefore(twc, iel); el.insertBefore(mwc, iel);
      el.insertBefore(bwc, iel);

      if (isie6) {
        el.onmouseover=function() { this.className+=" hover"; }
        el.onmouseout=function() { this.className=this.className.replace(/ hover/,""); }
      }
      if (isie) {
        function resize() {
          twc.style.width = bwc.style.width = mwc.style.width = el.offsetWidth + "px";
          mwc.firstChild.style.height = el.offsetHeight + "px";
        }
        el.onresize=resize;
        resize();
      }
    }
  };
}
}

// add our styles to the document
document.write('\
  <style type="text/css">\
  .sb, .sbi, .sb *, .sbi * { position:relative; z-index:100; }\
  * html .sb, * html .sbi { height:1%; }\
  .sbi { display:inline-block; }\
  .sb-inner { background:#ddd; }\
  .sb-shadow { background:#000; }\
  .sb-border { background:#bbb; }\
  </style>\
');


/**
 * Window scripts
 */

var Window = Class.create();

Window.keepMultiModalWindow = false;
Window.hasEffectLib = (typeof Effect != 'undefined');
Window.resizeEffectDuration = 0.4;

Window.prototype = {
  // Constructor
  // Available parameters : className, blurClassName, title, minWidth, minHeight, maxWidth, maxHeight, width, height, top, left, bottom, right, resizable, zIndex, opacity, recenterAuto, wiredDrag
  //                        hideEffect, showEffect, showEffectOptions, hideEffectOptions, effectOptions, url, draggable, closable, minimizable, maximizable, parent, onload
  //                        add all callbacks (if you do not use an observer)
  //                        onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose
  
  initialize: function() {
    var id;
    var optionIndex = 0;
    // For backward compatibility like win= new Window("id", {...}) instead of win = new Window({id: "id", ...})
    if (arguments.length > 0) {
      if (typeof arguments[0] == "string" ) {
        id = arguments[0];
        optionIndex = 1;
      }
      else
        id = arguments[0] ? arguments[0].id : null;
    }
    
    // Generate unique ID if not specified
    if (!id)
      id = "window_" + new Date().getTime();
      
  //  if ($(id)) {
  //    $(id).remove();
  //  }
      //alert("Window " + id + " is already registered in the DOM! Make sure you use setDestroyOnClose() or destroyOnClose: true in the constructor");

    this.options = Object.extend({
      className:         "dialog",
      blurClassName:     null,
      minWidth:          100, 
      minHeight:         20,
      resizable:         true,
      closable:          true,
      minimizable:       true,
      maximizable:       true,
      draggable:         true,
      userData:          null,
      showEffect:        (Window.hasEffectLib ? Effect.Appear : Element.show),
      hideEffect:        (Window.hasEffectLib ? Effect.Fade : Element.hide),
      showEffectOptions: {},
      hideEffectOptions: {},
      effectOptions:     null,
      parent:            document.body,
      title:             "&nbsp;",
      url:               null,
      onload:            Prototype.emptyFunction,
      width:             200,
      height:            300,
      opacity:           1,
      recenterAuto:      true,
      wiredDrag:         false,
      closeCallback:     null,
      destroyOnClose:    false,
      gridX:             1, 
      gridY:             1      
    }, arguments[optionIndex] || {});
    if (this.options.blurClassName)
      this.options.focusClassName = this.options.className;
      
    if (typeof this.options.top == "undefined" &&  typeof this.options.bottom ==  "undefined") 
      this.options.top = this._round(Math.random()*500, this.options.gridY);
    if (typeof this.options.left == "undefined" &&  typeof this.options.right ==  "undefined") 
      this.options.left = this._round(Math.random()*500, this.options.gridX);

    if (this.options.effectOptions) {
      Object.extend(this.options.hideEffectOptions, this.options.effectOptions);
      Object.extend(this.options.showEffectOptions, this.options.effectOptions);
      if (this.options.showEffect == Element.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    }
    if (Window.hasEffectLib) {
      if (this.options.showEffect == Effect.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    
      if (this.options.hideEffect == Effect.Fade)
        this.options.hideEffectOptions.from = this.options.opacity;
    }
    if (this.options.hideEffect == Element.hide)
      this.options.hideEffect = function(){ Element.hide(this.element); if (this.options.destroyOnClose) this.destroy(); }.bind(this)
    
    if (this.options.parent != document.body)  
      this.options.parent = $(this.options.parent);
      
    this.element = this._createWindow(id);       
    this.element.win = this;
       
    // Bind event listener
    this.eventMouseDown = this._initDrag.bindAsEventListener(this);
    this.eventMouseUp   = this._endDrag.bindAsEventListener(this);
    this.eventMouseMove = this._updateDrag.bindAsEventListener(this);
    this.eventOnLoad    = this._getWindowBorderSize.bindAsEventListener(this);
    this.eventMouseDownContent = this.toFront.bindAsEventListener(this);
    this.eventResize = this._recenter.bindAsEventListener(this);
 
    this.topbar = $(this.element.id + "_top");
    this.bottombar = $(this.element.id + "_bottom");
    this.content = $(this.element.id + "_content");
    
//    Event.observe(this.topbar, "mousedown", this.eventMouseDown);
//    Event.observe(this.bottombar, "mousedown", this.eventMouseDown);
//    Event.observe(this.content, "mousedown", this.eventMouseDownContent);
//    Event.observe(window, "load", this.eventOnLoad);
//    Event.observe(window, "resize", this.eventResize);
    Event.observe(window, "scroll", this.eventResize);
//    Event.observe(this.options.parent, "scroll", this.eventResize);
    
//    if (this.options.draggable)  {
//      var that = this;
//      [this.topbar, this.topbar.up().previous(), this.topbar.up().next()].each(function(element) {
//        element.observe("mousedown", that.eventMouseDown);
//        element.addClassName("top_draggable");
//      });
//      [this.bottombar.up(), this.bottombar.up().previous(), this.bottombar.up().next()].each(function(element) {
//        element.observe("mousedown", that.eventMouseDown);
//        element.addClassName("bottom_draggable");
//      });
//      
//    }    
    
//    if (this.options.resizable) {
//      this.sizer = $(this.element.id + "_sizer");
//      Event.observe(this.sizer, "mousedown", this.eventMouseDown);
//    }  
    
    this.useLeft = null;
    this.useTop = null;
    if (typeof this.options.left != "undefined") {
      this.element.setStyle({left: parseFloat(this.options.left) + 'px'});
      this.useLeft = true;
    }
    else {
      this.element.setStyle({right: parseFloat(this.options.right) + 'px'});
      this.useLeft = false;
    }
    
    if (typeof this.options.top != "undefined") {
      this.element.setStyle({top: parseFloat(this.options.top) + 'px'});
      this.useTop = true;
    }
    else {
      this.element.setStyle({bottom: parseFloat(this.options.bottom) + 'px'});      
      this.useTop = false;
    }
      
    this.storedLocation = null;
    
    this.setOpacity(this.options.opacity);
    if (this.options.zIndex)
      this.setZIndex(this.options.zIndex)

    if (this.options.destroyOnClose)
      this.setDestroyOnClose(true);

    this._getWindowBorderSize();
    this.width = this.options.width;
    this.height = this.options.height;
    this.visible = false;
    
    this.constraint = false;
    this.constraintPad = {top: 0, left:0, bottom:0, right:0};
    
    if (this.width && this.height)
      this.setSize(this.options.width, this.options.height);
    this.setTitle(this.options.title);
    Windows.register(this);      
  },
  
  // Destructor
  destroy: function() {
    this._notify("onDestroy");
    Event.stopObserving(this.topbar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.bottombar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.content, "mousedown", this.eventMouseDownContent);
    
    Event.stopObserving(window, "load", this.eventOnLoad);
    Event.stopObserving(window, "resize", this.eventResize);
    Event.stopObserving(window, "scroll", this.eventResize);
    
    Event.stopObserving(this.content, "load", this.options.onload);

    if (this._oldParent) {
      var content = this.getContent();
      var originalContent = null;
      for(var i = 0; i < content.childNodes.length; i++) {
        originalContent = content.childNodes[i];
        if (originalContent.nodeType == 1) 
          break;
        originalContent = null;
      }
      if (originalContent)
        this._oldParent.appendChild(originalContent);
      this._oldParent = null;
    }

    if (this.sizer)
        Event.stopObserving(this.sizer, "mousedown", this.eventMouseDown);

    if (this.options.url) 
      this.content.src = null

     if(this.iefix) {
       if (!(typeof this.iefix.parentNode == 'undefined') && (typeof this.iefix.parentNode == 'unknown')) {
         Element.remove(this.iefix);
       }
     }

    Element.remove(this.element);
    Windows.unregister(this);      
  },
    
  // Sets close callback, if it sets, it should return true to be able to close the window.
  setCloseCallback: function(callback) {
    this.options.closeCallback = callback;
  },
  
  // Gets window content
  getContent: function () {
    return this.content;
  },
  
  // Sets the content with an element id
  setContent: function(id, autoresize, autoposition) {
    var element = $(id);
    if (null == element) throw "Unable to find element '" + id + "' in DOM";
    this._oldParent = element.parentNode;

    var d = null;
    var p = null;

    if (autoresize) 
      d = Element.getDimensions(element);
    if (autoposition) 
      p = Position.cumulativeOffset(element);

    var content = this.getContent();
    // Clear HTML (and even iframe)
    this.setHTMLContent("");
    content = this.getContent();
    
    content.appendChild(element);
    element.show();
    if (autoresize) 
      this.setSize(d.width, d.height);
    if (autoposition) 
      this.setLocation(p[1] - this.heightN, p[0] - this.widthW);    
  },
  
  setHTMLContent: function(html) {
    // It was an url (iframe), recreate a div content instead of iframe content
    if (this.options.url) {
      this.content.src = null;
      this.options.url = null;
      
  	  var content ="<div id=\"" + this.getId() + "_content\" class=\"" + this.options.className + "_content\"> </div>";
      $(this.getId() +"_table_content").innerHTML = content;
      
      this.content = $(this.element.id + "_content");
    }
      
    this.getContent().innerHTML = html;
  },
  
  setAjaxContent: function(url, options, showCentered, showModal) {
    this.showFunction = showCentered ? "showCenter" : "show";
    this.showModal = showModal || false;
  
    options = options || {};

    // Clear HTML (and even iframe)
    this.setHTMLContent("");
 
    this.onComplete = options.onComplete;
    if (! this._onCompleteHandler)
      this._onCompleteHandler = this._setAjaxContent.bind(this);
    options.onComplete = this._onCompleteHandler;

    new Ajax.Request(url, options);    
    options.onComplete = this.onComplete;
  },
  
  _setAjaxContent: function(originalRequest) {
    Element.update(this.getContent(), originalRequest.responseText);
    if (this.onComplete)
      this.onComplete(originalRequest);
    this.onComplete = null;
    this[this.showFunction](this.showModal)
  },
  
  setURL: function(url) {
    // Not an url content, change div to iframe
    if (this.options.url) 
      this.content.src = null;
    this.options.url = url;
    var content= "<iframe frameborder='0' name='" + this.getId() + "_content'  id='" + this.getId() + "_content' src='" + url + "' width='" + this.width + "' height='" + this.height + "'> </iframe>";
    $(this.getId() +"_table_content").innerHTML = content;
    
    this.content = $(this.element.id + "_content");
  },

  getURL: function() {
  	return this.options.url ? this.options.url : null;
  },

  refresh: function() {
    if (this.options.url)
	    $(this.element.getAttribute('id') + '_content').src = this.options.url;
  },
  
  // Stores position/size in a cookie, by default named with window id
  setCookie: function(name, expires, path, domain, secure) {
    name = name || this.element.id;
    this.cookie = [name, expires, path, domain, secure];
    
    // Get cookie
    var value = WindowUtilities.getCookie(name)
    // If exists
    if (value) {
      var values = value.split(',');
      var x = values[0].split(':');
      var y = values[1].split(':');

      var w = parseFloat(values[2]), h = parseFloat(values[3]);
      var mini = values[4];
      var maxi = values[5];

      this.setSize(w, h);
      if (mini == "true")
        this.doMinimize = true; // Minimize will be done at onload window event
      else if (maxi == "true")
        this.doMaximize = true; // Maximize will be done at onload window event

      this.useLeft = x[0] == "l";
      this.useTop = y[0] == "t";

      this.element.setStyle(this.useLeft ? {left: x[1]} : {right: x[1]});
      this.element.setStyle(this.useTop ? {top: y[1]} : {bottom: y[1]});
    }
  },
  
  // Gets window ID
  getId: function() {
    return this.element.id;
  },
  
  // Detroys itself when closing 
  setDestroyOnClose: function() {
    this.options.destroyOnClose = true;
  },
  
  setConstraint: function(bool, padding) {
    this.constraint = bool;
    this.constraintPad = Object.extend(this.constraintPad, padding || {});
    // Reset location to apply constraint
    if (this.useTop && this.useLeft)
      this.setLocation(parseFloat(this.element.style.top), parseFloat(this.element.style.left));
  },
  
  // initDrag event

  _initDrag: function(event) {
    // No resize on minimized window
    if (Event.element(event) == this.sizer && this.isMinimized())
      return;

    // No move on maximzed window
    if (Event.element(event) != this.sizer && this.isMaximized())
      return;
      
    if (Prototype.Browser.IE && this.heightN == 0)
      this._getWindowBorderSize();
    
    // Get pointer X,Y
    this.pointer = [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];
    if (this.options.wiredDrag) 
      this.currentDrag = this._createWiredElement();
    else
      this.currentDrag = this.element;
      
    // Resize
    if (Event.element(event) == this.sizer) {
      this.doResize = true;
      this.widthOrg = this.width;
      this.heightOrg = this.height;
      this.bottomOrg = parseFloat(this.element.getStyle('bottom'));
      this.rightOrg = parseFloat(this.element.getStyle('right'));
      this._notify("onStartResize");
    }
    else {
      this.doResize = false;

      // Check if click on close button, 
      var closeButton = $(this.getId() + '_close');
      if (closeButton && Position.within(closeButton, this.pointer[0], this.pointer[1])) {
        this.currentDrag = null;
        return;
      }

      this.toFront();

      if (! this.options.draggable) 
        return;
      this._notify("onStartMove");
    }    
    // Register global event to capture mouseUp and mouseMove
//    Event.observe(document, "mouseup", this.eventMouseUp, false);
//    Event.observe(document, "mousemove", this.eventMouseMove, false);
    
    // Add an invisible div to keep catching mouse event over iframes
    WindowUtilities.disableScreen('__invisible__', '__invisible__', this.overlayOpacity);

    // Stop selection while dragging
    document.body.ondrag = function () { return false; };
    document.body.onselectstart = function () { return false; };
    
    this.currentDrag.show();
    Event.stop(event);
  },
  
  _round: function(val, round) {
    return round == 1 ? val  : val = Math.floor(val / round) * round;
  },

  // updateDrag event
  _updateDrag: function(event) {
    var pointer =  [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];  
    var dx = pointer[0] - this.pointer[0];
    var dy = pointer[1] - this.pointer[1];
    
    // Resize case, update width/height
    if (this.doResize) {
      var w = this.widthOrg + dx;
      var h = this.heightOrg + dy;
      
      dx = this.width - this.widthOrg
      dy = this.height - this.heightOrg
      
      // Check if it's a right position, update it to keep upper-left corner at the same position
      if (this.useLeft) 
        w = this._updateWidthConstraint(w)
      else 
        this.currentDrag.setStyle({right: (this.rightOrg -dx) + 'px'});
      // Check if it's a bottom position, update it to keep upper-left corner at the same position
      if (this.useTop) 
        h = this._updateHeightConstraint(h)
      else
        this.currentDrag.setStyle({bottom: (this.bottomOrg -dy) + 'px'});
        
      this.setSize(w , h);
      this._notify("onResize");
    }
    // Move case, update top/left
    else {
      this.pointer = pointer;
      
      if (this.useLeft) {
        var left =  parseFloat(this.currentDrag.getStyle('left')) + dx;
        var newLeft = this._updateLeftConstraint(left);
        // Keep mouse pointer correct
        this.pointer[0] += newLeft-left;
        this.currentDrag.setStyle({left: newLeft + 'px'});
      }
      else 
        this.currentDrag.setStyle({right: parseFloat(this.currentDrag.getStyle('right')) - dx + 'px'});
      
      if (this.useTop) {
        var top =  parseFloat(this.currentDrag.getStyle('top')) + dy;
        var newTop = this._updateTopConstraint(top);
        // Keep mouse pointer correct
        this.pointer[1] += newTop - top;
        this.currentDrag.setStyle({top: newTop + 'px'});
      }
      else 
        this.currentDrag.setStyle({bottom: parseFloat(this.currentDrag.getStyle('bottom')) - dy + 'px'});

      this._notify("onMove");
    }
    if (this.iefix) 
      this._fixIEOverlapping(); 
      
    this._removeStoreLocation();
    Event.stop(event);
  },

   // endDrag callback
   _endDrag: function(event) {
    // Remove temporary div over iframes
     WindowUtilities.enableScreen('__invisible__');
    
    if (this.doResize)
      this._notify("onEndResize");
    else
      this._notify("onEndMove");
    
    // Release event observing
    Event.stopObserving(document, "mouseup", this.eventMouseUp,false);
    Event.stopObserving(document, "mousemove", this.eventMouseMove, false);

    Event.stop(event);
    
    this._hideWiredElement();

    // Store new location/size if need be
    this._saveCookie()
      
    // Restore selection
    document.body.ondrag = null;
    document.body.onselectstart = null;
  },

  _updateLeftConstraint: function(left) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;

      if (left < this.constraintPad.left)
        left = this.constraintPad.left;
      if (left + this.width + this.widthE + this.widthW > width - this.constraintPad.right) 
        left = width - this.constraintPad.right - this.width - this.widthE - this.widthW;
    }
    return left;
  },
  
  _updateTopConstraint: function(top) {
    if (this.constraint && this.useLeft && this.useTop) {        
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      
      var h = this.height + this.heightN + this.heightS;

      if (top < this.constraintPad.top)
        top = this.constraintPad.top;
      if (top + h > height - this.constraintPad.bottom) 
        top = height - this.constraintPad.bottom - h;
    }
    return top;
  },
  
  _updateWidthConstraint: function(w) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;
      var left =  parseFloat(this.element.getStyle("left"));

      if (left + w + this.widthE + this.widthW > width - this.constraintPad.right) 
        w = width - this.constraintPad.right - left - this.widthE - this.widthW;
    }
    return w;
  },
  
  _updateHeightConstraint: function(h) {
    if (this.constraint && this.useLeft && this.useTop) {
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      var top =  parseFloat(this.element.getStyle("top"));

      if (top + h + this.heightN + this.heightS > height - this.constraintPad.bottom) 
        h = height - this.constraintPad.bottom - top - this.heightN - this.heightS;
    }
    return h;
  },
  
  
  // Creates HTML window code
  _createWindow: function(id) {
    var className = this.options.className;
    var win = document.createElement("div");
    win.setAttribute('id', id);
    win.className = "dialog";

    var content = content ="<div id=\"" + id + "_content\" class=\"" +className + "_content\"> </div>";

    win.innerHTML = "" + "\
      <table id='"+ id +"_row1' class=\"top table_window\">\
        <tr>\
          <td class='"+ className +"_nw'></td>\
          <td class='"+ className +"_n'><div id='"+ id +"_top' class='"+ className +"_title title_window'>"+ this.options.title +"</div><span></span></td>\
          <td class='"+ className +"_ne'></td>\
        </tr>\
      </table>\
      <table id='"+ id +"_row2' class=\"mid table_window\">\
        <tr>\
          <td class='"+ className +"_w'></td>\
            <td id='"+ id +"_table_content' class='"+ className +"_content' valign='top'>" + content + "</td>\
          <td class='"+ className +"_e'></td>\
        </tr>\
      </table>\
        <table id='"+ id +"_row3' class=\"bot table_window\">\
        <tr>\
          <td class='"+ className +"_sw'></td>\
            <td class='"+ className +"_s'><div id='"+ id +"_bottom' class='status_bar'><span style='float:left; width:1px; height:1px'></span></div></td>\
            <td></td>\
        </tr>\
      </table>\
    ";
    Element.hide(win);
    this.options.parent.insertBefore(win, this.options.parent.firstChild);
    // Event.observe($(id + "_content"), "load", this.options.onload);
    return win;
  },
  
  
  changeClassName: function(newClassName) {    
    var className = this.options.className;
    var id = this.getId();
    $A(["_close", "_minimize", "_maximize", "_sizer", "_content"]).each(function(value) { this._toggleClassName($(id + value), className + value, newClassName + value) }.bind(this));
    this._toggleClassName($(id + "_top"), className + "_title", newClassName + "_title");
    $$("#" + id + " td").each(function(td) {td.className = td.className.sub(className,newClassName); });
    this.options.className = newClassName;
  },
  
  _toggleClassName: function(element, oldClassName, newClassName) { 
    if (element) {
      element.removeClassName(oldClassName);
      element.addClassName(newClassName);
    }
  },
  
  // Sets window location
  setLocation: function(top, left) {
    top = this._updateTopConstraint(top);
    left = this._updateLeftConstraint(left);

    var e = this.currentDrag || this.element;
    e.setStyle({top: top + 'px'});
    e.setStyle({left: left + 'px'});

    this.useLeft = true;
    this.useTop = true;
  },
    
  getLocation: function() {
    var location = {};
    if (this.useTop)
      location = Object.extend(location, {top: this.element.getStyle("top")});
    else
      location = Object.extend(location, {bottom: this.element.getStyle("bottom")});
    if (this.useLeft)
      location = Object.extend(location, {left: this.element.getStyle("left")});
    else
      location = Object.extend(location, {right: this.element.getStyle("right")});
    
    return location;
  },
  
  // Gets window size
  getSize: function() {
    return {width: this.width, height: this.height};
  },
    
  // Sets window size
  setSize: function(width, height, useEffect) {    
    width = parseFloat(width);
    height = parseFloat(height);
    
    // Check min and max size
    if (!this.minimized && width < this.options.minWidth)
      width = this.options.minWidth;

    if (!this.minimized && height < this.options.minHeight)
      height = this.options.minHeight;
      
    if (this.options. maxHeight && height > this.options. maxHeight)
      height = this.options. maxHeight;

    if (this.options. maxWidth && width > this.options. maxWidth)
      width = this.options. maxWidth;

    
    if (this.useTop && this.useLeft && Window.hasEffectLib && Effect.ResizeWindow && useEffect) {
      new Effect.ResizeWindow(this, null, null, width, height, {duration: Window.resizeEffectDuration});
    } else {
      this.width = width;
      this.height = height;
      var e = this.currentDrag ? this.currentDrag : this.element;

      e.setStyle({width: width + this.widthW + this.widthE + "px"})
      e.setStyle({height: height  + this.heightN + this.heightS + "px"})

      // Update content size
      if (!this.currentDrag || this.currentDrag == this.element) {
        var content = $(this.element.id + '_content');
        content.setStyle({height: height  + 'px'});
        content.setStyle({width: width  + 'px'});
      }
    }
  },
  
  updateHeight: function() {
    this.setSize(this.width, this.content.scrollHeight, true);
  },
  
  updateWidth: function() {
    this.setSize(this.content.scrollWidth, this.height, true);
  },
  
  // Brings window to front
  toFront: function() {
    if (this.element.style.zIndex < Windows.maxZIndex)  
      this.setZIndex(Windows.maxZIndex + 1);
    if (this.iefix) 
      this._fixIEOverlapping(); 
  },
   
  getBounds: function(insideOnly) {
    if (! this.width || !this.height || !this.visible)  
      this.computeBounds();
    var w = this.width;
    var h = this.height;

    if (!insideOnly) {
      w += this.widthW + this.widthE;
      h += this.heightN + this.heightS;
    }
    var bounds = Object.extend(this.getLocation(), {width: w + "px", height: h + "px"});
    return bounds;
  },
      
  computeBounds: function() {
     if (! this.width || !this.height) {
      var size = WindowUtilities._computeSize(this.content.innerHTML, this.content.id, this.width, this.height, 0, this.options.className)
      if (this.height)
        this.width = size + 5
      else
        this.height = size + 5
    }

    this.setSize(this.width, this.height);
    if (this.centered)
      this._center(this.centerTop, this.centerLeft);    
  },
  
  // Displays window modal state or not
  show: function(modal) {
    this.visible = true;
    if (modal) {
      // Hack for Safari !!
      if (typeof this.overlayOpacity == "undefined") {
        var that = this;
        setTimeout(function() {that.show(modal)}, 10);
        return;
      }
      Windows.addModalWindow(this);
      
      this.modal = true;      
      this.setZIndex(Windows.maxZIndex + 1);
      Windows.unsetOverflow(this);
    }
    else    
      if (!this.element.style.zIndex) 
        this.setZIndex(Windows.maxZIndex + 1);        
      
    // To restore overflow if need be
    if (this.oldStyle)
      this.getContent().setStyle({overflow: this.oldStyle});
      
    this.computeBounds();
    
    this._notify("onBeforeShow");   
    if (this.options.showEffect != Element.show && this.options.showEffectOptions)
      this.options.showEffect(this.element, this.options.showEffectOptions);  
    else
      this.options.showEffect(this.element);  
	
    // Hack by Emiliano Mettini for IE ¬¬
    if (Prototype.Browser.IE) {
	  $('overlay_modal').setStyle({width: WindowUtilities.getPageSize().windowWidth + 'px'});
	}      
    this._checkIEOverlapping();
    
    WindowUtilities.focusedWindow = this
    this._notify("onShow");   
  },
  
  // Displays window modal state or not at the center of the page
  showCenter: function(modal, top, left) {
    this.centered = true;
    this.centerTop = top;
    this.centerLeft = left;

    this.show(modal);
  },
  
  isVisible: function() {
    return this.visible;
  },
  
  _center: function(top, left) {    
//    var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    
//    var pageSize = WindowUtilities.getPageSize(this.options.parent);    
//    if (typeof top == "undefined")
//      top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2;
//    top += windowScroll.top
//    
//    if (typeof left == "undefined")
//      left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2;
//    left += windowScroll.left      
//    this.setLocation(top, left);
//    this.toFront();

	var winPositionType = $(this.element.id).getStyle('position'); 
	if(!winPositionType && winPositionType == 'absolute') {
		var scroll = WindowUtilities.getWindowScroll();
    	loader.style.left = (scroll.left + (scroll.width/2)) + "px";
    	loader.style.top = (scroll.top + (scroll.height/2)) + "px";
	    $(this.element.id).setStyle({
	    	left:(scroll.left + (scroll.width/2) - (this.width/2)) + "px", 
	    	top:(scroll.top + (scroll.height/2) - (this.height/2)) + "px" 
	    });
	} else {
	    $(this.element.id).setStyle({
	    	left:'50%', 
	    	top:'50%', 
	    	margin: '-' + (this.height/2) + 'px 0 0 -' + (this.width/2) + 'px'
	    });
	}
  },
  
  _recenter: function(event) {     
    if (this.centered) {
      var pageSize = WindowUtilities.getPageSize(this.options.parent);
      var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    

      // Check for this stupid IE that sends dumb events
      if (this.pageSize && this.pageSize.windowWidth == pageSize.windowWidth && this.pageSize.windowHeight == pageSize.windowHeight && 
          this.windowScroll.left == windowScroll.left && this.windowScroll.top == windowScroll.top) 
        return;
      this.pageSize = pageSize;
      this.windowScroll = windowScroll;
      // set height of Overlay to take up whole page and show
      if ($('overlay_modal')) {
		 // Hack by Emiliano Mettini (IE puts a margin of 20px to the overlay)
  	    if (Prototype.Browser.IE || Prototype.Browser.Opera) {
          $('overlay_modal').setStyle({height: ((pageSize.pageHeight + 20) + 'px')});
	    } else {
		  $('overlay_modal').setStyle({height: (pageSize.pageHeight + 'px')});
	    } 	  
	  }
      
      if (this.options.recenterAuto)
        this._center(this.centerTop, this.centerLeft);    
    }
  },
  
  // Hides window
  hide: function() {
    this.visible = false;
    if (this.modal) {
      Windows.removeModalWindow(this);
      Windows.resetOverflow();
    }
    // To avoid bug on scrolling bar
    this.oldStyle = this.getContent().getStyle('overflow') || "auto"
    this.getContent().setStyle({overflow: "hidden"});

    this.options.hideEffect(this.element, this.options.hideEffectOptions);  

     if(this.iefix) 
      this.iefix.hide();

    if (!this.doNotNotifyHide)
      this._notify("onHide");
  },

  close: function() {
    // Asks closeCallback if exists
    if (this.visible) {
      if (this.options.closeCallback && ! this.options.closeCallback(this)) 
        return;

      if (this.options.destroyOnClose) {
        var destroyFunc = this.destroy.bind(this);
        if (this.options.hideEffectOptions.afterFinish) {
          var func = this.options.hideEffectOptions.afterFinish;
          this.options.hideEffectOptions.afterFinish = function() {func();destroyFunc() }
        }
        else 
          this.options.hideEffectOptions.afterFinish = function() {destroyFunc() }
      }
      Windows.updateFocusedWindow();
      
      this.doNotNotifyHide = true;
      this.hide();
      this.doNotNotifyHide = false;
      this._notify("onClose");
    }
  },
  
  minimize: function() {
    if (this.resizing)
      return;
    
    var r2 = $(this.getId() + "_row2");
    
    if (!this.minimized) {
      this.minimized = true;

      var dh = r2.getDimensions().height;
      this.r2Height = dh;
      var h  = this.element.getHeight() - dh;

      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, null, null, null, this.height -dh, {duration: Window.resizeEffectDuration});
      } else  {
        this.height -= dh;
        this.element.setStyle({height: h + "px"});
        r2.hide();
      }

      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom + dh) + 'px'});
      }
    } 
    else {      
      this.minimized = false;
      
      var dh = this.r2Height;
      this.r2Height = null;
      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, null, null, null, this.height + dh, {duration: Window.resizeEffectDuration});
      }
      else {
        var h  = this.element.getHeight() + dh;
        this.height += dh;
        this.element.setStyle({height: h + "px"})
        r2.show();
      }
      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom - dh) + 'px'});
      }
      this.toFront();
    }
    this._notify("onMinimize");
    
    // Store new location/size if need be
    this._saveCookie()
  },
  
  maximize: function() {
    if (this.isMinimized() || this.resizing)
      return;
  
    if (Prototype.Browser.IE && this.heightN == 0)
      this._getWindowBorderSize();
      
    if (this.storedLocation) {
      this._restoreLocation();
      if(this.iefix) 
        this.iefix.hide();
    }
    else {
      this._storeLocation();
      Windows.unsetOverflow(this);
      
      var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);
      var pageSize = WindowUtilities.getPageSize(this.options.parent);    
      var left = windowScroll.left;
      var top = windowScroll.top;
      
      if (this.options.parent != document.body) {
        windowScroll =  {top:0, left:0, bottom:0, right:0};
        var dim = this.options.parent.getDimensions();
        pageSize.windowWidth = dim.width;
        pageSize.windowHeight = dim.height;
        top = 0; 
        left = 0;
      }
      
      if (this.constraint) {
        pageSize.windowWidth -= Math.max(0, this.constraintPad.left) + Math.max(0, this.constraintPad.right);
        pageSize.windowHeight -= Math.max(0, this.constraintPad.top) + Math.max(0, this.constraintPad.bottom);
        left +=  Math.max(0, this.constraintPad.left);
        top +=  Math.max(0, this.constraintPad.top);
      }
      
      var width = pageSize.windowWidth - this.widthW - this.widthE;
      var height= pageSize.windowHeight - this.heightN - this.heightS;

      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
        new Effect.ResizeWindow(this, top, left, width, height, {duration: Window.resizeEffectDuration});
      }
      else {
        this.setSize(width, height);
        this.element.setStyle(this.useLeft ? {left: left} : {right: left});
        this.element.setStyle(this.useTop ? {top: top} : {bottom: top});
      }
        
      this.toFront();
      if (this.iefix) 
        this._fixIEOverlapping(); 
    }
    this._notify("onMaximize");

    // Store new location/size if need be
    this._saveCookie()
  },
  
  isMinimized: function() {
    return this.minimized;
  },
  
  isMaximized: function() {
    return (this.storedLocation);
  },
  
  setOpacity: function(opacity) {
    if (Element.setOpacity)
      Element.setOpacity(this.element, opacity);
  },
  
  setZIndex: function(zindex) {
    this.element.setStyle({zIndex: zindex});
    Windows.updateZindex(zindex, this);
  },

  setTitle: function(newTitle) {
    if (!newTitle || newTitle == "") 
      newTitle = "&nbsp;";
      
    Element.update(this.element.id + '_top', newTitle);
  },
   
  getTitle: function() {
    return $(this.element.id + '_top').innerHTML;
  },
  
  setStatusBar: function(element) {
    var statusBar = $(this.getId() + "_bottom");

    if (typeof(element) == "object") {
      if (this.bottombar.firstChild)
        this.bottombar.replaceChild(element, this.bottombar.firstChild);
      else
        this.bottombar.appendChild(element);
    }
    else
      this.bottombar.innerHTML = element;
  },

  _checkIEOverlapping: function() {
    if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (navigator.userAgent.indexOf('Opera')<0) && (this.element.getStyle('position')=='absolute')) {
        new Insertion.After(this.element.id, '<iframe id="' + this.element.id + '_iefix" '+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
        this.iefix = $(this.element.id+'_iefix');
    }
    if(this.iefix) 
      setTimeout(this._fixIEOverlapping.bind(this), 50);
  },

  _fixIEOverlapping: function() {
      Position.clone(this.element, this.iefix);
      this.iefix.style.zIndex = this.element.style.zIndex - 1;
      this.iefix.show();
  },
  
  _getWindowBorderSize: function(event) {
    // Hack to get real window border size!!
    var div = this._createHiddenDiv(this.options.className + "_n")
    this.heightN = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_s")
    this.heightS = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_e")
    this.widthE = Element.getDimensions(div).width;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_w")
    this.widthW = Element.getDimensions(div).width;
    div.parentNode.removeChild(div);
    
    var div = document.createElement("div");
    div.className = "overlay_" + this.options.className ;
    document.body.appendChild(div);
    //alert("no timeout:\nopacity: " + div.getStyle("opacity") + "\nwidth: " + document.defaultView.getComputedStyle(div, null).width);
    var that = this;
    
    // Workaround for Safari!!
    setTimeout(function() {that.overlayOpacity = ($(div).getStyle("opacity")); div.parentNode.removeChild(div);}, 10);
    
    // Workaround for IE!!
    if (Prototype.Browser.IE) {
      this.heightS = $(this.getId() +"_row3").getDimensions().height;
      this.heightN = $(this.getId() +"_row1").getDimensions().height;
    }

    // Safari size fix
    if (Prototype.Browser.WebKit && Prototype.Browser.WebKitVersion < 420)
      this.setSize(this.width, this.height);
    if (this.doMaximize)
      this.maximize();
    if (this.doMinimize)
      this.minimize();
  },
 
  _createHiddenDiv: function(className) {
    var objBody = document.body;
    var win = document.createElement("div");
    win.setAttribute('id', this.element.id+ "_tmp");
    win.className = className;
    win.style.display = 'none';
    win.innerHTML = '';
    objBody.insertBefore(win, objBody.firstChild);
    return win;
  },
  
  _storeLocation: function() {
    if (!this.storedLocation) {
      this.storedLocation = {useTop: this.useTop, useLeft: this.useLeft, 
                             top: this.element.getStyle('top'), bottom: this.element.getStyle('bottom'),
                             left: this.element.getStyle('left'), right: this.element.getStyle('right'),
                             width: this.width, height: this.height };
    }
  },
  
  _restoreLocation: function() {
    if (this.storedLocation) {
      this.useLeft = this.storedLocation.useLeft;
      this.useTop = this.storedLocation.useTop;
      
      if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow)
        new Effect.ResizeWindow(this, this.storedLocation.top, this.storedLocation.left, this.storedLocation.width, this.storedLocation.height, {duration: Window.resizeEffectDuration});
      else {
        this.element.setStyle(this.useLeft ? {left: this.storedLocation.left} : {right: this.storedLocation.right});
        this.element.setStyle(this.useTop ? {top: this.storedLocation.top} : {bottom: this.storedLocation.bottom});
        this.setSize(this.storedLocation.width, this.storedLocation.height);
      }
      
      Windows.resetOverflow();
      this._removeStoreLocation();
    }
  },
  
  _removeStoreLocation: function() {
    this.storedLocation = null;
  },
  
  _saveCookie: function() {
    if (this.cookie) {
      var value = "";
      if (this.useLeft)
        value += "l:" +  (this.storedLocation ? this.storedLocation.left : this.element.getStyle('left'))
      else
        value += "r:" + (this.storedLocation ? this.storedLocation.right : this.element.getStyle('right'))
      if (this.useTop)
        value += ",t:" + (this.storedLocation ? this.storedLocation.top : this.element.getStyle('top'))
      else
        value += ",b:" + (this.storedLocation ? this.storedLocation.bottom :this.element.getStyle('bottom'))
        
      value += "," + (this.storedLocation ? this.storedLocation.width : this.width);
      value += "," + (this.storedLocation ? this.storedLocation.height : this.height);
      value += "," + this.isMinimized();
      value += "," + this.isMaximized();
      WindowUtilities.setCookie(value, this.cookie)
    }
  },
  
  _createWiredElement: function() {
    if (! this.wiredElement) {
      if (Prototype.Browser.IE)
        this._getWindowBorderSize();
      var div = document.createElement("div");
      div.className = "wired_frame " + this.options.className + "_wired_frame";
      
      div.style.position = 'absolute';
      this.options.parent.insertBefore(div, this.options.parent.firstChild);
      this.wiredElement = $(div);
    }
    if (this.useLeft) 
      this.wiredElement.setStyle({left: this.element.getStyle('left')});
    else 
      this.wiredElement.setStyle({right: this.element.getStyle('right')});
      
    if (this.useTop) 
      this.wiredElement.setStyle({top: this.element.getStyle('top')});
    else 
      this.wiredElement.setStyle({bottom: this.element.getStyle('bottom')});

    var dim = this.element.getDimensions();
    this.wiredElement.setStyle({width: dim.width + "px", height: dim.height +"px"});

    this.wiredElement.setStyle({zIndex: Windows.maxZIndex+30});
    return this.wiredElement;
  },
  
  _hideWiredElement: function() {
    if (! this.wiredElement || ! this.currentDrag)
      return;
    if (this.currentDrag == this.element) 
      this.currentDrag = null;
    else {
      if (this.useLeft) 
        this.element.setStyle({left: this.currentDrag.getStyle('left')});
      else 
        this.element.setStyle({right: this.currentDrag.getStyle('right')});

      if (this.useTop) 
        this.element.setStyle({top: this.currentDrag.getStyle('top')});
      else 
        this.element.setStyle({bottom: this.currentDrag.getStyle('bottom')});

      this.currentDrag.hide();
      this.currentDrag = null;
      if (this.doResize)
        this.setSize(this.width, this.height);
    } 
  },
  
  _notify: function(eventName) {
    if (this.options[eventName])
      this.options[eventName](this);
    else
      Windows.notify(eventName, this);
  }
};

// Windows containers, register all page windows
var Windows = {
  windows: [],
  modalWindows: [],
  observers: [],
  focusedWindow: null,
  maxZIndex: 0,
  overlayShowEffectOptions: {duration: 0.5},
  overlayHideEffectOptions: {duration: 0.5},

  addObserver: function(observer) {
    this.removeObserver(observer);
    this.observers.push(observer);
  },
  
  removeObserver: function(observer) {  
    this.observers = this.observers.reject( function(o) { return o==observer });
  },
  
  // onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose
  notify: function(eventName, win) {  
    this.observers.each( function(o) {if(o[eventName]) o[eventName](eventName, win);});
  },

  // Gets window from its id
  getWindow: function(id) {
    return this.windows.detect(function(d) { return d.getId() ==id });
  },

  // Gets the last focused window
  getFocusedWindow: function() {
    return this.focusedWindow;
  },

  updateFocusedWindow: function() {
    this.focusedWindow = this.windows.length >=2 ? this.windows[this.windows.length-2] : null;    
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
    
  // Add a modal window in the stack
  addModalWindow: function(win) {
    // Disable screen if first modal window
    if (this.modalWindows.length == 0) {
      WindowUtilities.disableScreen(win.options.className, 'overlay_modal', win.overlayOpacity, win.getId(), win.options.parent);
    }
    else {
      // Move overlay over all windows
      if (Window.keepMultiModalWindow) {
        $('overlay_modal').style.zIndex = Windows.maxZIndex + 1;
        Windows.maxZIndex += 1;
        WindowUtilities._hideSelect(this.modalWindows.last().getId());
      }
      // Hide current modal window
      else
        this.modalWindows.last().element.hide();
      // Fucking IE select issue
      WindowUtilities._showSelect(win.getId());
    }      
    this.modalWindows.push(win);    
  },
  
  removeModalWindow: function(win) {
    this.modalWindows.pop();
    
    // No more modal windows
    if (this.modalWindows.length == 0)
      WindowUtilities.enableScreen();     
    else {
      if (Window.keepMultiModalWindow) {
        this.modalWindows.last().toFront();
        WindowUtilities._showSelect(this.modalWindows.last().getId());        
      }
      else
        this.modalWindows.last().element.show();
    }
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
  
  // Unregisters a window (called by Windows destructor)
  unregister: function(win) {
    this.windows = this.windows.reject(function(d) { return d==win });
  }, 
  
  // Closes all windows
  closeAll: function() {  
    this.windows.each( function(w) {Windows.close(w.getId())} );
  },
  
  closeAllModalWindows: function() {
    WindowUtilities.enableScreen();     
    this.modalWindows.each( function(win) {if (win) win.close()});    
  },

  // Minimizes a window with its id
  minimize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.minimize();
    Event.stop(event);
  },
  
  // Maximizes a window with its id
  maximize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.maximize();
    Event.stop(event);
  },

  // Closes a window with its id
  close: function(id, event) {
    var win = this.getWindow(id);
    if (win) 
      win.close();
    if (event)
      Event.stop(event);
  },
  
  blur: function(id) {
    var win = this.getWindow(id);  
    if (!win)
      return;
    if (win.options.blurClassName)
      win.changeClassName(win.options.blurClassName);
    if (this.focusedWindow == win)  
      this.focusedWindow = null;
    win._notify("onBlur");  
  },
  
  focus: function(id) {
    var win = this.getWindow(id);  
    if (!win)
      return;       
    if (this.focusedWindow)
      this.blur(this.focusedWindow.getId())

    if (win.options.focusClassName)
      win.changeClassName(win.options.focusClassName);  
    this.focusedWindow = win;
    win._notify("onFocus");
  },
  
  unsetOverflow: function(except) {    
    this.windows.each(function(d) { d.oldOverflow = d.getContent().getStyle("overflow") || "auto" ; d.getContent().setStyle({overflow: "hidden"}) });
    if (except && except.oldOverflow)
      except.getContent().setStyle({overflow: except.oldOverflow});
  },

  resetOverflow: function() {
    this.windows.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({overflow: d.oldOverflow}) });
  },

  updateZindex: function(zindex, win) { 
    if (zindex > this.maxZIndex) {   
      this.maxZIndex = zindex;    
      if (this.focusedWindow) 
        this.blur(this.focusedWindow.getId())
    }
    this.focusedWindow = win;
    if (this.focusedWindow) 
      this.focus(this.focusedWindow.getId())
  }
};

var Dialog = {
  dialogId: null,
  onCompleteFunc: null,
  callFunc: null, 
  parameters: null, 
    
  confirm: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.confirm);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";
    var cancelLabel = parameters.cancelLabel ? parameters.cancelLabel : "Cancel";

    // Backward compatibility
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};

    parameters.className = parameters.className || "alert";

    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
          <input type='button' value='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "/>\
        </div>\
    ";
    return this._openDialog(content, parameters)
  },

  alert: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.alert);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";

    // Backward compatibility    
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
        </div>";                  
    return this._openDialog(content, parameters)
  },
  
  info: function(content, parameters) {   
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.info);
      return 
    }
    content = content || "";
     
    // Backward compatibility
    parameters = parameters || {};
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var content = "<div id='modal_dialog_message' class='" + parameters.className + "_message'>" + content  + "</div>";
    if (parameters.showProgress)
      content += "<div id='modal_dialog_progress' class='" + parameters.className + "_progress'>  </div>";

    parameters.ok = null;
    parameters.cancel = null;
    
    return this._openDialog(content, parameters)
  },
  
  setInfoMessage: function(message) {
    $('modal_dialog_message').update(message);
  },
  
  closeInfo: function() {
    Windows.close(this.dialogId);
  },
  
  _openDialog: function(content, parameters) {
    var className = parameters.className;
    
    if (! parameters.height && ! parameters.width) {
      parameters.width = WindowUtilities.getPageSize(parameters.options.parent || document.body).pageWidth / 2;
    }
    if (parameters.id)
      this.dialogId = parameters.id;
    else { 
      var t = new Date();
      this.dialogId = 'modal_dialog_' + t.getTime();
      parameters.id = this.dialogId;
    }

    // compute height or width if need be
    if (! parameters.height || ! parameters.width) {
      var size = WindowUtilities._computeSize(content, this.dialogId, parameters.width, parameters.height, 5, className)
      if (parameters.height)
        parameters.width = size + 5
      else
        parameters.height = size + 5
    }
    parameters.effectOptions = parameters.effectOptions ;
    parameters.resizable   = parameters.resizable || false;
    parameters.minimizable = parameters.minimizable || false;
    parameters.maximizable = parameters.maximizable ||  false;
    parameters.draggable   = parameters.draggable || false;
    parameters.closable    = parameters.closable || false;
    
    var win = new Window(parameters);
    win.getContent().innerHTML = content;
    
    win.showCenter(true, parameters.top, parameters.left);  
    win.setDestroyOnClose();
    
    win.cancelCallback = parameters.onCancel || parameters.cancel; 
    win.okCallback = parameters.onOk || parameters.ok;
    
    return win;    
  },
  
  _getAjaxContent: function(originalRequest)  {
      Dialog.callFunc(originalRequest.responseText, Dialog.parameters)
  },
  
  _runAjaxRequest: function(message, parameters, callFunc) {
    if (!message.options)
      message.options = {}  
    Dialog.onCompleteFunc = message.options.onComplete;
    Dialog.parameters = parameters;
    Dialog.callFunc = callFunc;
    
    message.options.onComplete = Dialog._getAjaxContent;
    new Ajax.Request(message.url, message.options);
  },
  
  okCallback: function() {
    var win = Windows.focusedWindow;
    if (!win.okCallback || win.okCallback(win)) {
      // Remove onclick on button
      $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;})
      win.close();
    }
  },

  cancelCallback: function() {
    var win = Windows.focusedWindow;
    // Remove onclick on button
    $$("#" + win.getId()+" input").each(function(element) {element.onclick=null})
    win.close();
    if (win.cancelCallback)
      win.cancelCallback(win);
  }
}
/*
  Based on Lightbox JS: Fullsize Image Overlays 
  by Lokesh Dhakar - http://www.huddletogether.com

  For more information on this script, visit:
  http://huddletogether.com/projects/lightbox/

  Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
  (basically, do anything you want, just leave my name and link)
*/

if (Prototype.Browser.WebKit) {
  var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));
  Prototype.Browser.WebKitVersion = parseFloat(array[1]);
}

var WindowUtilities = {  
  // From dragdrop.js
  getWindowScroll: function(parent) {
    var T, L, W, H;
    parent = parent || document.body;              
    if (parent != document.body) {
      T = parent.scrollTop;
      L = parent.scrollLeft;
      W = parent.scrollWidth;
      H = parent.scrollHeight;
    } 
    else {
      var w = window;
      with (w.document) {
        if (w.document.documentElement && documentElement.scrollTop) {
          T = documentElement.scrollTop;
          L = documentElement.scrollLeft;
        } else if (w.document.body) {
          T = body.scrollTop;
          L = body.scrollLeft;
        }
        if (w.innerWidth) {
          W = w.innerWidth;
          H = w.innerHeight;
        } else if (w.document.documentElement && documentElement.clientWidth) {
          W = documentElement.clientWidth;
          H = documentElement.clientHeight;
        } else {
          W = body.offsetWidth;
          H = body.offsetHeight
        }
      }
    }
    return { top: T, left: L, width: W, height: H };
  }, 
  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(parent){
    parent = parent || document.body;              
    var windowWidth, windowHeight;
    var pageHeight, pageWidth;
    if (parent != document.body) {
      windowWidth = parent.getWidth();
      windowHeight = parent.getHeight();                                
      pageWidth = parent.scrollWidth;
      pageHeight = parent.scrollHeight;                                
    } 
    else {
      var xScroll, yScroll;

      if (window.innerHeight && window.scrollMaxY) {  
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }


      if (self.innerHeight) {  // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }  

      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else { 
        pageHeight = yScroll;
      }

      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){  
        pageWidth = windowWidth;
      } else {
        pageWidth = xScroll;
      }
    }             
    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },

  disableScreen: function(className, overlayId, overlayOpacity, contentId, parent) {
    WindowUtilities.initLightbox(overlayId, className, function() {this._disableScreen(className, overlayId, overlayOpacity, contentId)}.bind(this), parent || document.body);
  },

  _disableScreen: function(className, overlayId, overlayOpacity, contentId) {
    // prep objects
    var objOverlay = $(overlayId);

    var pageSize = WindowUtilities.getPageSize(objOverlay.parentNode);

    // Hide select boxes as they will 'peek' through the image in IE, store old value
    if (contentId && Prototype.Browser.IE) {
      WindowUtilities._hideSelect();
      WindowUtilities._showSelect(contentId);
    }  
  
    // set height of Overlay to take up whole page and show
    objOverlay.style.height = (pageSize.pageHeight + 'px');
    objOverlay.style.display = 'none'; 
    if (overlayId == "overlay_modal" && Window.hasEffectLib && Windows.overlayShowEffectOptions) {
      objOverlay.overlayOpacity = overlayOpacity;
      new Effect.Appear(objOverlay, Object.extend({from: 0, to: overlayOpacity}, Windows.overlayShowEffectOptions));
    }
    else
      objOverlay.style.display = "block";
  },
  
  enableScreen: function(id) {
    id = id || 'overlay_modal';
    var objOverlay =  $(id);
    if (objOverlay) {
      // hide lightbox and overlay
      if (id == "overlay_modal" && Window.hasEffectLib && Windows.overlayHideEffectOptions)
        new Effect.Fade(objOverlay, Object.extend({from: objOverlay.overlayOpacity, to:0}, Windows.overlayHideEffectOptions));
      else {
        objOverlay.style.display = 'none';
        objOverlay.parentNode.removeChild(objOverlay);
      }
      
      // make select boxes visible using old value
      if (id != "__invisible__") 
        WindowUtilities._showSelect();
    }
  },

  _hideSelect: function(id) {
    if (Prototype.Browser.IE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (! WindowUtilities.isDefined(element.oldVisibility)) {
          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
          element.style.visibility = "hidden";
        }
      });
    }
  },
  
  _showSelect: function(id) {
    if (Prototype.Browser.IE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (WindowUtilities.isDefined(element.oldVisibility)) {
          // Why?? Ask IE
          try {
            element.style.visibility = element.oldVisibility;
          } catch(e) {
            element.style.visibility = "visible";
          }
          element.oldVisibility = null;
        }
        else {
          if (element.style.visibility)
            element.style.visibility = "visible";
        }
      });
    }
  },

  isDefined: function(object) {
    return typeof(object) != "undefined" && object;
  },
  
  // initLightbox()
  // Function runs on window load, going through link tags looking for rel="lightbox".
  // These links receive onclick events that enable the lightbox display for their targets.
  // The function also inserts html markup at the top of the page which will be used as a
  // container for the overlay pattern and the inline image.
  initLightbox: function(id, className, doneHandler, parent) {
    // Already done, just update zIndex
    if ($(id)) {
      Element.setStyle(id, {zIndex: Windows.maxZIndex + 1});
      Windows.maxZIndex++;
      doneHandler();
    }
    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    else {
      var objOverlay = document.createElement("div");
      objOverlay.setAttribute('id', id);
      objOverlay.className = "overlay_" + className
      objOverlay.style.display = 'none';
      objOverlay.style.position = 'absolute';
      objOverlay.style.top = '0';
      objOverlay.style.left = '0';
      objOverlay.style.zIndex = Windows.maxZIndex + 1;
      Windows.maxZIndex++;
      objOverlay.style.width = '100%';
      parent.insertBefore(objOverlay, parent.firstChild);
      if (Prototype.Browser.WebKit && id == "overlay_modal") {
        setTimeout(function() {doneHandler()}, 10);
      }
      else
        doneHandler();
    }    
  },
  
  setCookie: function(value, parameters) {
    document.cookie= parameters[0] + "=" + escape(value) +
      ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") +
      ((parameters[2]) ? "; path=" + parameters[2] : "") +
      ((parameters[3]) ? "; domain=" + parameters[3] : "") +
      ((parameters[4]) ? "; secure" : "");
  },

  getCookie: function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else {
      begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
      end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
  },
    
  _computeSize: function(content, id, width, height, margin, className) {
    var objBody = document.body;
    var tmpObj = document.createElement("div");
    tmpObj.setAttribute('id', id);
    tmpObj.className = className + "_content";

    if (height)
      tmpObj.style.height = height + "px"
    else
      tmpObj.style.width = width + "px"
  
    tmpObj.style.position = 'absolute';
    tmpObj.style.top = '0';
    tmpObj.style.left = '0';
    tmpObj.style.display = 'none';

    tmpObj.innerHTML = content;
    objBody.insertBefore(tmpObj, objBody.firstChild);

    var size;
    if (height)
      size = $(tmpObj).getDimensions().width + margin;
    else
      size = $(tmpObj).getDimensions().height + margin;
    objBody.removeChild(tmpObj);
    return size;
  }  
}

/**
 * Growler scripts
 */

var noticeOptions = {
	header: 			'&nbsp;'
	,speedin: 			0.3
	,speedout: 			0.5
	,outDirection: 		{ y: -20 }
	,life: 				5
	,sticky: 			false
	,className: 		""
};
var growlerOptions = {
	location: 			"tr"
	,width: 			"250px"
};
var IE = (Prototype.Browser.IE) ? parseFloat(navigator.appVersion.split("MSIE ")[1]) || 0 : 0;
function removeNotice(n, o){
	o = o || noticeOptions;
	new Effect.Parallel([
		new Effect.Move(n, Object.extend({ sync: true, mode: 'relative' }, o.outDirection)),
		new Effect.Opacity(n, { sync: true, to: 0 }) 
	], {
		duration: o.speedout
		,afterFinish: function(){
			try {
				var ne = n.down("div.notice-exit");
				if(ne != undefined){
					ne.stopObserving("click", removeNotice);
				}
				if(o.created && Object.isFunction(o.created)){
					n.stopObserving("notice:created", o.created);
				}
				if(o.destroyed && Object.isFunction(o.destroyed)){
					n.fire("notice:destroyed");
					n.stopObserving("notice:destroyed", o.destroyed);
				}
			} catch(e){}
			try {
				n.remove();
			} catch(e){}
		}
	});
}
function createNotice(growler, msg, options){
	var opt = Object.clone(noticeOptions);
	options = options || {};
	Object.extend(opt, options);
	var notice;
	if (opt.className != ""){
		notice = new Element("div", {"class": opt.className}).setStyle({display: "block", opacity: 0});
	} else {
		notice = new Element("div", {"class": "Growler-notice"}).setStyle({display: "block", opacity: 0});
	}
	if(opt.created && Object.isFunction(opt.created)){
		notice.observe("notice:created", opt.created);
	}
	if(opt.destroyed && Object.isFunction(opt.destroyed)){
		notice.observe("notice:destroyed", opt.destroyed);
	}
	if (opt.sticky){
		var noticeExit = new Element("div", {"class": "Growler-notice-exit"}).update("&times;");
		noticeExit.observe("click", function(){ removeNotice(notice, opt); });
		notice.insert(noticeExit);
	}
	notice.insert(new Element("div", {"class": "Growler-notice-head"}).update(opt.header));
	notice.insert(new Element("div", {"class": "Growler-notice-body"}).update(msg));
	growler.insert(notice);
	new Effect.Opacity(notice, { to: 0.85, duration: opt.speedin });
	if (!opt.sticky){
		removeNotice.delay(opt.life, notice, opt);
	}
	notice.fire("notice:created");
	return notice;
}
function specialNotice(g, m, o, t, b, c){
	o.header = o.header || t;
	var n = createNotice(g, m, o);
	n.setStyle({ backgroundColor: b, color: c });
	return n;
}
var Growler = Class.create({
	initialize: function(options){
		var opt = Object.clone(growlerOptions);
		options = options || {};
		Object.extend(opt, options);
		this.growler = new Element("div", { "class": "Growler", "id": "Growler" });
		this.growler.setStyle({ position: ((IE==6)?"absolute":"fixed"), padding: "10px", "width": opt.width, "z-index": "50000" });
		if(IE==6){
			var offset = { w: parseInt(this.growler.style.width)+parseInt(this.growler.style.padding)*3, h: parseInt(this.growler.style.height)+parseInt(this.growler.style.padding)*3 };
			switch(opt.location){
				case "br":
					this.growler.style.setExpression("left", "( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
				  	this.growler.style.setExpression("top", "( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
					break;
				case "tl":
					this.growler.style.setExpression("left", "( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
				  	this.growler.style.setExpression("top", "( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
					break;
				case "bl":
					this.growler.style.setExpression("left", "( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
				  	this.growler.style.setExpression("top", "( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
					break;
				default:
					this.growler.setStyle({right: "auto", bottom: "auto"});
					this.growler.style.setExpression("left", "( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
				  	this.growler.style.setExpression("top", "( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
					break;
			}
		} else {
			switch(opt.location){
				case "br":
					this.growler.setStyle({bottom: 0, right: 0});
					break;
				case "tl":
					this.growler.setStyle({top: 0, left: 0});
					break;
				case "bl":
					this.growler.setStyle({top: 0, right: 0});
					break;
				case "tc":
					this.growler.setStyle({top: 0, left: "25%", width: "50%"});
					break;
				case "bc":
					this.growler.setStyle({bottom: 0, left: "25%", width: "50%"});
					break;
				default:
					this.growler.setStyle({top: 0, right: 0});
					break;
			}
		}
		this.growler.wrap( document.body );		
	}
	,growl: function(msg, options) {
		return createNotice(this.growler, msg, options);
	}
	,warn: function(msg, options){
		return specialNotice(this.growler, msg, options, "Warning!", "#F6BD6F", "#000");
	}
	,error: function(msg, options){
		return specialNotice(this.growler, msg, options, "Critical!", "#F66F82", "#000");
	}
	,info: function(msg, options){
		return specialNotice(this.growler, msg, options, "Information!", "#BBF66F", "#000");
	}
	,ungrowl: function(n, o){
		removeNotice(n, o);
	}
});


/**
 * General scripts
 */
var Likexo = {};

Likexo.Ajax = Class.create({
	
	onCompleteFunction: null,
	
	initialize: function(message) {
	    this._checkRequestStatus = this._checkRequestStatus.bind(this);
	
	    this.onCompleteFunction = message.options.onComplete;
	    message.options.onComplete = this._checkRequestStatus
	    message.options.onException = this._handleError
	    if(!message.options.parameters) {
	    	message.options.parameters = {actualUrl: $F('actualUrl')};
	    } else {
	    	message.options.parameters.actualUrl = $F('actualUrl');
	    }
	    
	    new Ajax.Request(message.url, message.options);
    },
    
    _checkRequestStatus: function(originalRequest) {
	    if(200 == originalRequest.status) {
	    	if ((originalRequest.getResponseHeader('LOGIN_PAGE') || '').match(/true/)) {
	    		window.location.href = $F('ajaxErrorPage');
	    	} else if(this.onCompleteFunction) {
	    		this.onCompleteFunction(originalRequest);
	    		return;
	    	}
	    } else {
	    	if(originalRequest.status != 0) {
	    		this._handleError(originalRequest);
	    	}
	    }
	},
	
	_handleError: function(originalRequest) {
        var g = new Growler({location:"br"});
        g.growl($F('ajaxErrorMsg'), {life:10, header: $F('ajaxErrorTitle')});
	}
});

/**
 * Captcha functions
 */
function nextCaptcha(rootPath) {
    var now = new Date();
    var newSrc = rootPath + 'captcha.jpg?' + now.getTime();
    if (document.images) {
        document.images.captcha.src = newSrc;
    }

}

/**
 * Category scripts
 */
function addRemoveListedItem(itemId, addUrl, removeUrl) {
    //$$("#item" + itemId + " div.item").first().addClassName("modificando");
    ModifyUtils.showModifyingOverlay($$("#item" + itemId + " div.item").first());
    
    var message;
    if($("addRemoveButton" + itemId).hasClassName("agregar")) {
        message = {
            url: addUrl,
            options: {
                method: 'post',
                parameters: {itemId: itemId, itemCounter: $('itemCounter' + itemId).innerHTML},
                asynchronous: true,
                onComplete: function(response) {updateItem(response,$(itemId));}
            }
        };
    } else {
        message = {
            url: removeUrl,
            options: {
                method: 'post',
                parameters: {itemId: itemId, itemCounter: $('itemCounter' + itemId).innerHTML},
                asynchronous: true,
                onComplete: function(response) {updateItem(response,$(itemId));}
            }
        };
    }
    
    new Likexo.Ajax(message);
}

function updateItem(originalRequest, itemId) {
    if (originalRequest.responseText.isJSON()) {
        var data = originalRequest.responseText.evalJSON();
        if(data.error) {
            // error
        }
    } else {
        $("item" + itemId).update(originalRequest.responseText);
    }
}

/**
 * Image preloading scripts
 */
var ImagePreloader = Class.create();
ImagePreloader.prototype = {
  initialize: function(images, callBack) {

   // store the callBack
   this.callBack = callBack;

   // initialize internal state.
   this.nLoaded = 0;
   this.nProcessed = 0;
   this.aImages = new Array;

   // record the number of images.
   this.nImages = images.length;

   // for each image, call preload()
   for ( var i = 0; i < images.length; i++ )
      this.preload(images[i]);
  },
  

  preload: function(image) {

   // create new Image object and add to array
   var oImage = new Image;
   this.aImages.push(oImage);

   // set up event handlers for the Image object
   oImage.onload = ImagePreloader.prototype.onload;
   oImage.onerror = ImagePreloader.prototype.onerror;
   oImage.onabort = ImagePreloader.prototype.onabort;

   // assign pointer back to this.
   oImage.oImagePreloader = this;
   oImage.bLoaded = false;

   // assign the .src property of the Image object
   oImage.src = image;
  },

  onComplete: function() {

   this.nProcessed++;
   if ( this.nProcessed == this.nImages ) {
      if(this.callBack) {
        this.callBack(this.aImages, this.nLoaded);
      }
   }
  },

  onload: function(){
   this.bLoaded = true;
   this.oImagePreloader.nLoaded++;
   this.oImagePreloader.onComplete();
  },

  onerror: function(){
   this.bError = true;
   this.oImagePreloader.onComplete();
  },

  onabort: function() {
   this.bAbort = true;
   this.oImagePreloader.onComplete();
  }
}

/**
 * Input adder scripts
 */
var InputAdd = Class.create();
InputAdd.prototype = {

    initialize: function(beforeName, triggerName, options) {
        this.beforeElement = $(beforeName);
        this.triggerElement = $(triggerName);

        this.setOptions(options);

		this.insertManager = this.insertManager.bindAsEventListener(this);
		this.triggerElement.observe('click', this.insertManager);

    },

    insertManager: function(event) {

		if(!this.options.maxitems || this.options.maxitems>this.options.elementNumber) {

		    var newElement = Builder.node('input', { 'type': this.options.type, 'name': this.options.basename + '['+this.options.elementNumber+']' + this.options.parameter , 'id': this.options.id, 'class':this.options.clazz, 'size':this.options.size });
			this.options.elementNumber++;

			var newLabel = Builder.node('label');

			// add the element
			Element.insert(this.beforeElement, {before: newLabel});
			Element.insert(this.beforeElement, {before: newElement});
			Element.insert(this.beforeElement, {before: '<br/>'});
			Element.insert(this.beforeElement, {before: '<br clear=\'all\'/>'});
		}

    },


    setOptions: function(options) {
        this.options = Object.extend({
		    type: 'text',
			basename: 'name',
			parameter: '',
		    elementNumber: 0,
			id: '',
			size: '',
			maxitems: null,
			clazz: ''

	    }, options || {});
	}
}

/**
 * Items scripts
 */
function addRemoveItem(updateUrl, itemInfoUrl, itemExtraInfoAndBoxesUrl, itemLeftBoxesUrl) {
    ModifyUtils.showModifyingOverlay();

    var message = {
        url: updateUrl,
        options: {onComplete: function(originalRequest) {updateItemPage(originalRequest, itemInfoUrl, itemExtraInfoAndBoxesUrl, itemLeftBoxesUrl);}}
    };

    new Likexo.Ajax(message);
}

function reloadItemPageParts(itemInfoUrl, itemExtraInfoAndBoxesUrl, itemLeftBoxesUrl) {
	ModifyUtils.showModifyingOverlay();
	reloadItemInfo(itemInfoUrl, itemExtraInfoAndBoxesUrl);
	reloadLeftBoxes(itemLeftBoxesUrl);
}

function updateItemPage(originalRequest, itemInfoUrl, itemExtraInfoAndBoxesUrl, itemLeftBoxesUrl) {
	reloadItemInfo(itemInfoUrl, itemExtraInfoAndBoxesUrl);
	reloadLeftBoxes(itemLeftBoxesUrl);
}

function updateItemCompletedPercentage(updateUrl) {
	message = {url: updateUrl, options: {onComplete: refreshItemCompletedPercentage}};
    new Likexo.Ajax(message);
}

function refreshItemCompletedPercentage(originalRequest) {
	$$("div.fotoDesc span#value").first().update(originalRequest.responseText);
}

function reloadItemInfo(itemInfoUrl, itemExtraInfoAndBoxesUrl) {
    var itemInfoMessage = {url: itemInfoUrl,options: {onComplete: refreshItemInfo}};
    new Likexo.Ajax(itemInfoMessage);

    var itemExtraInfoAndBoxesMessage = {url: itemExtraInfoAndBoxesUrl,options: {onComplete: function(originalRequest) {
    	refreshItemExtraInfoAndBoxes(originalRequest);
    	showItemButtons();
    	updateItemsCounter();
    	if($("addRemoveButton").hasClassName("remover")) {
    		hideBtmas();
    	}
    	refreshToolsPosition.delay(1);
    	ModifyUtils.hideModifyingOverlay();
    }}};
    new Likexo.Ajax(itemExtraInfoAndBoxesMessage);
}

function reloadLeftBoxes(itemLeftBoxesUrl) {
    var leftBoxesMessage = {url: itemLeftBoxesUrl, options: {onComplete: refreshItemLeftBoxes}};
    new Likexo.Ajax(leftBoxesMessage);
}

function refreshItemLeftBoxes(originalRequest) {
	$("item-left-boxes").update(originalRequest.responseText);
}

function refreshItemInfo(originalRequest) {
    $("box_prf_public").update(originalRequest.responseText);
}

function showItemButtons() {
	buildItemRollover();
	buildBtmasMouseOverMsg();
}

function updateItemsCounter() {
	var numberOfItems = new Number($("numberOfItems").innerHTML);
	if($("addRemoveButton").hasClassName("agregar")) {
		if(numberOfItems &&  numberOfItems > 0) {
			$("numberOfItems").update(numberOfItems - 1);
		}
	} else {
		$("numberOfItems").update(numberOfItems + 1);
	}
}

function refreshItemExtraInfoAndBoxes(originalRequest) {
	$("item-extra-info-and-boxes").update(originalRequest.responseText);
}

function reloadItemComment(itemId, containerName, commentListReloadUrl) {
	var message = { 
		url: commentListReloadUrl + '?itemId=' + itemId, 
		options: {
			method: 'get',
			onComplete: function(originalRequest){ 
		        refreshContent(originalRequest, containerName);
		    }
		}
	}; 
	new Likexo.Ajax(message);
}

function reloadPage(url) {
    window.location.href = url; 
}

function reloadTagCloud() {
	itemId = $F('itemId');
	containerName = $F('containerNameIT');
	var message = { 
		url: $F('tagCloudReloadUrl') + '?itemId=' + itemId, 
		options: {
			method: 'get',
			onComplete: function(originalRequest){ 
		        refreshContent(originalRequest, containerName);
		    }
		}
	}; 
	new Likexo.Ajax(message);
}

function updateFieldValue(fieldName, newValue) {
    $(fieldName).update(newValue);
    refreshToolsPosition.delay(1);
}

function makePendingField(fieldName, triggerDescName, triggeDescValue) {
    $(fieldName).addClassName("pendiente");
    $(triggerDescName).toggleClassName("normal", "large");
    $(triggerDescName).select('[class="palabra"]').first().update(triggeDescValue);
    refreshToolsPosition.delay(1);
}

function removeItemField(listName, containerName, emptyListMsg, lightboxScriptId) {
  $(listName).removeChild($(containerName));
  if($(listName).empty()) {
	$(listName).hide();
    $(listName).parentNode.insert(emptyListMsg);
  }
  if($(lightboxScriptId)) {
	  $(lightboxScriptId).remove();
  }
  refreshToolsPosition.delay(1);
}

function addItemField(listName, containerName, content, emptyListMsgId) {
  var element = new Element("li", {id:containerName}).update(content);
  if($(listName).empty()) {
	$(listName).show();
    $(emptyListMsgId).remove();
  }
  $(listName).insert(element);
}

function sortBaseList(listName) {
  var sortedElements = $(listName).childElements().sortBy(function(e){return e.select('span.fieldvalue').first().innerHTML;});
  if(sortedElements && sortedElements.length >= 1) {
	  var list = $(listName).update();
	  sortedElements.each(function(e){list.insert(e);});
  }
}

function sortItemRelarionList(listName) {
  var sortedElements = $(listName).childElements().sortBy(function(e){return e.select('span.fieldvalue a').first().innerHTML;});
  if(sortedElements && sortedElements.length >= 1) {
	  var list = $(listName).update();
	  sortedElements.each(function(e){list.insert(e);});
  }
}

function bringOnAddElementScript(url, containerName) {
    var message = {
       url: url,
       options: {method: 'get', onComplete:function(originalRequest){
           $(containerName).insert(originalRequest.responseText);
       }}
   };
    new Likexo.Ajax(message);
}

function makeHiddenTextbox(textBoxId, hiddenMsgId, triggerId, searchFlagId) {
  $(textBoxId).hide();
  Event.observe($(triggerId), "click", function(e) {showTextBox(textBoxId, hiddenMsgId, triggerId, searchFlagId);});
}

function showTextBox(textBoxId, hiddenMsgId, triggerId, searchFlagId) {
  $(textBoxId).show();
  $(hiddenMsgId).hide();
  $(triggerId).hide();
  $(searchFlagId).setAttribute("value", "true");
}

function refreshRoleList(prefix, typeField, formId, castEditUrl, baseEditUrl) {
	var containerId = prefix + "RoleCheckboxList";
	var containerLabelId = prefix + "RoleCheckboxListLabel";
	var castTextboxId = prefix + "CastTextbox";
	var castLabelId = prefix + "CastLabel";
	
	if($("hidden-role")) {
		$("hidden-role").remove();
	}
	
	var list = roleCheckboxListHash.get($(typeField).value);
	if(list) {
		if(($(typeField).value == 'Movie Cast Member')) {
			$(containerId).hide();
			$(containerLabelId).hide();
			$(castTextboxId).show();
			$(castLabelId).show();
			//$(formId).writeAttribute('action', castEditUrl);
		} else {
			//$(formId).action = baseEditUrl;
			$(castTextboxId).hide();
			$(castLabelId).hide();
			if(list.size() >= 1) {
				if(list.size() > 1) {
				  $(containerId).show();
				  $(containerLabelId).show();
				} else {
					$(containerId).hide();
					$(containerLabelId).hide();
				}
				list.print(containerId);
			} else {
				$(containerId).hide();
				$(containerLabelId).hide();
			}
		}
	} else {
		$(formId).action = baseEditUrl;
		$(containerId).hide();
		$(containerLabelId).hide();
		$(castTextboxId).hide();
		$(castLabelId).hide();
	}
}

var toolTipsPositions = new Hash();
function refreshToolsPosition() {
  $$("div.itemTooltip").each(function(toolTip){
	  var toolTipTrigger = $(toolTip.id.substring(0, toolTip.id.indexOf("Desc")));
	  if(toolTipTrigger) {
		  var offsets = Element.cumulativeOffset(toolTipTrigger);
		  var positions = toolTipsPositions.get(toolTip.id);
	
		  var left;
		  var top;
		  if(positions) {
			  left = positions.left;
			  top = positions.top;
		  } else {
			  left = Element.getStyle(toolTip, "left");
			  left = parseInt(left.substring(0, left.indexOf("px")));
	
			  top = Element.getStyle(toolTip, "top");
			  top = parseInt(top.substring(0, top.indexOf("px")));
			  
			  toolTipsPositions.set(toolTip.id, {'left': left, 'top': top});
		  }
	
		  Element.setStyle(toolTip,{
	    	  left: (offsets[0] + left) + 'px',
	    	  top: (offsets[1] - toolTipTrigger.getHeight() - top) + 'px',
	    	  position: 'absolute'
	      });
	      
	      toolTip.parentNode.removeChild(toolTip);
		  document.body.appendChild(toolTip);
	
	      Event.observe(toolTipTrigger, 'mouseover', function() {toolTip.show();});
	      Event.observe(toolTipTrigger, 'mouseout', function() {toolTip.hide();});
  	  }
  });
}

/**
 * Lightbox scripts
 */
var LightBox = Class.create({
  lightBoxId: null,
  parameters: null,
  lightBoxTop: 0,
  lightBoxLeft: 0,
  lightBoxWindow: null,
  lightBoxWidth: 446,
  windowScroll: null,
  closerId: null,
  closeCallBack: null,
  ajaxRequest: null,
  initialContent:null,

  initialize: function(content, parameters) {
  
	if(!parameters.className) {
		parameters.className = "likexo-lightbox";
	}
	parameters.destroyOnClose = true;
	
    this.initialContent = content;
    this._setLightBoxWidth(parameters);
	parameters = this._checkId(parameters);
    parameters = this._checkWindowEffects(parameters);

    if (content && typeof content != "string") {
      this.ajaxRequest = content;
      content = $('loader').innerHTML;

    } 

//    parameters = this._computeSize(content, parameters);
    parameters.width = this.lightBoxWidth;
    parameters.zIndex = 20;
//    var win = new Window(parameters);
//    win.getContent().update(content);

    this.lightBoxTop = parameters.top;
	this.lightBoxLeft = parameters.left;
    this.parameters = parameters;
//	this.lightBoxWindow = win;
	
	if (parameters.triggerId) {
		if(parameters.triggerId.indexOf(",") > 0) {
		  LightBoxManager.addTriggerEvent(parameters.triggerId, this.lightBoxId);
          var triggerIds = parameters.triggerId.split(",");
          for ( var i = 0; i < triggerIds.length; i++ ) {
      	    if($(triggerIds[i])) {
   		      LightBoxManager.addTriggerEvent(triggerIds[i], this.lightBoxId);
    	    }
	      }
		} else {
			LightBoxManager.addTriggerEvent(parameters.triggerId, this.lightBoxId);
		}
	}
	
    // Overlay Opera Hack
	if (Prototype.Browser.Opera) {
      var overlayAnchor = new Element('span', {'id': 'overlay-anchor'}).update('&nbsp;');
      document.body.appendChild(overlayAnchor);
	}

	// Binding..
	this.open = this.open.bind(this);
	this.close = this.close.bind(this);
	this.updateContent = this.updateContent.bind(this);
	this.setCloser = this.setCloser.bind(this);
	this._checkId = this._checkId.bind(this);
	this._setLightBoxWidth = this._setLightBoxWidth.bind(this);
	this._computeSize = this._computeSize.bind(this);
	this._blockScroll = this._blockScroll.bind(this);
	this._setNewContent = this._setNewContent.bind(this);
	this._runAjaxRequest = this._runAjaxRequest.bind(this);
	this._getAjaxContent = this._getAjaxContent.bind(this);
	this._handleError = this._handleError.bind(this);
	this._resetVars = this._resetVars.bind(this);
	this.destroy = this.destroy.bind(this);

//	return win;
  },

  open: function() {
    var win = new Window(this.parameters);
    win.getContent().update(this.initialContent);
    this.lightBoxWindow = win;

    this.lightBoxWindow.showCenter(true, this.lightBoxTop, this.lightBoxLeft);     
    if (this.ajaxRequest) {
      this._setNewContent($('loader').innerHTML);
      this._runAjaxRequest(this.ajaxRequest);
    }
  },

  close: function() {
    if(this.lightBoxWindow) {
      this.lightBoxWindow.close();
    } else {
      Windows.close(this.lightBoxId);
    }

	if(this.closeCallBack) {
	  this.closeCallBack.delay(this.parameters.hideEffectOptions.duration);
	}
	this._resetVars();
	if (this.initialContent && typeof this.initialContent  != "string") {
      this.ajaxRequest = this.initialContent;
    } else {
      this._setNewContent(this.initialContent);
	}
  },
 
  updateContent: function(newContent, parameters) {
    if(parameters && parameters.closeCallBack) {
      this.closeCallBack = parameters.closeCallBack; 
    }

    if(parameters && parameters.closerId) {
      this.closerId = parameters.closerId; 
    }

    if (newContent && typeof newContent != "string") {
      this._setNewContent($('loader').innerHTML);
      this._runAjaxRequest(newContent);
    } else {
      this._setNewContent(newContent);
    }
  },
  
  destroy: function() {
    this.lightBoxWindow.destroy();
  },
  
  setCloser: function(closerId, closeCallBack) {
    this.closerId = closerId;
    if(closeCallBack) {
      this.closeCallBack = closeCallBack;
    }
    LightBoxManager.addCloserEvent(this.closerId, this.lightBoxId);
    //Event.observe($(this.closerId), 'click', function(event){this.close();}.bindAsEventListener(this));
  },
  
  /********************/
  /* Internal Methods */
  /********************/
  
  _resetVars: function() {
    this.closeCallBack = null; 
    this.closerId = null; 
  },
  
  _checkId: function(parameters) {
    if (parameters.id)
      this.lightBoxId = parameters.id;
    else { 
      var t = new Date();
      this.lightBoxId = 'lightbox_' + t.getTime();
      parameters.id = this.lightBoxId;
    }
    
    return parameters;
  },
    
  _setLightBoxWidth: function(parameters){
  	this.lightBoxWidth = parameters.width ? parameters.width : this.lightBoxWidth;
    if (!parameters.height && !this.lightBoxWidth) {
      this.lightBoxWidth = WindowUtilities.getPageSize(parameters.options.parent || document.body).pageWidth / 2;
    }
  },
  
  _computeSize: function(content, parameters) {
    if (! parameters.height || ! this.lightBoxWidth) {
      var size = WindowUtilities._computeSize(content, this.lightBoxId, this.lightBoxWidth, 
                                                     parameters.height, 5, parameters.className);
      if (parameters.height)
        this.lightBoxWidth = size + 5
      else
        parameters.height = size + 5
    }
    
    return parameters;
  },
  
  _checkWindowEffects: function(parameters) {
    parameters.resizable   = false;
    parameters.minimizable = false;
    parameters.maximizable = false;
    parameters.draggable   = false;
    parameters.closable    = false;
  
    parameters.showEffectOptions = parameters.showEffectOptions || {duration:0.25};
	parameters.hideEffectOptions = parameters.hideEffectOptions || {duration:0.25};
    Windows.overlayHideEffectOptions = parameters.overlayHideEffectOptions || {duration:0.25};
	Windows.overlayShowEffectOptions = parameters.overlayShowEffectOptions || {duration:0.25};
	
	return parameters;
  },

  _setWindowScroll: function(left, top) {
      var w = window;
      with (w.document) {
        if (w.document.documentElement && documentElement.scrollTop) {
          documentElement.scrollTop = top;
          documentElement.scrollLeft = left;
        } else if (w.document.body) {
          body.scrollTop = top;
          body.scrollLeft = left;
        }
      }
  }, 

  _blockScroll: function(event) {
    this._setWindowScroll(this.windowScroll.left, this.windowScroll.top);
  },
  
  _setNewContent: function(content) {
  	this.lightBoxWindow.getContent().update(content);
  	this.lightBoxWindow.height = null;
  	  
  	// Set undefined vars.. windows.js accepts only that :S
  	var width;
  	var height;
  	this.lightBoxWindow.centerTop = width;
  	this.lightBoxWindow.centerLeft = height;
  	this.lightBoxWindow.computeBounds();

    if($(this.closerId)) {
      LightBoxManager.addCloserEvent(this.closerId, this.lightBoxId);
      //Event.observe($(this.closerId), 'click', this.close.bindAsEventListener(this));
    }
  },
  
  _runAjaxRequest: function(message) {
    if (!message.options) {
      message.options = {};
    }
    message.options.onComplete = this._getAjaxContent;
    message.options.onException = this._handleError;
    if(!message.options.parameters) {
    	message.options.parameters = {actualUrl: $F('actualUrl')};
    } else {
    	message.options.parameters.actualUrl = $F('actualUrl');
    }

    new Ajax.Request(message.url, message.options);
  },
   
  _handleError: function(originalRequest) {
	  var errorMsg = "<div class=\"modal\">" +
	                 "<span class=\"title\">Uppsss...</span>" +
                     "<p>There were dificulties making the request.</p>" +
                     "<a href=\"javascript:;\" class=\"botonGenerico\" id=\"errorCloseButton\">Ok</a>" +
                     "<p id=\"footer\">" +
                     "  Try again, if the problem persists, contact us support@likexo.com." +
                     "</p>" +
	                 "</div>";
	  
      this.updateContent(errorMsg, null);
      LightBoxManager.addCloserEvent('errorCloseButton', this.lightBoxId);
  },
  
  _getAjaxContent: function(originalRequest) {
      if(200 == originalRequest.status) {
    	  if ((originalRequest.getResponseHeader('LOGIN_PAGE') || '').match(/true/)) {
	          window.location.href = $F('ajaxErrorPage');
	      } else {
              this._setNewContent(originalRequest.responseText);
	      }
      } else {
          this._handleError(originalRequest);
      }
  }
  
});

var LightBoxManager = {
	triggerEvents : null,
	closerEvents : null,
	
	addTriggerEvent: function(triggerId, lightboxWindowId) {
		if(!LightBoxManager.triggerEvents) {
			LightBoxManager.triggerEvents = new Hash();
		}
		LightBoxManager.triggerEvents.set(triggerId, lightboxWindowId);
	},

	addCloserEvent: function(closerId, lightboxWindowId) {
		if(!LightBoxManager.closerEvents) {
			LightBoxManager.closerEvents = new Hash();
		}
		LightBoxManager.closerEvents.set(closerId, lightboxWindowId);
	},
	
	observe: function() {
		Event.observe(document,'click', LightBoxManager.clickManager);
	},
	
	stopObserving: function() {
		Event.stopObserving(document,'click', LightBoxManager.clickManager);
	},
	
	clean: function() {
		LightBoxManager.triggerEvents = null;
		LightBoxManager.closerEvents = null;
	},
	
	clickManager: function(event) {
		if(Event.element(event) && Event.element(event).id) {
			if(LightBoxManager.triggerEvents) {	
				var windowId = LightBoxManager.triggerEvents.get(Event.element(event).id);
				if(windowId) {
					window[windowId].open();
				}
			}
			if(LightBoxManager.closerEvents) {
				var windowId = LightBoxManager.closerEvents.get(Event.element(event).id);
				if(windowId) {
					window[windowId].close();
				}
			}
		}
	}
}

/**
 * Likexo extras scripts
 */
function selectPrfMenuOption(optionId) {
    $(optionId).addClassName("selec");
}

function refreshContent(originalRequest, containerName) {
    $(containerName).update(originalRequest.responseText);
}

var ModifyUtils = {
  showModifyingOverlay: function(anElement) {
    if(!anElement) {
	    var div = document.createElement("div");
	    div.setAttribute('id', "modificandoLoadingImageFullPage");
	    div.innerHTML = $('fullpage-loader-container').innerHTML;
	    if(Prototype.Browser.IE) {
	    	div.style.width = WindowUtilities.getPageSize().pageWidth + "px";
	    	div.style.height = WindowUtilities.getPageSize().pageHeight + "px";
	    } else {
	    	div.style.width = (WindowUtilities.getPageSize().pageWidth - 18) + "px";
	    	div.style.height = (WindowUtilities.getPageSize().pageHeight - 18)+ "px";
	    }
	    document.body.appendChild(div);
	    if(Prototype.Browser.IE) {
	    	var loader = $('modificandoLoadingImageFullPage').childElements().find(function(e){return e.hasClassName("loading-image");});
	    	loader.style.position = 'absolute';
	    	var scroll = WindowUtilities.getWindowScroll();
	    	loader.style.left = (scroll.left + (scroll.width/2)) + "px";
	    	loader.style.top = (scroll.top + (scroll.height/2)) + "px";
	    }
    } else {
        var loadingContainer = anElement.select(".loading-image-container").first();
        loadingContainer.removeClassName("disabled");
        Element.clonePosition(loadingContainer, anElement, {setLeft:false,setTop:false});
    }
  },

  hideModifyingOverlay: function(anElement) {
      if(!anElement) {
    	  if($("modificandoLoadingImageFullPage")) {
            document.body.removeChild($("modificandoLoadingImageFullPage"));
    	  }
      } else {
    	  anElement.select(".loading-image-container").first().addClassName("disabled");
      }
  }  
}

function scrollToErrorDesc() {
}


/**
 * Login scripts
 */
function updateActualUrl(url) {
	if(url) {
		$('actualUrl').value = url;
	}
}

/**
 * Role checkbox scripts
 */
var RoleCheckbox = Class.create({
	checkboxName: null,
	checkboxValue: null,
	checkboxDescription: null,
	
	initialize: function (name, value, description) {
	    this.checkboxName = name;
	    this.checkboxValue = value;
	    this.checkboxDescription = description;
	    
	    this.print = this.print.bind(this);
    },
    
    print: function (containerId) {
    	var li = new Element("li");
    	var checkbox = new Element("input", {'class': 'checkbox', 'type': 'checkbox'})
    	checkbox.name = this.checkboxName;
    	checkbox.value = this.checkboxValue;
    	li.appendChild(checkbox);
    	li.update(li.innerHTML + this.checkboxDescription);
    	
    	$(containerId).insert(li);
    },
    
    printLikeHidden: function (containerId) {
    	var input = new Element("input");
    	input.id = "hidden-role";
    	input.type = "hidden";
    	input.name = this.checkboxName;
    	input.value = this.checkboxValue;

    	$(containerId).insert(input);
    }
});

var RoleCheckboxList = Class.create({
	checkboxList: null,
	
	initialize: function() {
	    this.checkboxList = new Array();
	    this.addCheckbox = this.addCheckbox.bind(this);
	    this.print = this.print.bind(this);
	    this.size = this.size.bind(this);
    },
    
    addCheckbox: function(checkbox) {
    	this.checkboxList[this.checkboxList.length] = checkbox;
    },
    
    print: function(containerId) {
    	if(this.checkboxList.length == 1) {
    		this.checkboxList.first().printLikeHidden($(containerId).parentNode.id);
    	} else {
    	    $(containerId).childElements().each(function(element){element.remove()});
    	    this.checkboxList.each(function(checkbox){checkbox.print(containerId)});
    	}
    },
    
    size: function() {
    	return this.checkboxList.length;
    }
	
});

function hideBtmas() {
	JQ('div#contenidoPrincipal div#cuerpo table.iteminfocontainer td.iteminfo div.fieldtitle').find('span').hide();
}

function buildBtmasMouseOverMsg() {
    JQ('div#contenidoPrincipal div#cuerpo table.iteminfocontainer td.iteminfo div.fieldtitle a')
	    .mouseover(function(){	JQ(this).parent().find('span').show();	})
	    .mouseout(function(){	JQ(this).parent().find('span').hide();	});
}

function buildItemRollover() {
	JQ('div#contenidoPrincipal div#cuerpo div div.items a')
	    .find('span.datos').css({ opacity:0.5 }).end()
	    .find('span').hide().end()
	    .mouseover(function(a){	JQ('span',this).show()	})
	    .mouseout(function(a){	JQ('span',this).hide()	});
}

/**
 * Scrapbook scripts
 */
function reloadScrapbook(receiverUsername, containerName, scrapbookUrl) {
	receiverUsername = receiverUsername;
	containerName = containerName;
	var message = { 
		url: scrapbookUrl + '?show=all&username=' + receiverUsername, 
		options: {
			method: 'get', 
			onComplete: function(originalRequest){ 
		 					refreshContent(originalRequest, containerName); }
						}
		}; 
	new Likexo.Ajax(message);	
}

/**
 * Select scripts
 */
Autocompleter.SelectBox = Class.create();
Autocompleter.SelectBox.prototype = Object.extend(new Autocompleter.Base(), {
  initialize: function(select, options) {
	this.element = "<input type=\"text\" id=\"" + $(select).id + "_combo\" />"
	new Insertion.Before(select, this.element)
	var inputClasses = Element.classNames(select);
	inputClasses.each(function(inputClass)
		{
			Element.addClassName($(select).id + "_combo", inputClass);
		});
	
	this.update = "<div id=\"" + $(select).id + "_options\" class=\"autocomplete\"></div>"	
	new Insertion.Before(select, this.update)
		
		
    this.baseInitialize($(select).id + "_combo", $(select).id + "_options", options);
    this.select = select;
	this.selectOptions = [];
		
	$(this.element.id).setAttribute('readonly','readonly');

	// Add by Emiliano Mettini (26-08-2008)
	$(this.element.id).onmousedown = function() {return false};
	if (!Prototype.Browser.IE) {
  	  $(this.element.id).onfocus = function() {$($(select).id + "_combo").blur()};
	} else {
	  $(this.element.id).onselect = 
		  function() {
            if (document.selection)
              document.selection.empty();
            else if (window.getSelection)
              window.getSelection().removeAllRanges();
	      }
	}
    ////

	this.element.readOnly = true;
	if(this.options.debug)alert('input ' + this.element.id + ' and div '+ this.update.id + ' created, Autocompleter.Base() initialized');
	if(!this.options.debug)Element.hide(select);

	var optionList = $(this.select).getElementsByTagName('option');
	var nodes = $A(optionList);

	for(i=0; i<nodes.length;i++){
		this.selectOptions.push("<li id=\"" + nodes[i].value + "\">" + nodes[i].innerHTML + '</li>');
		if (nodes[i].getAttribute("selected")) this.element.value = nodes[i].innerHTML;
		
		if(this.options.debug)alert('option ' + nodes[i].innerHTML + ' added to '+ this.update.id);
	}
	
	Event.observe(this.element, "click", this.activateOrDesactivate.bindAsEventListener(this));
	
	if ($(select).selectedIndex >= 0)this.element.value = $(select).options[$(select).selectedIndex].innerHTML;
	
	var self = this;
	this.options.afterUpdateElement = function(text, li) {
		var optionList = $(select).getElementsByTagName('option');
		var nodes = $A(optionList);

		var opt = nodes.find( function(node){
			return (node.value == li.id);
		});
		$(select).selectedIndex=opt.index;
		if(self.options.redirect) document.location.href = opt.value;
		if(self.options.autoSubmit != '') 
			$(self.options.autoSubmit).submit;
		if($(select).onchange) {
			$(select).onchange();
		}	
	}
  },

  activateOrDesactivate: function() {
	if(this.hasFocus) {
		this.desactivate();
	} else {
		this.activate();
	}  
  },

  desactivate: function(){
    setTimeout(this.hide.bind(this), 1);
    this.hasFocus = false;
    this.active = false;     
  },

  getUpdatedChoices: function() {
  		this.updateChoices(this.setValues());
  },

  setValues : function(){
		return ("<ul>" + this.selectOptions.join('') + "</ul>");
  },
  
  getTokenBounds: function() {
    return [-1, 0];
  },
  
  
  setOptions: function(options) {
    this.options = Object.extend({
		//MORE OPTIONS TO EXTEND THIS CLASS
		redirect	: false, // redirects to option value
		debug		: false, //show alerts with information
		autoSubmit	: '' //form Id to submit after change 
	}, options || {});
  }
})

/**
 * Show mails scripts
 */
function _runDelete(url) {
    confirmDeleteLightBox.close();
    window.location.href = url;
}

/**
 * Url changer scripts
 */
var NameUrlChanger = Class.create();
NameUrlChanger.prototype = {

    initialize: function(inputName, aName, emptyFieldText) {

        this.inputElement = $(inputName);
        this.aElement = $(aName);
        this.emptyFieldText = emptyFieldText;
        
        if(this.inputElement.value && this.inputElement.value != "") {
          this.aElement.update(this.inputElement.value + '.likexo.com');
        } else {
          this.aElement.update('[' + this.emptyFieldText + ']' + '.likexo.com');
        }
		
		this.changeManager = this.changeManager.bindAsEventListener(this);
		this.inputElement.observe('keyup', this.changeManager);		
    },

    changeManager: function(event) {
      if(this.inputElement.value && this.inputElement.value != "") {
        this.aElement.update(this.inputElement.value + '.likexo.com');
      } else {
        this.aElement.update('[' + this.emptyFieldText + ']' + '.likexo.com');
      }	
    }
}

/**
 * Image functions
 */
function resize(wich, imgWidth, imgHeight, max) {
    var elem = JQ(wich);
    if (elem === undefined || elem === null) { 
        return false;
    }

    var originalWidth = new Number(imgWidth);
    var originalHeight = new Number(imgHeight);

    if (max === undefined) { 
        max = 100; 
    }
    if (originalWidth > originalHeight) {
        if (originalWidth > max) {
            elem.attr('width', max);
            originalWidth = max;
            originalHeight = elem.attr('height');
        }
    } else {
        if (originalHeight > max) {
            elem.attr('height', max);
            originalHeight = max;
            originalWidth = elem.attr('width');
        }
    }

}    	

JQ(document).ready(function(){
   ElementVisualizerManager.observe();
   refreshToolsPosition.delay(1);
   LightBoxManager.observe();
   if($('muestroErrores')) {
 	   $('muestroErrores').scrollTo();
 	   window.scrollBy(0, -(WindowUtilities.getPageSize().windowHeight - 30 + $('muestroErrores').getHeight()));
   }
   if($('loginPageActualUrl')) {
	   updateActualUrl($F('loginPageActualUrl'));
   }
   if(Prototype.Browser.IE) {
	 if( $('errorArrowPath')) {
         JQ('img.flechaError').attr("src", $('errorArrowPath').value);
	 }
   }
   buildItemRollover();
   buildBtmasMouseOverMsg();
      
  /** 
   * Contact list scripts
   */
   if($('email_contacts_list')) {
	 JQ('#toggle_all_checkbox').attr('checked', true);
     JQ("table#email_contacts_list INPUT[@id='contacts'][type='checkbox']").attr('checked', true);  
	   
     JQ('#toggle_all_checkbox').click(function () {
        if (JQ('#toggle_all_checkbox').attr('checked')) {
             JQ("table#email_contacts_list INPUT[@id='contacts'][type='checkbox']").attr('checked', true);
        } else {
            JQ("table#email_contacts_list INPUT[@id='contacts'][type='checkbox']").attr('checked', false);
        }
     });

	 JQ('#toggle_all_checkbox_text').click(function () {
        if (JQ('#toggle_all_checkbox').attr('checked')) {
		     JQ('#toggle_all_checkbox').attr('checked', false);
             JQ("table#email_contacts_list INPUT[@id='contacts'][type='checkbox']").attr('checked', false);
        } else {
		    JQ('#toggle_all_checkbox').attr('checked', true);
            JQ("table#email_contacts_list INPUT[@id='contacts'][type='checkbox']").attr('checked', true);
        }
	 });
	 
	 JQ('td.name, td.email').each(function () {
		 JQ(this).click(function () {
			 var checkbox = JQ(this).parent().find('.checkbox').find('.inputcheckbox');
			 if (checkbox.attr('checked')) {
				 checkbox.attr('checked', false);
			 } else {
				 checkbox.attr('checked', true);
			 }
		 });
	 });
   }
	if($('email_friends_list')) {
      JQ('#toggle_all_checkbox').click(function () {
         if (JQ('#toggle_all_checkbox').attr('checked')) {
              JQ("table#email_friends_list INPUT[@id='contacts'][type='checkbox']").attr('checked', true);
         } else {
             JQ("table#email_friends_list INPUT[@id='contacts'][type='checkbox']").attr('checked', false);
         }
      });
	  JQ('#toggle_all_checkbox_text').click(function () {
	        if (JQ('#toggle_all_checkbox').attr('checked')) {
	    	    JQ('#toggle_all_checkbox').attr('checked', false);
	            JQ("table#email_friends_list INPUT[@id='contacts'][type='checkbox']").attr('checked', false);
	        } else {
	    	    JQ('#toggle_all_checkbox').attr('checked', true);
	            JQ("table#email_friends_list INPUT[@id='contacts'][type='checkbox']").attr('checked', true);
	        }
	  });
	  
	  JQ('td.name, td.email').each(function () {
		  JQ(this).click(function () {
			  var checkbox = JQ(this).parent().find('.checkbox').find('.inputcheckbox');
			  if (checkbox.attr('checked')) {
				  checkbox.attr('checked', false);
			  } else {
				  checkbox.attr('checked', true);
			  }
		  });
	  });
	}
});
