
var SOUND = {};
SOUND.click = function() {};
SOUND.error = function() {};


GBS.ui = { VERSION: 1.1 };

GBS.ui.wm = new YAHOO.widget.OverlayManager(); 
GBS.ui.destroyTimeout = 500;	// the timeout for a destroy after a dialog is cancelled

GBS.activateWidgets = GBS.util.activateWidgets;

GBS.util.prompt = function(msg, op){

	return new GBS.util.Prompt(msg, op);

}
GBS.util.Prompt = function(msg, op){
// var d = GBS.ui.makeDialog(); 

 var d = new GBS.ui.Dialog({modal: true, fixedcenter: true}); 
 var opts = op;
 var handlers = [];

try {
 d.setHeader('Prompt:'); // + GBS.util.randomNumber(0, 900));
 var b = document.createElement('div');
b.innerHTML = "<h1>" + msg + "</h1>";

 var f = document.createElement('div');
//dom.addClass("button-group", f);
f.className = "button-group";
f.style.textAlign='center';
f.style.fontSize = '2.0em';
 if(opts) for(var n=0;n<opts.length;n++){
    
    handlers[n] = opts[n];

 var bb = document.createElement('button');
 bb.innerHTML = opts[n].label;

f.appendChild(bb);
YAHOO.util.Event.addListener(bb, "click", function(evt ,obj){ 
  obj.option.onSelect();
  obj.dialog.cancel();
},{ 
    option: opts[n],
    dialog: d
});
}

b.appendChild(f);
d.setBody(b);
//d.setFooter(f);

d.show();

} catch(err){
  d.setHeader("Error");
  d.setBody(err);
}
d.show();
 return d;
};


/*
EDITOR.freedrag = {};

EDITOR.freedrag.Instance = function(id, sGroup, config) {
    EDITOR.freedrag.Instance.superclass.constructor.apply(this, arguments);
};
*/
GBS.ui.freedrag = {};

GBS.ui.freedrag.Instance = function(id, sGroup, config) {
    GBS.ui.freedrag.Instance.superclass.constructor.apply(this, arguments);
};

YAHOO.extend(GBS.ui.freedrag.Instance, YAHOO.util.DD, {
    origZ: 0,

    startDrag: function(x, y) {
        YAHOO.log(this.id + " startDrag", "info", "example");

        var style = this.getEl().style;

        // store the original z-index
        this.origZ = style.zIndex;

        // The z-index needs to be set very high so the element will indeed be on top
        style.zIndex = 999;
    },

    endDrag: function(e) {
        YAHOO.log(this.id + " endDrag", "info", "example");

	var ele = this.getEl();

        // restore the original z-index
        ele.style.zIndex = this.origZ;
   	

	var q = YAHOO.util.Selector.query;

	var x_input = q('.free-drag-x', this.getEl());
	if(x_input.length>0) {
		x_input[0].value = ele.style.top.substr(0, ele.style.top.length-2);
	}

	var y_input = q('.free-drag-y', this.getEl());
	if(y_input.length>0) {
		y_input[0].value = ele.style.left.substr(0, ele.style.left.length-2);
	}


   }
});




GBS.ui.dialogStyles = {

	'blank': {
		position: 'absolute',
		constraintoviewport: true
	},
	'warning': { 
		width: '200px'
	},
	'prompt': { 
		width: '300px',
		modal: true 
	},
	'alert': { 
		visible: false,
		modal: false,
		close: false,
		effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}
	},
	'default': {
		modal: false, 
		position: 'absolute',
		constraintoviewport: true,
		width: '550px', 
		visible: false,
		iframe: true
	},
	'fancy': {
		modal: false, 
		position: 'absolute', 
		width: '600px', 
		visible: false,
		effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}
	}
}

GBS.ui.redraw = function(){
		
	var ssrc = {
		'leftnav-recordset': 155,
		'tableintabs': 225,
		'narrativegoalslisting': 159,
		'tabcontent': 200,
		'tabcontent-table': 251,
		'tabsubcontent': 188,
		'leftcol30': 38,
		'leftcol30list': 64,
		'leftcol30buttonlist': 89,
		'rightcol70': 38,
		'full': 0,
		'left-col-resize': 83
	};
	
	var src = {
		'.leftnav-recordset .tbd': 135,
		'.leftnav-recordset .tree': 70,
		'.ah-left-col-resize': 70

	};
	var anims = [];
	var sel = YAHOO.util.Selector;
	try {
	    var h = dom.getViewportHeight();
	
	    for(x in src){
		//console.log(x + " - " + src[x]);
		var tabs = sel.query('#application ' + x);
		
		for(var n=0; n<tabs.length; n++){
		    //console.log(tabs[n]);
		    tabs[n].style.height = (h - parseInt(src[x])) + 'px';
		}
	    }
	} catch(err){

	}
	//console.log("done");


}

