// DataForm Client Script Library
// Alfa-XP, Michael Isipciuc, 2006-2007.
//
Type.registerNamespace("FM");

FM.DataForm= function(element) {
		FM.DataForm.initializeBase(this, [element]);
		// Properties
		this.id= element.getAttribute('id');
		this.tableName= element.getAttribute('tableName');
		this.formName= element.getAttribute('formName');
		this.keyValue= element.getAttribute('keyValue');

		this._Controls= new Array();
		this._controlList= new Array();
    // Variables
    this._tabBar= null;

    this._service= null;
    this.RefreshHnd= null;
    FM.DataForm._current= this;
}

FM.DataForm.prototype= {

  initialize : function() {
		FM.DataForm.callBaseMethod(this, 'initialize');

		var o;
		var hasBinding= false;
		var inputs= this.get_element().getElementsByTagName('INPUT');
		for (var i= 0; i < inputs.length; i++) {
			if (inputs[i].getAttribute('context') != "form") continue;
			o= FM.DataForm._CreateControl(inputs[i], this);
			if (o) {
				this.RegisterControl(o.Name, o);
				if (o._bindings) hasBinding= true;
			}
		}
		
		if (hasBinding) FM.DataForm._RegisterObservers(this);
		//this.initForm();
  },

  initForm : function(bFocus) {
		var o= this.get_element();

		o.focus();

		// init tabs
		var tabRow= o.rows[0];
		if (tabRow.id == "formDesc") tabRow= o.rows[1];
		if (tabRow.id == "tabRow") { // if has tabs menu
			this._tabBar= $create(FM.UI.TabBar, null, null, null, tabRow.cells[0].firstChild);
			this._tabBar.onAfterChange= Function.createDelegate(this, this.setFocus);
			this._tabBar.load();
		} else {
			this.setFocus(null); // single hidden tab
		}

		this.onload_script= o.getAttribute('onload_script');
		this.onsave_script= o.getAttribute('onsave_script');
		this.fireOnLoadEvent();
  },

  dispose : function() {
		if (this._controlList != null) {
			for (var i= 0; i < this._controlList.length; i++) this._controlList[i].dispose();
			this._controlList= null;
		}
		if (this._tabBar != null) {
			this._tabBar.dispose();
			this._tabBar= null;
		}
    FM.DataForm.callBaseMethod(this, 'dispose');
  },

  RegisterControl : function(name, control) {
		this._Controls[name]= control;
		this._controlList.push(control);
  },

  focus : function() {
		if (this._tabBar) this._tabBar.focus();
		else this.setFocus(null);
  },
	focusElement : function() { this.get_element().focus(); },

	IsDataChanged : function() {
		var o;
		if (this._controlList) {
			for (var i= 0; i < this._controlList.length; i++) {
				o= this._controlList[i];
				if (o.IsChanged()) {window.status= o.Name + " is changed"; return true;}
			}
		}
		return false;
	},

	buildXml: function(raiseMessage) {
		if (raiseMessage == null) raiseMessage= true;
		var s= new Sys.StringBuilder();
		var o, xns;
		var isNew= (this.keyValue == "");
		for (var i= 0; i < this._controlList.length; i++) {
			o= this._controlList[i];
			xns= o.ConvertToXml(raiseMessage, isNew);
			if (xns == null) return null;
			if (xns.length > 0) s.appendLine(xns);
		}
		//alert(s.toString());
		return s.toString();
	},

	Reset: function() {
		for (var i= 0; i < this._controlList.length; i++) {
			this._controlList[i].resetValue();
		}
	},
	
	Refresh : function() { if (this.RefreshHnd) this.RefreshHnd(); },

  showInfo : function(o) {
		alert("Name: " + o.Name + "\n\n\n" + "defaultValue:" + o.defaultValue + "\nValue:" + o.getValue() + "\nIsRequired:" + o.IsRequired);
  },

	setFocus : function(sTabId) {
		var o;
		for (var i= 0; i < this._controlList.length; i++) {
			o= this._controlList[i];
			if ((sTabId == null || o.tabID == sTabId) && o.canFocus())	{ o.focus(); break; }
		}
	},

	showTab : function(sTabId) {
		if (this._tabBar) this._tabBar.showTab(sTabId);
	},

	fireOnLoadEvent : function() {
		if (this.onload_script) try { eval(this.onload_script); } catch (e) { alert("The form OnLoad script has been failed.\n\n\n" + e.description); }
	},

	fireOnBeforeSaveEvent : function() {
		var saveRes= true;
		if (this.onsave_script) try { saveRes= eval('this.onsave_f= function() {' + this.onsave_script + '};this.onsave_f();'); } catch (e) { alert("The form OnSave script has been failed.\n\n\n" + e.description); saveRes= false; }
		return saveRes;
	},
	
	getTabIndex : function() { return (this._tabBar) ? this._tabBar.selectedIndex : 0;},
	
	// programming utils
	$get : function(name) { return this._Controls[name]; },  
  getValue : function(name) { var o= this._Controls[name]; return (o) ? o.getValue() : ""; },
  setValue : function(name, val) { var o= this._Controls[name]; if (o) o.setValue(val); },
  
  GetControlByName : function(name) { return this._Controls[name]; },
  GetValueByName : function(name) { var o= this._Controls[name]; return (o) ? o.getValue() : ""; },
  IsCreateMode : function() { return (this.keyValue == ""); }
}

