
function BizProcCoordinator(pageId, baseUrl)
{
	this.pageId = pageId;
	this.baseUrl = baseUrl + '?';
	this.bizProcs = new Array();
	this.inEvent = false;
	this.afterAjaxEventHandlers = new Array();
}

BizProcCoordinator.prototype.addAfterAjaxEventHandler = function(handler) {
    this.afterAjaxEventHandlers.push(handler);
}

BizProcCoordinator.prototype.addBizProc = function(bizProc) {
	this.bizProcs.push(bizProc);
}

BizProcCoordinator.prototype.triggerEvent = function(bizProc, eventInfo) {
	if (this.inEvent) {
		this.lastEvent = [bizProc, eventInfo];
		return; //Blow off event trigger if in an event already!
	}
	this.disabledButtons = new Array();
	if (eventInfo.disableButtons == true) {
		$(".AcBut").each(function(i) {
			if (!this.disabled) {
				bizProcManager.disabledButtons.push(this);
				this.disabled = true;
			}
		});
		$(".AjaxIndi").css("display", "inline");
	}
	this.inEvent = true;
	try {
		var doc = nitobi.xml.createXmlDoc('<ClientEvent />');
		var docEl = doc.documentElement;
		docEl.setAttribute('bizProcId', bizProc == null ? '' : bizProc.id);
		eventInfo.addState(docEl);
		for (var p = 0; p < this.bizProcs.length; p++)
			this.processBizProc(doc, docEl, this.bizProcs[p]);

		return this.sendRequest(doc, eventInfo);
	}
	catch (e) {
	}
}

BizProcCoordinator.prototype.processBizProc = function(doc, docEl, bizProc)
{
	var bizProcEl = doc.createElement('BizProc');
	bizProc.getState(bizProcEl);
	docEl.appendChild(bizProcEl);
}

BizProcCoordinator.prototype.sendRequest = function(doc, eventInfo) {
	//var xhr = new nitobi.ajax.HttpRequest();
	//xhr.handler = this.baseUrl + 'pi=' + this.pageId + '&RequestType=' + doc.documentElement.getAttribute('event');
	//xhr.async = true;
	//xhr.responseType = 'xml';
	//xhr.onPostComplete.subscribe(function(doc) { bizProcManager.processWebResponse(doc.response); if (eventInfo.eventHandler != null) eventInfo.eventHandler(); });
	//var webRespDoc = xhr.post(nitobi.xml.serialize(doc.documentElement));
	$.ajax({ type: "POST",
		url: this.baseUrl + 'pi=' + this.pageId + '&RequestType=' + doc.documentElement.getAttribute('event'),
		data: nitobi.xml.serialize(doc.documentElement),
		processData: false,
		dataType: "xml",
		contentType: "text/xml",
		success: function(doc) { bizProcManager.processWebResponse(doc); if (eventInfo.eventHandler != null) eventInfo.eventHandler(); },
		error: function(a, b, c) { alert("ajax failure!Better Contact Syrinx."); debugger; }
	});
}

BizProcCoordinator.prototype.processWebResponse = function(doc) {
    if (doc.documentElement != null && doc.documentElement.getAttribute("gotoView") != null)
        window.location.href = doc.documentElement.getAttribute("gotoView");
    else {
        try {
            var tempBizProcs = new Array();
            var firstLen = this.bizProcs.length;
            for (var pos = 0; pos < this.bizProcs.length; pos++) {
                var process = true;
                for (var p2 = 0; p2 < tempBizProcs.length; p2++) {
                    if (tempBizProcs[p2] == this.bizProcs[pos]) {
                        process = false;
                        break;
                    }
                }
                if (process) {
                    tempBizProcs.push(this.bizProcs[pos]);
                    var bpid = this.bizProcs[pos].id;
                    this.bizProcs[pos].processControlStates(doc);
                    if (firstLen != this.bizProcs.length) {
                        pos = 0;
                        firstLen = this.bizProcs.length;
                    }
                }
            }
        }
        catch (e) {
        }

        this.inEvent = false;
        for (var i = 0; i < this.disabledButtons.length; i++)
            try { this.disabledButtons[i].disabled = false; } catch (e) { }

        var indEls = doc.selectNodes("//ControlStates/State[@independent = 'true']");
        if (indEls != null)
            for (var i = 0; i < indEls.length; i++) {
            var script = indEls[i].getAttribute("script");
            if (script != null && script != "")
                try { eval(script); } catch (e) { }
        }

        for (var p = 0; p < this.afterAjaxEventHandlers.length; p++)
            try {
            this.afterAjaxEventHandlers[p]();
        } catch (e) {
        }

        $(".AjaxIndi").css("display", "none");

        if (this.lastEvent != null) {
            var l = this.lastEvent;
            this.lastEvent = null;
            this.triggerEvent(l[0], l[1]);
        }
        return (doc.documentElement == null) ? "" : doc.documentElement.getAttribute("curId");
    }
}

function EventInfo(ctlId, eventId, val, eventHandler, disableButtons) {
	this.disableButtons = disableButtons == false ? false : true;
	this.ctlId = ctlId;
	this.eventId = eventId;
	this.val = val;
	this.eventHandler = eventHandler;
}

EventInfo.prototype.addState = function(eventEl)
{
	eventEl.setAttribute('event', this.eventId);
	eventEl.setAttribute('id', this.ctlId);
	if(this.val != null)
	    eventEl.setAttribute('value', this.val);	
}
function ClientBizProc(id)
{
	this.id = id;
	this.ClientControls = new Array();
	bizProcManager.addBizProc(this);
}