YAHOO.util.Event.addListener(window, 'resize', GBS.ui.redraw);

GBS.ui.Dialog = function(args){

	//alert('GBS.ui.Dialog dbroken!');
	//return null;

	var d = GBS.ui.makeDialog(undefined, 'blank');
try{
	if(typeof(args)=="object"){
                for(x in args){
			d.cfg.queueProperty(x, args[x]);
         	}
	}
} catch(err){
console.error(err);
}

	//io.log	(d);
	this.setBody = function(x){
		d.setBody(x);
		
		GBS.activateWidgets(d.body);
		
	}
	this.setHeader = function(x){
		d.setHeader(x);	
	}
	this.setFooter = function(v){
		d.setFooter(v);
	}
	this.show = function(){
		
		d.show();
		d.center();
	}
	this.hide = function(){
		d.hide();;
	}
	this.cancel = function(){
		d.cancel();
	}	
	this.destroy = function(){
		d.destroy();
	}
	this.dialog = d;
	d.setBody("Loading");
	d.setHeader("Loading");
	
	d.render(document.body);
	
	return this;
}



GBS.ui.makeDialog = function(dialog_id, style){
	
	if(dialog_id==undefined) var dialog_id = GBS.Dom.generateId();
	if(style==undefined) var style = GBS.ui.dialogStyles['default'];
	else  var style = GBS.ui.dialogStyles[style];
	
	var dialog = new YAHOO.widget.Dialog(dialog_id, style);
	
	GBS.ui.wm.register(dialog);
	
	var canceled = function(evt, obj){
		SOUND.click();
		clearTimeout(this.heartbeat);
		
		//EDITOR.clearLock(this.id);
		
		var me = this;
		
		if(document.body.style.overflow=='hidden'){
			document.body.style.overflow = 'auto';	
		}
		setTimeout(function(){ me.destroy();   }, GBS.ui.destroyTimeout);
	}
	
	var submitted = function(){
	//	alert("submit");
	}
	var validate = function(){
		//alert("validating");	
	}
	//dialog.asyncSubmitEvent.subscribe(submitted);
	//dialog.beforeSubmitEvent.subscribe(validate);
	
	dialog.cancelEvent.subscribe(canceled, dialog);
	return dialog;
}