FM.DataForm.inheritsFrom(Sys.UI.Control);
FM.DataForm.registerClass('FM.DataForm', Sys.UI.Control);

FM.DataForm.getCurrent= function() { return FM.DataForm._current; }
//
//

FM.DataForm._CreateControl= function(input, hostForm) {
	if (!input) return null;
	var strctype= input.getAttribute('ctype');
	if (!strctype) return null;
	var ctype= null;
	switch (strctype) {
		case "FM.UI.TextControl": ctype= FM.UI.TextControl; break;
		case "FM.UI.TextareaControl": ctype= FM.UI.TextareaControl; break;
		case "FM.UI.TemplateControl": ctype= FM.UI.TemplateControl; break;
		case "FM.UI.ACTextControl": ctype= FM.UI.ACTextControl; break;
		case "FM.UI.BooleanControl": ctype= FM.UI.BooleanControl; break;
		case "FM.UI.BooleanRadioControl": ctype= FM.UI.BooleanRadioControl; break;
		case "FM.UI.DateTimeControl": ctype= FM.UI.DateTimeControl; break;
		case "FM.UI.EditableGridControl": ctype= FM.UI.EditableGridControl; break;
		case "FM.UI.LookupControl": ctype= FM.UI.LookupControl; break;
		case "FM.UI.PicklistControl": ctype= FM.UI.PicklistControl; break;
		case "FM.UI.RadiolistControl": ctype= FM.UI.RadiolistControl; break;
		case "FM.UI.NumberControl": ctype= FM.UI.NumberControl; break;
		case "FM.UI.HtmlControl": ctype= FM.UI.HtmlControl; break;
		case "FM.UI.FileControl": ctype= FM.UI.FileControl; break;
		default:
			ctype= window.eval(strctype);
			if (typeof(ctype) == 'undefined') { alert('Control type "' + strctype + '" not defined.'); return null; }
			break;
	}
	input.id= "fmc_" + FM.DataForm._uniqueID++;
	//return $create(ctype, null, null, null, input);
	var o= new ctype(input); 
	o._hostForm= hostForm;
	o.initialize();
	return o;
}

FM.DataForm._RegisterObservers= function(hostForm) {
	var o, b, controller;
	for (var i= 0; i < hostForm._controlList.length; i++) {
		o= hostForm._controlList[i];
		if (o._bindings) {
			for (var j= 0; j < o._bindings.length; j++) {
				b= o._bindings[j];
				controller= hostForm.$get(b.From);
				if (controller && FM.UI.IObserver.isImplementedBy(o)) {
					controller.AddObserver(Function.createDelegate(o, o.Controller_HandleEvent));
					o.Controller_HandleEvent(true);// call function on form load.
				}
			}
		}
	}
},

FM.DataForm._ResolveBindings= function(hostForm, bindings, refControl) {
	var filter= "";
	var b, o, val; 
	var bEnabled= true;
	for (var j= 0; j < bindings.length; j++) {
		b= bindings[j];
		o= hostForm.$get(b.From);
		if (!o) continue;
		if (filter != "") filter+= ",";
		val= o.getValue();
		if (val == "") { bEnabled= false; continue; }
		filter+= b.To + ":" + val;
	}
	if (refControl && !refControl.Readonly) refControl.set_enabled(bEnabled);
	return filter;
},



FM.DataForm._uniqueID= 100;

fmQuickDesignForm= function(t, f) {
	var url= fmCommonPath + "../Explorer/FormBuilder/Designer.aspx?t=" + t + "&f=" + f;
	openStdWin(url, "FormBuilder", 820, 550);
}

//
Type.registerNamespace("FM.Utils");
FM.Utils.GetRecordInfo= function(lookupTable, filter, columns) {
	var params= "lookupTable=" + lookupTable + "&columns=" + columns + "&filter=" + escape(filter);
	var url= fmDataViewerPath + "Form/Lookup/Resolver.aspx?" + params;
	//alert(Server_ReceiveData(url, false));return;
	var xn= Server_ReceiveData(url, true).documentElement;
	var a= [];
	if (xn.nodeName == "error") { alert(xn.text); return a; }
	var xnCell, c;
	var aColumns= columns.split(",");
	for (var i= 0; i < aColumns.length; i++) {
		c= aColumns[i];
		xnCell= xn.selectSingleNode(c);
		a[c]= (xnCell != null) ? xnCell.text : "";
	}
	return a;
}

