
//- Dialog ----------------------------------------------------------------
// •needs:	popup, jquery

jQuery(document).ready(function($){
// this only allows one dialog to be showing at a time: if another appears,
// the first is automatically closed/cancelled/answered ‘no’

popup_dialog = new Popup('dialog', 'poppedup');

popup_dialog.alert = function (m) { var _ = popup_dialog;
	_.type = 'alert';
	_.popup_html(m);
	return false;
}

popup_dialog.confirm = function (m, callback, y, n) { var _ = popup_dialog;
	_.type = 'confirm';
	y = (y == undefined ? "OK" : y);
	n = (n == undefined ? "Cancel" : n);
	_.callback = function(v){ _.hide(); callback(v) };
	_.popup_html(m + '<div class="popup-controls">'
	+ '<button name="Cancel" type="button" class="secondary">'+n+'</button>'
	+ '<button name="OK" type="button">'+y+'</button>'
	+ '</div>');
	var b = $("."+_.content_class);
	setTimeout(function(){
		$(b).find('[name=Cancel]').click(function(){_.callback(false)});
		$(b).find('[name=OK]').click(function(){_.callback(true)});
	}, 100);// delay so there’s time for the confirm to be created
	return false;
}

popup_dialog.password = function (m, signin) { var _ = popup_dialog;
	_.type = 'password';
	if (signin == undefined) signin = validate_and_sign_in;
	_.signin = function (f) {
		_.hide();
		with (f) signin(username.value, password.value);
	}
	_.bail = function () { _.hide() }
	_.popup_html('<form onsubmit="return false">'
	+ m + '<table><tr><th>Name</th><td><input name="username" /></td></tr>'
	+ '<tr><th>Password</th><td><input type="password" name="password" value="" />'
	+ '</td></tr></table><div class="popup-controls">'
	+ '<button name="Cancel" class="secondary" type="button">'+"Cancel"+'</button>'
	+ '<button name="OK" type="submit">'+"Sign In"+'</button>'
	+ '</div></form>');
	$(_).find('form').submit(function(){ _.signin(_); return false });
	$(_).find('[name="Cancel"]').click(function(){ _.bail() });
	return false;
}

popup_dialog.notify = function (m) { var _ = popup_dialog;
	_.type = 'notify';
	var original = { show: _.show, hide: _.hide };
	// popup w/ auto-popdown
	_.show = function(){
		_.show = original.show;
		_.show();
		var hide_notification = function () {
			with (_) if (type == 'notify') hide();
		};
		setTimeout(hide_notification, 2000);
	};
	_.popup_html(m);
	return false;
}


popup_dialog.reloadable_history = [];

// so failed reloadable won’t open whatever was in previously closed dialog
popup_dialog.original_hide = popup_dialog.hide;
popup_dialog.hide = function(){ var _ = popup_dialog;
	$("."+_.content_class).html("");// Empty dialog
	_.original_hide();
}

// options
//    bounce: if true, return to previous url after form submit, otherwise close
//      load: run on dialog content after load & link loads (not form submits)
//    submit: run on dialog content just before form submit (for targetted forms)
popup_dialog.reloadable = function(url, options) { var _ = popup_dialog;
	//window.console.info("Reloadable: "+url);
	if (!_.is_showing()) {
		_.here = undefined;
		_.reloadable_history = [];
	}
	if (_.here && url != _.here) _.reloadable_history.push(_.here);
	_.here = url;
	_.type = 'reloadable';
	if (typeof options == 'boolean')
		options = { bounce: (options ? true : false) };
	else if (typeof options == 'function')
		options = { __load: options };
	else if (typeof options == 'string')
		options = { __style: options };
	else if (typeof options != 'object')
		options = {};

	_.bounce = (options.bounce ? true : false);
	var _error_class = "dialog-error";
	var _empty_rx = new RegExp(/^[ \t\r\n]*$/);
	var could_not_load = function(url){
		//window.console.info("Could not load");
		var writeto = $("."+_.content_class);
		if (!$(writeto).find("."+_error_class).length)
			$(writeto).prepend('<p class="'+_error_class+'"></p>');
		$(writeto).find("."+_error_class).html('Could not load “<a href="'+url+'" target="_blank">'+url+'</a>”.');
	}
	$.fn.reloadable_associate = function(){
		visit_previous_url = function(){
			_.here = undefined;
			var url = _.reloadable_history.pop();
			url ? _.reloadable(url) : _.hide();
		};
		$(this).find('a:not(.'+_error_class+' > a, .plain-display a)').click(function(){
			_.reloadable(this.href, $(this).hasClass("bounce"));
			return false;
		});
		if (options.__submit) $(this).find('form').submit(function(){
			this.__submit = options.__submit;
			var _result = this.__submit();
			this.__submit = undefined;
			return _result;
		});
		$(this).find('form[target]').submit(function(){
			_.original_hide();
			return true;
		});
		$(this).find('form:not([target])').ajaxForm({ iframe: false,
		  beforeSend: function(x){
			_.request_url = this.url+"?"+this.data;
		  },
		  //error: function(x, s, e) { window.console.info("Error: status "+s) },
		  //success: function(d, s) { window,console.info("Success: data "+d+" status "+s) },
		  complete: function(request, status) {
			//window.console.info("Completed: "+request+" and status "+status+", options "+this);
			// handle any response actions here.
			type = request.getResponseHeader('Content-Type');
			response = request.responseText;
			//window.console.info(" type "+type+" text "+response+" xml "+request.responseXML);
			if (false && !type) {
				// application/json encoding makes the jquery form plugin fail in iframe mode on ff3
				notify("No content type from request!");
			}
			else if (response.match(/{[^}]*}/)) {//ie. json //type.match("application/json")) {
				//window.console.info("response "+response);;
				try { response = eval("("+response+")"); }
				catch (e) { /*info("Exception "+e);*/ };
				var _data = response.data ? response.data : undefined;
				if (response.event)
					$(document).trigger(response.event, _data);
				else if (response.action)
					response.action(_data);
				if (_.bounce) {
					//window.console.info("A bounce was requested");
					visit_previous_url();
				}
				else if (response.notification)
					notify(response.notification);
				else	_.hide();
			}
			else {//if (type.match("^text/")) {
				_.popup_html(response);
				if (response.match(_empty_rx)) {
					could_not_load(_.request_url);
				}
				$("."+_.content_class).reloadable_associate();
				if (options.__load) { // !!! may be undesirable in some cases? !!!
					var _t = $("."+_.content_class);
					_t.__load = options.__load;
					setTimeout(function(){ _t.__load();
				        	               _t.__load = undefined },
					           500);
				}
			}
			delete _.request_url;// or empty?
		  }
		});
		$(this).find('[name="Cancel"]').click(function(){
			visit_previous_url();
		});
	};
	$(document.body).addClass("reloadable-loading");
	$("."+_.content_class).load(url, function(response, status){
		$(document.body).removeClass("reloadable-loading");
		//window.console.info("Load: response "+response+" status "+status);
		// some hosts don’t properly return error statuses
		if (!response) status = "error";
		if (!response || response.match(_empty_rx))
			status = "error";
		if (status == "success") {
			// let page know dialog’s changed content
			$(document).trigger('popup-content-changed', this);
			$(this).reloadable_associate();
			if (options.__load) {// “this” will be the content area
				this.__load = options.__load;
				var _t = this;
				//window.console.info("Set up callback");
				setTimeout(function(){ _t.__load();
				                       _t.__load = undefined },
				           500);// run after dialog’s been shown
			}
			//window.console.info("Succeeded with response "+response+" status "+status);
		}
		else if (status == "error") could_not_load(url);
		if (options.__style)
			$("."+_.content_class).attr('style', options.__style);
		else
			$("."+_.content_class).removeAttr('style');
		_.show();
	})
	return false;
}


//inside_alert = function(a){};
window._alert = window.alert;
window.builtin_alert = window.alert;
window.inside_alert = window.alert;

// ie needs these to override the window properties
window.alert = popup_dialog.alert;
window.confirm = popup_dialog.confirm;
window.password = popup_dialog.password;
window.notify = popup_dialog.notify;

// ..& needs this for popup_dialog to be available
window.popup_dialog = popup_dialog;
});