GBS.ui._realWindows = false;
GBS.ui.form = function(url, args, callback){
	
	SOUND.click();
	//var me = this;
	var dialog_id = GBS.Dom.generateId();
	
	var t = new String(url);
	//alert(t.indexOf('?'));
	if(t.indexOf('?')>=0){
		url += '&dialog_id='+dialog_id;
	} else {
		url += '?dialog_id='+dialog_id;
	}

	// add compatibilit ylayer to support regular popup windows
	if(this._realWindows) {
		var w = window.open(url,dialog_id,'toolbars=false');
		return;
	}
	
	var dialog = GBS.ui.makeDialog(dialog_id);
	dialog.autoCenter = true;
	
	// don't do it if it's ie
	if(YAHOO.env.ua.ie){
		var w = YAHOO.util.Dom.getViewportWidth() - 100;
		dialog.cfg.queueProperty('width', w + 'px');
	} else {
		if(typeof(args)=="object"){
			for(x in args){
				dialog.cfg.queueProperty(x, args[x]);
				//io.log('queued property for dialog:' + x + ': ' + args[x]);
			}
		}
	}
	
	io.log('opening: ' + url);	
	// we want to create a new dialog to load our data into, never re-use a dialog
	var submitted = function(d, x){
		SOUND.click();
	}
	
	var validate = function(){
		this.callback.success = function(d){
			if(d.getResponseHeader['Content-Type']=='text/json'){
				var o = YAHOO.lang.JSON.parse(d.responseText);
				io.log(o);
				//alert('we got text/json response');
				
				GBS.util.runCMD(o);
				
				io.log('killing the dialog');
				dialog.destroy();
				return;
				
			} 
			
			dialog.destroy();
		}
		//var me = this;
		//io.log('validating ' + me.parent);	
	}
	//validate.parent = me;

	var cb = {
	success: function(d){

		//alert(d.getResponseHeader['Content-Type']);
		switch(d.getResponseHeader['Content-Type']){
			case("text/json"):
				GBS.util.parseResponse(d);
				dialog.hide();
				return;
			break;
			default:
                }

		if(d.getResponseHeader['dialog-style']){
			var style = d.getResponseHeader['dialog-style'];
			var args = EDITOR.util.dialogStyles[style];
				
			for(x in args){
				dialog.cfg.queueProperty(x, args[x]);
				io.log('queued property for dialog:' + x + ': ' + args[x]);
			}
		}
		//SOUND.say(d.getResponseHeader['Title']);
		dialog.setHeader("" + d.getResponseHeader['Title']);
		
		dialog.setBody(d.responseText);			
		
		var forms = YAHOO.util.Selector.query('form', dialog.body);
		if(forms.length>0){
			for(var fx=0;fx<forms.length; fx++){
				if(forms[fx].name=='dlgForm'){
					var submitButtons = YAHOO.util.Selector.query('.submit-button', forms[fx]);
					YAHOO.util.Event.addListener(submitButtons, 'click', GBS.submitForm, forms[fx]);
				}
			}
		}
		var cbs = YAHOO.util.Selector.query('.cancel-button', dialog.body)
		YAHOO.util.Event.addListener(cbs, 'click', function(evt, d){ io.log(dialog); dialog.cancel() }, dialog)
					
		var rbs = YAHOO.util.Selector.query('.refresh-button', dialog.body)
		YAHOO.util.Event.addListener(rbs, 'click', function(evt, d){ io.log(dialog); dialog.refresh() }, dialog)
			
		// check for any tabsets in teh dialog
		/*
		var tabSets = YAHOO.util.Selector.query('.yui-navset', dialog.body)
		if(tabSets.length>0){
			//io.log('we have a tabset' + tabSets[0].id);	
			dialog.tabs = new YAHOO.widget.TabView(tabSets[0].id); 
		}
		var freedrag = YAHOO.util.Selector.query('.free-drag', dialog.body)
			
		//io.log(freedrag);
		if(freedrag.length>0){
			for(var n=0; n<freedrag.length; n++){
				io.log('we have a freedrag item' + freedrag[0]);	
				new YAHOO.util.DD(freedrag[n].id); 
			}
		}
		*/
		// subscribe to the submit event to validate
		dialog.asyncSubmitEvent.subscribe(submitted);
		dialog.beforeSubmitEvent.subscribe(validate);
		dialog.registerForm();
		dialog.render();
		dialog.show();
		
		GBS.util.activateWidgets(dialog.body);

		if(dialog.autoCenter) {
			dialog.center();
			dialog.focus();
		}
		dialog.autoCenter=false;
			
		if(d.argument.args!=undefined){
			if(d.argument.args.onComplete!=undefined){
				d.argument.args.onComplete();	
			}
		}

		if(d.argument.callback!=undefined){
			//alert('cutom callback for loading');
			switch(typeof(d.argument.callback)){
				case("function"):	d.argument.callback();
				break;
				default:			io.log('unsupported callback type: '+ typeof(d.argument.callback));
			}
		}
			
		try{
			if(d.getResponseHeader['onLoad']!=undefined){
				eval(d.getResponseHeader['onLoad']+'()');
			}
		} catch(err){
			io.error(err);	
		}
	},
	failure: function(d){
		dialog.setHeader(d.statusText);
		dialog.setBody("Status: " + d.status);
		dialog.show();
	},
	argument: {
		dialog: dialog,
		args: args,
		callback: callback}
	}
	dialog.refresh = function(d){
				
		this.url = url;
		dialog.setBody('<img src=images/loading.gif alt="Reloading..." />');
		try {
			if(this.tabs){
				io.log(this.tabs);
			}
		} catch(err){
			io.error(err);	
		}
		var c = YAHOO.util.Connect.asyncRequest('GET',url, cb);
		io.log(url);
	}
	
	


	dialog.toggle = function(){

		//alert('dialog is: ' + this.windowState);
		switch(this.windowState){
			case("maximized"):
				
				this.restore();
			
			break;
			default:
			case("minimized"):
				this.expand();
				this.maximize();
			break;
			
		}
	}
	
	
	dialog.collapsed = false;
	dialog.expand = function(){
		this.body.style.display = 'block';
		this.collapsed = false;
		
		this.cfg.queueProperty('width', '800px');
		this.render();
		
		this.center();
		//EDITOR.util.slideTo(this.id, this.prevXY, 1);
			
		this.toggle_button.className = 'container-toggle-button';
	}
	dialog.collapse = function(){
	
		if(this.collapsed){
			this.expand();
		} else {
			this.body.style.display = 'none';
			
			
			this.cfg.queueProperty('width', '200px');
			this.render();
			this.moveTo(0,dom.getViewportHeight()-25);
			//EDITOR.util.slideTo(this.id, [0,dom.getViewportHeight()-25], .5);
			
			this.toggle_button.className = 'container-toggle-button-collapsed';
			this.collapsed = true;
		}
	}
	dialog.restore = function(){
		if(this.windowState!="maximized") return;
		this.windowState = "";
		this.max_button.className = 'container-maximize-button';
		
		document.body.style.overflow = 'auto';
		io.log(this.prevWidth);
		//io.log(this.prevHeight);
		
		this.cfg.queueProperty('width', this.prevWidth);
		this.cfg.queueProperty('height', 'auto');
		this.cfg.queueProperty('underlay', 'shadow');
		this.cfg.queueProperty('draggable', true);
		this.render();
		
		this.moveTo(this.prevXY[0], this.prevXY[1]);
		
		
		
		//this.prevWidth = false;
		this.prevHeight = false;
		this.prevXY = false;
	}
	
	dialog.maximize = function(arg){
		
		
		if(typeof(arg)=="object"){
			if(arg.force){
			
				var h = dom.getViewportHeight();
				var w = dom.getViewportWidth();
				this.cfg.queueProperty('height', h + 'px');
				this.cfg.queueProperty('width', w + 'px');
				this.render();
				this.moveTo(0,0);
				
			}
		}
		
		if(this.collapsed) this.expand();
		if(this.windowState=='maximized') return;
		
		
		this.windowState = "maximized";
		this.max_button.className = 'container-maximize-button-active';
		
		this.prevWidth = this.cfg.config.width.value;
		this.prevHeight = this.cfg.config.height.value;
		this.prevXY = this.cfg.config.xy.value;
	
		var h = dom.getViewportHeight();
		var w = dom.getViewportWidth();
		document.body.style.overflow = 'hidden';
		
		this.header.style.cursor = 'pointer';
	
		this.cfg.queueProperty('height', h + 'px');
		this.cfg.queueProperty('width', w + 'px');
		this.cfg.queueProperty('underlay', 'none');
		this.cfg.queueProperty('draggable', false);
		
		this.render();
		this.moveTo(0,0);
		
		EDITOR.updateUI();
		
	
	}
	
	
	
	dialog.loadUrl = function(url){
		
		var c = YAHOO.util.Connect.asyncRequest('GET',url, cb);
		io.log(url);
	}
	var c = YAHOO.util.Connect.asyncRequest('GET',url, cb);
	dialog.poll = function(){
		io.log('polling ' + this.url);
		this.refresh();	
	}
	if(typeof(args)=="object"){
		if(args.autoRefresh){
			
			io.log(this.id + ' boing:' + args.autoRefresh);
			dialog.heartbeat = setInterval(function(){ dialog.poll(dialog) }, args.autoRefresh);
			
		}
	}
	
	dialog.setHeader('Loading...');
	dialog.setBody('<img src="images/loading.gif" />');
	dialog.render(document.body);
	dialog.show();
	dialog.center();
	
	// add some window commands
		/*
	this.max_button = document.createElement('div');
	this.max_button.innerHTML = '';
	this.max_button.className = 'container-max';
	dialog.element.firstChild.appendChild(this.max_button);
	*/
	this.windowControls = false;
	
	if(args!=undefined){
		if(args.close == false){
			this.windowControls = false;		
		}
	}
	
	if(this.windowControls){
		dialog.max_button = document.createElement('div');
		dialog.max_button.innerHTML = '';
		dialog.max_button.className = 'container-maximize-button';
		dialog.element.firstChild.appendChild(dialog.max_button);
	
		dialog.toggle_button = document.createElement('div');
		dialog.toggle_button.innerHTML = '';
		dialog.toggle_button.className = 'container-toggle-button';
		dialog.element.firstChild.appendChild(dialog.toggle_button);
	
	
		YAHOO.util.Event.addListener(dialog.toggle_button, 'click', dialog.collapse, {},dialog);
		YAHOO.util.Event.addListener(dialog.max_button, 'click', dialog.toggle, {},dialog);
		
		io.log(dialog);
		
		YAHOO.util.Event.addListener(dialog.header, 'dblclick', dialog.toggle, {}, dialog);
	}
	
	
	// try and load the form
	//UI.dialog(form, { getString: args });
	return dialog;
}


GBS.ui.codeViewScrolled = function(textField,lineNumberDisplay) {

	//var text = tf.value.replace(/\s+$/g,"")
	//var split = text.split("\n")
	//var num_lines = split.length;

	//lnf.value = 'x'
    try {
	lineNumberDisplay.style.top= (-1*textField.scrollTop) + "px";
    } catch(err){
	
    }
}


GBS.ui.contentChanged = function(textField){

    // Here we need to do something relevant...
    // undos perhaps, don't allow the user to navigate away before clearing edit lock...

    /*
    // count the number of lines in each of the items
    var t1= textField.value.replace(/\s+$/g,"")
    var s1= t1.split("\n")
    var tf_num_lines = s1.length;
    
    var t2= textField.value.replace(/\s+$/g,"")
    var s2= t2.split("\n")
    var lnf_num_lines = s2.length;
    
    lineNumberDisplay.value ='';
    
    tf_num_lines+= 10
    var t = '';
    for(var n=0; n<tf_num_lines; n++){
	t = t + (n+1) + '<br />';
    }
    lineNumberDisplay.innerHTML= t;
    */
}