FM.Utils.GetDataByCommand= function(provider, cmd, vars) {
	var qs= "provider=" + provider + "&cmd=" + cmd + "&params=" + escape(vars);
	var url= fmDataViewerPath + "Form/Lookup/Resolver.aspx?" + qs;
	var xn= Server_ReceiveData(url, true).documentElement;
	var a= []; a['returnValue']= '';
	if (xn.nodeName == "error") { alert('Error occured during processing the command on the server\n\nProvider: ' + provider + '\nCommand: ' + cmd + '\n\n\n' + xn.text); return a; }
	var xns= xn.childNodes;
	for (var i= 0; i < xns.length; i++) a[xns[i].nodeName]= xns[i].text;
	return a;
}

// FM.UI.TabBar
//
FM.UI.TabBar= function(element) {
		FM.UI.TabBar.initializeBase(this, [element]);
		var sIndex= element.getAttribute("selectedIndex");
		this.selectedIndex= (sIndex != null) ? parseInt(sIndex): 0
		this._context= null;
		this._oTab= null;
		// Events
		this.onBeforeChange= null;
		this.onAfterChange= null;
}

FM.UI.TabBar.prototype= {

  initialize : function() {
		FM.UI.TabBar.callBaseMethod(this, 'initialize');
		var o= this.get_element();
		$addHandlers(o, {
			'click': this.down,
			'mouseover': this.on,
			'mouseout': this.off,
			'keyup': this.keyPress
		}, this);

  },

  dispose : function() {
		if (this.get_element() != null) $clearHandlers(this.get_element());
		
    FM.UI.TabBar.callBaseMethod(this, 'dispose');
  },
 
	load : function() {
		var o= this.get_element();
		this._context= o.parentNode.parentNode.nextSibling.firstChild.firstChild;
		//if (this.id != "tabBar" && this.id != "") this._context= window.document;
		
		this.hrGlowTab= o.nextSibling;
		this.hrSelectedTab= o.nextSibling.nextSibling;
		
		this.down(null, o.childNodes[this.selectedIndex], true);
	},

	keyPress : function(e) {
		// Handle ENTER Key
		if (e.keyCode == 13) e.target.click();
	},

	down : function(e, oTab, bForce) {
		if (oTab == null && e == null) return;
		var o= (oTab) ? oTab : e.target;
		if (o.className == "tab" || !this._oTab)	{
			this.hrGlowTab.style.display= "none";

			this.selectedIndex= parseInt(o.getAttribute('index'));
			
			if (this.onBeforeChange) {
				if (!this.onBeforeChange(o.getAttribute('tabID'))) return;
			}

			o.className = "tab tabOn";
			this.show(this.hrSelectedTab, o);

			var tab= $get(o.getAttribute('tabID'), this._context);
			if (tab != null) tab.style.display= "block";
			if (this._oTab) {
				this._oTab.className= "tab";
				tab= $get(this._oTab.getAttribute('tabID'), this._context);
				if (tab != null) tab.style.display = "none";
			}

			this._oTab= o;

			//eventAfterChange.fire(oEvent);
			if (this.onAfterChange) this.onAfterChange(o.getAttribute('tabID'));
		}
	},

	on : function(e) {
		this.show(this.hrGlowTab, e.target);
	},

	off : function(e) {
		if (!this.hrGlowTab) return;
		this.hrGlowTab.style.display= "none";
	},

	show : function(oShow, o) {
		if (o.tagName != "SPAN") return;
		try {
			with (oShow.style) {
				left	= o.offsetLeft + 1 + 'px';
				top		= o.offsetTop - 1 + 'px';
				width	= o.offsetWidth - 2 + 'px';
				display = "inline";
			}
		} catch(e) {
		}
	},
	
	focus : function() {
		this._oTab.focus();
	},
	
	showTab : function(tabID) {
		var s= tabID.substring(3);
		if (s != ("" + this.selectedIndex)) {
			this.down(null, this.get_element().childNodes[parseInt(s, 10)], true);
		}
	}
}

FM.UI.TabBar.inheritsFrom(Sys.UI.Control);
FM.UI.TabBar.registerClass('FM.UI.TabBar', Sys.UI.Control);

Sys.Application.notifyScriptLoaded();

fmRefreshForm= function() {
	if (FM.DataForm._current) FM.DataForm._current.Refresh();
}

if (Sys.Browser.agent == Sys.Browser.Firefox) {
	document.forms[0].onsubmit= function() { return false; }
}