/*
wsDialog
*/

WSDialog = function (options) {
	options = options || {};
	
	/* Cache & status */
	this._dialog = null;
	this._header = null;
	this._content = null;
	this._iframe = null;
	this._shadow = null;
	this._curtain = null;
	this._page_size = null;
	this.visible = false;

	/* Element ids */
	this.id_dialog = "WSDialog_dialog";
	this.id_header = "WSDialog_header";
	this.id_header_title = "WSDialog_header_title";
	this.id_close = "WSDialog_close";
	this.id_content = "WSDialog_content";
	this.id_iframe = "WSDialog_iframe";
	this.id_shadow = "WSDialog_shadow";
	this.id_curtain = "WSDialog_curtain";
	this.id_marker = "WSDialog_marker";

	/* CSS Class */
	this.class_dialog = "wsd_dialog";
	this.class_header = "wsd_header";
	this.class_header_right = "float_right";
	this.class_content = "wsd_content";
	this.class_shadow = "wsd_shadow";
	this.class_curtain = "wsd_curtain";
	
	/* Size & position */
	this.width = 700;           // Integer
	this.height = 'auto';       // Auto or integer
  this.top = 0;
	this.left = 0;
	this.zindex_dialog = 902;
	this.zindex_shadow = 901;
	this.zindex_curtain = 900;
	this.align_horz = "center"; // [left, center, right]
	this.align_vert = "middle";    // [top, middle]
	this.offset_horz = 20;
	this.offset_vert = 20;

	/* Effects */
	this.show_header = false;
	this.use_shadow = this._isIE();
	this.scroll_effect = false;
	this.scroll_effect_duration = 0.5;
	
	/* Title */
	this.title = "Adsend";
	
	/* Dailog action */
	this.action = 'ajax';       // [element, url, ajax]
	this.action_source = null;  // element id, url, ajax url
	this.action_params = null;  // Mainly used for ajax
	
	/* Event handlers */
	this.onClose = options.onClose || null;
	this.onShow = options.onShow || null;
	this.onActionComplete = options.onActionComplete || null;

	/* Return the instance */
	return this;
};

WSDialog.prototype._isIE = function() {
  return (navigator.appName == "Microsoft Internet Explorer");
}

WSDialog.prototype._getPageSize = function() {
	if (this._page_size != null) { return this._page_size; }

	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2) // all but Explorer Mac
	{
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	}
	else // Explorer Mac. Would also work in Explorer 6 Strict, Mozilla and Safari
	{
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}

	/* Calculate the bottom of the document with a fake element */
	var el = $(this.id_marker);
	if (!el) {
		new Insertion.Bottom(document.body, '<div id="'+this.id_marker+'" style="clear:both;visible:none;height:0px;width:1px;"></div>');
		el = $(this.id_marker);
	}
	Position.cumulativeOffset(el);
	y = (y > el.offsetTop) ? y : el.offsetTop;

	/* Cache */
	this._page_size = {'width':x, 'height':y};

	/* Return */
	return this._page_size;
}