ClientBizProc.prototype.addClientControl = function(ctl)
{
	for(var pos = 0; pos < this.ClientControls.length;pos++)
		if(this.ClientControls[pos].id == ctl.id)
		{
			this.ClientControls[pos] = ctl;
			return;
		}
	this.ClientControls[this.ClientControls.length] = ctl;
}

ClientBizProc.prototype.triggerEvent = function(ctlId, eventId, val, eventHandler, disableButtons) {
    try {
        if (ctlId == null)
            ctlId = this.id;
        bizProcManager.triggerEvent(this, new EventInfo(ctlId, eventId, val, eventHandler, disableButtons));
    }
    catch (e) { }
}

ClientBizProc.prototype.getState = function(bizProcEl)
{
	bizProcEl.setAttribute('id', this.id);
	this.insertControlStates(bizProcEl.ownerDocument, bizProcEl);
}

ClientBizProc.prototype.processControlStates = function(doc)
{
	for(var pos = 0; pos < this.ClientControls.length; pos++)
	{
		var clientCtl = this.ClientControls[pos];
		var clientId = clientCtl.id;
		if(clientCtl.dhtmlObj != null)
		{
			if(clientId == null || clientId == '')
				clientId = clientCtl.dhtmlObj.id;
			var stateEl = doc.selectSingleNode("//ControlStates/State[@id = '" + clientId + "']");
			if(stateEl != null && clientCtl.setState != null)
				clientCtl.setState(stateEl);
		}
	}	
}

ClientBizProc.prototype.insertControlStates = function(doc, bizProcEl)
{
	var states = doc.createElement('ControlStates');
	bizProcEl.appendChild(states);
	for(var pos = 0; pos < this.ClientControls.length; pos++)
	{
		var clientCtl = this.ClientControls[pos];
		if(clientCtl.getState != null && clientCtl.dhtmlObj != null)
		{
			var stateEl = doc.createElement('State');
			var clientId = clientCtl.id;
			if(clientId == null || clientId == '')
				clientId = clientCtl.dhtmlObj.id;
			stateEl.setAttribute('id', clientId);
			this.ClientControls[pos].getState(stateEl);
			states.appendChild(stateEl);
		}
	}
}

function ClientControl(dhtmlObj, setStateFun, getStateFun, showBizObjFun, updateBizObjFun)
{
	this.dhtmlObj = dhtmlObj;
	this.setState = setStateFun;
	this.getState = getStateFun;
	this.showBizObj = showBizObjFun;
	this.updateBizObj = updateBizObjFun;
	if(dhtmlObj != null)
	    this.id = dhtmlObj.id;
}


//-----------

function parseUsaDate(date){
debugger;
	return new Date(date.replace(/^(\d+).(\d+).(\d+).(.*)$/,"$3/$1/$2 $4"));
};

function toUsaDate(date){
	if(nitobi.base.DateMath.invalid(date)){
		return "";
	}
	var pz=nitobi.lang.padZeros;
	return pz(date.getMonth()+1)+"-"+pz(date.getDate())+"-"+date.getFullYear();
};

//-----------

function getBizObjFromControl(clientId) {
	var docEl = nitobi.xml.createXmlDoc('<BizObj />').documentElement;
	eval("updateBizObj" + clientId + "(docEl);");
	return docEl;
}
function updateControlFromBizObj(clientId, bizobj) {
	eval("showBizObj" + clientId + "(bizobj);");
}

//-----------

function setComboSelectedRowByKey(combo, key)
{
//debugger;
	var ds =combo.GetList().GetXmlDataSource();
	var numRows = ds.GetNumberRows();
	var setVal = false;
	for(var p = 0; p < numRows; p++)
		if(ds.GetRow(p)[0] == key)
		{
			$ntb(combo.GetId()+'SelectedRowIndex').value = p;
			combo.GetList().SetSelectedRow(p);
			combo.SetTextValue(ds.GetRow(p)[1]);
			setVal = true;
			break;
		}
	if(!setVal)
		combo.SetTextValue(key);
		
}
function getComboSelectedRowKey(combo)
{
    //debugger;
	var fld = $ntb(combo.GetId() + 'SelectedValue0');
    return fld.value;
//	var ds =combo.GetList().GetXmlDataSource();	
//	var index = combo.GetList().GetSelectedRowIndex();
//	if(index == -1)
//		index = window.document.getElementById(combo.GetId()+'SelectedRowIndex').value;
//	var numRows = ds.GetNumberRows();
//	return (index == null || index < 0 || numRows == 0)?null:ds.GetRow(index)[0];
}

function setComboState(stateEl)
{
	var refresh = stateEl.getAttribute('refresh');
	if(refresh != null && this.dhtmlObj.GetMode() != "unbound")
	{
	    var cl = this.dhtmlObj.GetList();
        cl.Clear();
	    cl._syx = this;
	    cl.GetPage(0, 50, null,0, null, function(EBAComboSearchNewRecords,list){
		    //setSelectedRowByKey(list._syx.dhtmlObj,list._syx.lastKey);
	    });
	}
}

function getComboState(stateEl)
{
//	var lastKey = getSelectedRowKey(this.dhtmlObj);
//	if((lastKey == null || lastKey.length == 0) && this.lastKey != null)
//		lastKey = this.lastKey;
//	//stateEl.setAttribute('selected', lastKey);
//	stateEl.setAttribute('selected', this.dhtmlObj.GetList().GetSelectedRowIndex());
}


//-----------------
function setInnerHtmlWithScript(element, html) {
document.getElementById(element).innerHTML=html;

var re = /<script\b[\s\S]*?>([\s\S]*?)<\//ig;
var match;
while (match = re.exec(html)) {
eval(match[1]);
}
};


var globalEval = function globalEval(src) {
    if (window.execScript) {
        window.execScript(src);
        return;
    }
    var fn = function() {
        window.eval.call(window, src);
    };
    fn();
};