/* Get client height */
WSDialog.prototype._getClientHeight = function() {
	return this._filterSizeResults(
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

/* Get page's scroll top */
WSDialog.prototype._getScrollTop = function() {
	return this._filterSizeResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

/* Ensure to return correct value */
WSDialog.prototype._filterSizeResults = function(val1, val2, val3) {
	var result = val1 ? val1 : 0;
	if (val2 && (!result || (result > val2)))
		result = val2;
	return val3 && (!result || (result > val3)) ? val3 : result;
}

/* Prepare a curatin element */
WSDialog.prototype._prepareCurtain = function() {
	/* Ensure to create only one instance */
	var el = $(this.id_curtain);
	if (!el) {
		new Insertion.Bottom(document.body, '<div id="'+this.id_curtain+'" class="'+this.class_curtain+'" style="display:none;z-index:'+this.zindex_curtain+';"></div>');
		el = $(this.id_curtain);
		Event.observe(el, 'click', this._doClose.bindAsEventListener(this) );
	}

	/* Initialize */
	el.innerHTML = "";

	/* Cache */
	this._curtain = el;

	/* Return the element */
  return el;
};

/* Position the curtain */
WSDialog.prototype._positionCurtain = function() {
	/* Ensure to create only one instance */
	var el = this._curtain || $(this.id_curtain);
	if (!el) { el = this._prepareCurtain(); }

	/* Initialize */
	el.style.height = this._getPageSize().height + 'px';
};

/* Prepare a dialog element */
WSDialog.prototype._prepareShadow = function() {
	if (!this.use_shadow || this.action == "url") { return false; }

	/* Ensure to create only one instance */
	var el = $(this.id_shadow);
	if (!el) {
		new Insertion.Bottom(document.body, '<iframe src="javascript:\'<html></html>\'" scrolling="no" frameborder="0" id="'+this.id_shadow+'" class="'+this.class_shadow+'" style="display:none;z-index:'+this.zindex_shadow+';"></iframe>');
		el = $(this.id_shadow);
	}

	/* Initialize */
	el.style.width = (this.width == 'auto') ? 'auto' : this.width + 'px';
	el.style.height = (this.height == 'auto') ? 'auto' : this.height + 'px';

	/* Cache */
	this._shadow = el;

	/* Return the element */
	return el;
};

/* Position the shadow element */
WSDialog.prototype._positionShadow = function() {
	if (!this.use_shadow || this.action == "url") { return false; }
	
	var shadow = this._shadow || this._prepareShadow();
	var dialog = this._dialog || this._prepareDialog();
	
	shadow.style.top = dialog.style.top;
	shadow.style.left = dialog.style.left;
	shadow.style.width = dialog.getWidth() + 'px';
	shadow.style.height = dialog.getHeight() + 'px';
};

/* Prepare a dialog element */
WSDialog.prototype._prepareDialog = function() {
	/* Ensure to create only one instance */
	if (!$(this.id_dialog)) {
		new Insertion.Bottom(document.body, '<div id="'+this.id_dialog+'" class="'+this.class_dialog+'" style="display:none;z-index:'+this.zindex_dialog+';"></div>');
		this._dialog = $(this.id_dialog);

		/* Add event for dialog size change */
		Event.observe(this._dialog, 'resize', this._handleDialogResize.bindAsEventListener(this) );

    if (this.show_header) {
			new Insertion.Top(this._dialog, '<div id="'+this.id_header+'" class="'+this.class_header+'" style=""><div class="'+this.class_header_right+'"><a href="#" id="'+this.id_close+'" onclick="'+this.action_close+'; return false;"><span>Close</span></a></div><h1 id='+this.id_header_title+'>'+this.title+'</h1></div>');
			this._header = $(this.id_header);
			
			/* Assing close event */
			Event.observe(this.id_close, 'click', this._doClose.bindAsEventListener(this) );
		}
		
		if (this.action == "url") {
			new Insertion.Bottom(this._dialog, '<div class="'+this.class_content+'" style="width:auto"><iframe id="'+this.id_iframe+'" src="javascript:\'<html></html>\'" frameborder="0" style="width:100%;"></iframe></div>');
			this._iframe = $(this.id_iframe);
		} else {
		  new Insertion.Bottom(this._dialog, '<div id="'+this.id_content+'" class="'+this.class_content+'"><p> Loading...</p></div>');
      this._content = $(this.id_content);
		}
	} else {
	  this._dialog = $(this.id_dialog);
	  this._content = $(this.id_content);
	  this._iframe = $(this.id_iframe);
	}

	/* Update the title */
	var title = $(this.id_header_title);
	if (title) { title.innerHTML = this.title; }
	
	/* Initialize the content */
	if (this._content) { this._content.innerHTML = '<p> Loading...</p>'; }
	if (this._iframe) { this._iframe.src = 'javascript:\'<html><p> Loading...</p></html>\''; }

	/* Select content element */
	var content = null;
	if (this.action == "url") {
		content = this._iframe;
	} else {
    content = this._content;
	}

	/* Initialize height */
	this._dialog.style.width = (this.width == 'auto') ? 'auto' : this.width + 'px';
	content.style.height = (this.height == 'auto') ? 'auto' : this.height + 'px';

	/* Return the element */
	return this._dialog;
};

/* Prepare a dialog element */
WSDialog.prototype._positionDialog = function() {
	/* Ensure to create only one instance */
	var el = this._dialog || $(this.id_dialog);
	if (!el) { el = this._prepareDialog(); }
	
	var page = this._getPageSize();
	switch (this.align_horz) {
		case "left":
		  el.style.left = (this.offset_horz) + 'px';
		  break;
		case "center":
		  el.style.left = ((page.width - el.getWidth()) / 2) + 'px';
		  break;
		case "right":
		  el.style.left = (page.width - el.getWidth() - this.offset_horz) + 'px';
		  break;
	}
	switch (this.align_vert) {
		case "top":
		  el.style.top = ( this._getScrollTop() + this.offset_vert) + 'px';
		  break;
		case "middle":
		  el.style.top = Math.max(this._getScrollTop() + this.offset_vert, this._getScrollTop() + ((this._getClientHeight() - el.getHeight()) / 2 ) )+ 'px';
		  break;
	}
};

/* Handle page resize */
WSDialog.prototype._handlePageResize = function() {
  if (!this.visible) { return false; }

  this._page_size = null;
	this._positionCurtain();
	this._positionDialog();
	this._positionShadow();
};

/* Handle dialog resize */
WSDialog.prototype._handleDialogResize = function() {
	this._positionDialog();
	this._positionShadow();
}

/* Do the action */
WSDialog.prototype._doAction = function() {
	switch (this.action) {
		case "element":
		  this._content.update($(this.action_source).innerHTML);
		  this._doActionComplete();
		  break;
		case "url":
			this._doActionComplete(); /* Trigger complete event immediately to fix Safari hidden iframe onload event issue */
			this._iframe.src = this.action_source;
		  break;
		case "ajax":
		  if (this.action_params) {
			  new Ajax.Updater( { success: this.id_content }, this.action_source, { evalScripts: true, parameters: this.action_params, onComplete: this._doActionComplete.bindAsEventListener(this) } );
			} else {
			  new Ajax.Updater( { success: this.id_content }, this.action_source, { evalScripts: true, onComplete: this._doActionComplete.bindAsEventListener(this) } );
			}
		  break;
	}
}

WSDialog.prototype._doActionComplete = function() {
	this._positionDialog();
	this._positionShadow();
	
	this._toggle(this._dialog, true);
	this._toggle(this._shadow, true);
	
	if (this.onActionComplete) {
    setTimeout(this.onActionComplete.bind(this), 10);
	}
}

WSDialog.prototype._doClose = function() {
  setTimeout(this.close.bind(this), 10);
}

/* Toggle visibility */
WSDialog.prototype._toggle = function(el, mode) {
	if (el) { el.style.display = (mode) ? 'block' : 'none'; }
}

/* Show the dialog and the curtain */
WSDialog.prototype.show = function() {
	/*
	if (!this._curtain) { this._prepareCurtain(); }
	if (!this._shadow) { this._prepareShadow(); }
	if (!this._dialog) { this._prepareDialog(); }
	*/
	this._prepareCurtain();
	this._prepareShadow();
	this._prepareDialog();

	this._positionCurtain();
	/*
	this._positionDialog();
	this._positionShadow();
	*/
	
	this._toggle(this._curtain, true);
	/*
	this._toggle(this._dialog, true);
	this._toggle(this._shadow, true);
	*/

	this._doAction();

	/* Add event for page size change */
	Event.observe(window, 'resize', this._handlePageResize.bindAsEventListener(this) );

	/* Set mode */
  this.visible = true;
  
  if (this.onShow) {
    setTimeout(this.onShow.bind(this), 10);
	}
	
	if (this.scroll_effect) {
		new Effect.ScrollTo(this.id_dialog, {offset: -50, duration: this.scroll_effect_duration});
	}
};

/* Close the dialog and the curtain */
WSDialog.prototype.close = function() {
	/* Set mode. It's imporant that it's set here first before the elements are hidden away */
  this.visible = false;
  
	this._toggle(this._curtain, false);
	this._toggle(this._dialog, false);
	this._toggle(this._shadow, false);

	/* Remmove event listener */
	Event.stopObserving(window, 'resize', null);
	
	/* Reset page size */
	this._page_size = null;

	/* Trigger Event */
  if (this.onClose) {
    setTimeout(this.onClose.bind(this), 10);
	}
};

/* Close the dialog and the curtain */
WSDialog.prototype.repaint = function() {
  this._page_size = null;
	this._positionDialog();
	this._positionShadow();
};

