// Profile Client Script Library
// Alfa-XP, Michael Isipciuc, 2007.
//



FM.Profile= function(hostWindow) {
	FM.Profile._current= this;
	this.Window= hostWindow;
	this.Name= null;
	this.GroupName= "";
	this.HandleByGroup= true;
	//
	this._service= FM._ResourceLoader.getResourceLoaderService();
	this._splitterBehavior= null;
	this._tree= null;
	this._panel= null;
	this.InputParameters= "";


	this.onProfileLoadedDelegate= Function.createDelegate(this, this.onProfileLoaded)
	this.onLoadCompleteDelegate= null;
	this._Result= null;
	this.currentControl= null;
	this._counting= null;
	this.refreshCountingOnChange= null;

	//this.Window.onBeforeClose= Function.createDelegate(this, this.onBeforeClose);
	this._onGridRefreshDlg= Function.createDelegate(this, this.onGridRefresh);

	this.WindowID= hostWindow.ID;
	this.loadWithTransitional= true;

	hostWindow.Profile= this;
}

FM.Profile.prototype= {

	dispose : function() {
		this.disposeControls();

		FM.Profile._current= null;
	},

	disposeControls : function() {
		if (this._tree) { this._tree.dispose(); this._tree= null; }
		if (this.currentControl) {this.currentControl.dispose(); this.currentControl= null; }
		if (this._panelWindow) {this._panelWindow.dispose(); this._panelWindow= null; }
		if (this._counting) { this._counting.dispose(); this._counting= null; }
		if (this._splitterBehavior) { this._splitterBehavior.dispose(); this._splitterBehavior= null; }
		this.isInitialized= null;
	},

	LoadContainer : function(profileName) {
		if (profileName != null) this.Name= profileName;

		this.prepareProgress(fmres("prf_loading", "The profile is loading ..."));
		this._service.Profile_LoadContainer(this.Name, this.GroupName, this.HandleByGroup, this.WindowID, this.InputParameters, this.onServiceComplete, this.onServiceFailed, this);
	},

  onServiceComplete : function(result, element) {
		if (result) {
			element._Result= result;
			FM._ResourceLoader.getCurrent().Register(element._Result.Resources, element._Result.InlineScript, element.onProfileLoadedDelegate);
		} else {
			element.hideProgress();
		}
	},

	onProfileLoaded : function() {
		this.disposeControls();

		this.Window.SetContent(this._Result);
		this.profileTopBtns= this._Result.TopBtns;
		this._Result= null;
		var htmlTable= this.Window.GetBodyElement().firstChild;
		if (htmlTable.tagName != "TABLE") { // ERROR MESSAGE
			//this.Window.Show();
			this.hideProgress();
			return;
		}
		if (this.GroupName == "") this.GroupName= htmlTable.getAttribute('group');
		var leftPanel= htmlTable.rows[0].cells[0];
		var splitter= htmlTable.rows[0].cells[1];
		var rightPanel= htmlTable.rows[0].cells[2];
		var treeRowIndex= 1;
		var htmlTree= leftPanel.firstChild.rows[treeRowIndex].cells[0].firstChild;

		// CREATE TREE
		this._tree= $create(FM.UI.Tree, null, null, null, htmlTree);

		this.hideProgress();

		this._panel= rightPanel.firstChild.rows[0].cells[0];
		this._panelWindow= new window.parent.FM.SimpleWindow(this._panel, this.Window);

		this._tree.add_onSelect(Function.createDelegate(this, this.OnSelectTreetNode));
		this._tree.raiseOnSelect();
		this._tree.add_onBeforeSelect(Function.createDelegate(this, this.OnBeforeSelectTreetNode));

		// CREATE SPLITTER BEHAVIOR

		this._splitterBehavior= new FM.UI.SplitterBehavior(htmlTable, leftPanel, splitter, rightPanel);

		var refreshSec= parseInt(htmlTable.getAttribute('refreshSec'));
		this._counting= new FM.ProfileCounting(this._tree, this.Name, this.GroupName, true, refreshSec, htmlTable.getAttribute('refreshOnChange'), this.InputParameters);
		this.cacheMode= htmlTable.getAttribute('cacheMode');
	},

	OnBeforeSelectTreetNode : function(treeNode) {
		if (treeNode == null) return true;
		if (this.currentControl && this.currentControl.IsFormContainer) {
			if (!this.currentControl.IsValidContent()) {
				return false;
			}
			this.currentControl.dispose(); this.currentControl= null;
		}
		return true;
	},

	OnSelectTreetNode : function(treeNode) {
		if (treeNode == null) return;
		if (this.currentControl) {this.currentControl.dispose(); this.currentControl= null; }
			
		FM.Profile.InitTreeNode(treeNode);
		this._currentNode= treeNode;
		this.Load(this._currentNode);

		if (this.cacheMode == "Cookies") this.createCookie("PROFILE_" + this.Name, treeNode.ID, 5);
		//Profile_ResetFolderByID(f.ID);
	},

	Load : function(profileNode) {
		if (!profileNode) return;
		if (this.currentControl != null) { this.currentControl.dispose(); this.currentControl= null; }
		var id= profileNode.ID;
		var name= profileNode.Name;
		this._tree.Disable();
		this.prepareProgress(fmres("prf_cloading", "The content is being loaded..."));
		var qs= this.InputParameters; var params= profileNode.Profile_Parameters;
		if (params != "" && params != null) qs+= ((qs != "") ? "&" : "") + params;
		
		this._service.Profile_LoadControl(this.Name, this.GroupName, name, (this.cacheMode == "Session"), qs, this.onPreLoadComplete, this.onServiceFailed, this);
  },

  onPreLoadComplete : function(result, element) {
		if (result) {
			element._Result= result;
			if (result.Resources != null) {
				if (!element.onLoadCompleteDelegate) element.onLoadCompleteDelegate= Function.createDelegate(element, element.onLoadComplete);
				FM._ResourceLoader.getCurrent().Register(result.Resources, result.InlineScript, element.onLoadCompleteDelegate);
			} else {
				element.onLoadComplete();
			}
		}
	},

	onLoadComplete : function() {
		this.createContainerControl(this._Result);
		this.LoadingDone();
		this._Result= null;

		if (this.isInitialized == null) {
			this.isInitialized= true;
			this._counting.Prepare();
		}
	},

	createContainerControl : function(result) {
		this.currentControl= null;
		this._panel.innerHTML= result.BodyHtml;

		if (this.loadWithTransitional || this._Result.CType == "") {
			FM._ResourceLoader.StartTransitionalEffect(this._panel, 50, 25);
			this.loadWithTransitional= false;
		}

		switch (result.CType) {
			case "FM.DataGrid" :
				this.currentControl= new FM.GridContainer(this._panelWindow, this._onGridRefreshDlg, this.InputParameters);
				FM.Profile.SetTreeNodeCount(this._currentNode, null, true);
				break;
			case "FM.DataForm" :
				this.currentControl= new FM.FormContainer(this._panelWindow);
				this.currentControl.IsFormContainer= true;
				this.currentControl.PROFILE_createDataForm();
				if (!this.onCreateDelegate) this.onCreateDelegate= Function.createDelegate(this, this.OnFormCreate);
				this.currentControl.onCreateCallback= this.onCreateDelegate;
				break;
			case "FM.Workflow" :
				this.currentControl= new FM.Workflow("", this._panelWindow);
				this.currentControl.InputParameters= this.InputParameters;
				this.currentControl.PROFILE_create();
				break;
			case "FM.DataInfo" :
				break;
		}
	},

	LoadingDone : function() {
		if (this._tree) this._tree.Enable();
		this.hideProgress();
	},

  onServiceFailed : function(res, element) {
		element.LoadingDone();
		window.status= "Error";
		alert(res.get_message());
  },

  onGridRefresh : function(recordsCount) {
		if (this._counting) this._counting.SetNodeCount(this._currentNode, recordsCount);
  },

	Close : function() {
		this.Window.Hide();
	},

	prepareProgress : function(s) {
		window.parent.FM._ProgressBar.getInstance().Prepare(s);
  },

  hideProgress : function() {
		window.parent.FM._ProgressBar.getInstance().Hide();
  },

  createCookie : function(name,value,days) {
		if (days) {
			var date= new Date();
			date.setTime(date.getTime()+(days*86400000));//24*60*60*1000
			var expires= "; expires="+date.toGMTString();
		}	else var expires= "";
		document.cookie= name + "=" + value + expires + "; path=/";
	},

	Admin_ChangeGroup : function(img, roles) {
		if (this.groupSelector == null) {
			this.gridSelector= new FM.PopupWindow(null, null, window.document, 150, 22);
			this.gridSelector.SetOffsetParent(img);
			var gn= FM.Profile.getCurrent().GroupName;
			var s= "<select onchange='var p=FM.Profile.getCurrent();p.GroupName=this.value;this.Window.Hide();p.LoadContainer();' onclick='this.Window._wasClicked=true;' style='width:100%'>";
			roles= roles.split(',');
			for (var i= 0; i < roles.length; i++) s+= "<option value='"+roles[i]+"'"+((roles[i] == gn) ? " selected" : "")+">"+roles[i]+"</option>";
			s+= "</select>";
			this.gridSelector.SetContent(s);
			this.gridSelector.GetBodyElement().childNodes[0].Window= this.gridSelector;
		}
		this.gridSelector.Show();
	},
	Admin_ControlProperties : function() {
		if (this._currentNode == null) return;
		var fID= this._currentNode.Name;
		var url= fmDataViewerPath.replace("DataViewer/", "Explorer/") + "ProfileBuilder/Settings/PropertyWizard.aspx?isModalContext=1&profile=" + this.Name + "&group=" + this.GroupName + "&folder=" + fID;
		var res= openStdDlg(url, "ProfileControlProperties", 700, 500);

		if (res) this.Load(this._currentNode);
	},
	Admin_Builder : function() {
		var url= fmDataViewerPath.replace("DataViewer/", "Explorer/") + "ProfileBuilder/main.aspx?profile=" + this.Name + "&group=" + this.GroupName;
		openStdWin(url, "ProfileBuilder", 900, 530);
	},
	Reload : function() { this.LoadContainer(); },

	OnFormCreate : function(keyValue) {
		this.InputParameters= "id=" + keyValue;
		this.LoadContainer();
		return false;
	},
	focus : function() {
	//
	},
	
	GetContextInfo : function() {
		return "PROFILE " +
		"  \"" + this.Name + "\"" +
		"\n\tUser Group: \"" + this.GroupName + "\"" +
		"\n\tFolder: \"" + ((this._currentNode) ? this._currentNode.Name : "") + "\"" +
		"\n\tParameters: \"" + this.InputParameters + "\"" +
		"";
	},
	GetDescriptor : function() { return "PROFILE:" + this.Name + "/" + this.GroupName + "/" + ((this._currentNode) ? this._currentNode.Name : ""); },
	
	EndFunc: function() {
	}
}

FM.Profile.registerClass('FM.Profile', null, Sys.IDisposable);
FM.Profile._current= null;
FM.Profile.getCurrent= function () { return FM.Profile._current; }
FM.Profile.FindByWindow= function() { return FM.Profile._current; }

// END

FM.Profile.InitTreeNode= function(treeNode) {
	if (treeNode.InitCount != null) return;
	treeNode.InitCount= -1;
	treeNode.Profile_Count= -1;
	var attr= treeNode.Data.split(",");
	treeNode.Name= attr[0];
	treeNode.AllowAutoCount= (attr[1] == "true" && attr[3] != "");
	treeNode.Profile_AllowPlay= (attr[2] == "true");
	treeNode.Profile_Control= attr[3];
	treeNode.Profile_Parameters= attr[4];
}
FM.Profile.SetTreeNodeCount= function(treeNode, count, bReset) {
	if (count == null) {
		if (treeNode.Profile_Count == -1) return;
		count= treeNode.Profile_Count;
	} else {
		treeNode.Profile_Count= count;
	}
	if (treeNode.InitCount == -1 || bReset) treeNode.InitCount= count;
	
	if (count == -1) {
		treeNode.AllowAutoCount= false;
	} else {
		var text= treeNode.GetDefaultText() + " (" + count + ")";
		var d= count - treeNode.InitCount;
		var bold= false;
		if (d != 0) {
			var sd= (d > 0) ? (" +" + d) : (" " + d);
			text+= sd;
			bold= true;
		}
		treeNode.SetText(text, bold);
	}
}
	

// Recursive Tree Traversal and filling nodes by records Count value
//

FM.ProfileCounting= function(tree, pname, gname, enabled, refreshSec, refreshOnChange, qs) {
	this._tree= tree;
	this.ProfileName= pname;
	this.GroupName= gname;
	this.Enabled= enabled;
	this.RefreshSec= refreshSec;
	this.RefreshOnChange= refreshOnChange;
	this.InputParameters= qs;
	this._needToPlayAudio= false;

	this._profileNodes= null;

	this._index= -1;
	this._current= null;
	this._startDelegate= null;
	this.timerID= null;
}

FM.ProfileCounting.prototype= {

	dispose : function() {
		this._profileNodes= null;
		this.clearTimeout();
  },

  Prepare : function() {
		if (!this.Enabled) return;

		if (!this._service) this._service= FM._ResourceLoader.getResourceLoaderService();
		if (!this._startDelegate) this._startDelegate= Function.createDelegate(this, this.Start);
		
		window.setTimeout(this._startDelegate, 500);
  },

	Start : function () {
		if (!this.Enabled) return;

		this._needToPlayAudio= false;
		this._index= -1;
		if (!this._profileNodes) {
			this.InitNodes();
			if (!this.Enabled) return;
		}

		this.ProcessNextNode();
	},

	Done : function() {
		window.status= "";
		// if (this._needToPlayAudio) this.Audio_Play();
		if (this.RefreshSec != null && this.RefreshSec > 0) {
			this.timerID= window.setTimeout(this._startDelegate, this.RefreshSec * 1000);
		}
	},
	
	clearTimeout : function() {
		if (this.timerID != null) window.clearTimeout(this.timerID);
	},

	InitNodes : function() {
		this._profileNodes= [];
		var htmlNodes= this._tree.GetTreeHtmlNodes();
		var o, hasAC;
		for (var i= 0; i < htmlNodes.length; i++) {
			if (htmlNodes[i].disabled) continue;
			o= FM.UI.TreeNode.GetOrCreate(htmlNodes[i]);
			FM.Profile.InitTreeNode(o);
			if (o.AllowAutoCount) {
				hasAC= true;
				this._profileNodes.push(o);
			}
		}
		if (!hasAC) this.Enabled= false;
	},

	ProcessNextNode : function() {
		if (!this._profileNodes) return; // fix for closed window
		this._index++;
		if (this._index < this._profileNodes.length) {
			var node= this._profileNodes[this._index];
			if (node.AllowAutoCount) {
				this._current= node;
				window.status= "Request records count for folder '" + node.Name + "' ...";
				var qs= this.InputParameters; var params= node.Profile_Parameters;
				if (params != "" && params != null) qs+= ((qs != "") ? "&" : "") + params;
				this._service.Profile_GetCount(this.ProfileName, this.GroupName, node.Name, qs, this.onServiceComplete, this.onServiceFailed, this);
			} else {
				this.ProcessNextNode();
			}
		} else {
			this.Done();
		}
	},

	onServiceComplete : function(result, element) {
		if (element._current) {
			if (element._current == element._tree._currentNode) FM.Profile.SetTreeNodeCount(element._current, null, true);
			else FM.Profile.SetTreeNodeCount(element._current, result);
			element._current= null;
			element.ProcessNextNode();
		}
	},

	SetNodeCount : function(node, count) {
		if (node && node.AllowAutoCount) {
			FM.Profile.SetTreeNodeCount(node, count, true);
		}
		if (this.RefreshOnChange == "true") {
			this.clearTimeout();
			this.Prepare();
		}
	},

	onServiceFailed : function(res, element) {
		element.Done();
	}

}

FM.ProfileCounting.registerClass('FM.ProfileCounting', null, Sys.IDisposable);

// Profile SplitterBehavior Script
// Alfa-XP, Michael Isipciuc, 2006-2007.
//
Type.registerNamespace("FM.UI");

FM.UI.SplitterBehavior= function(tbl, left, splitter, right){
	// Properties
	this._tbl= tbl;
	this._leftPanel= left;
	this._handle= splitter;
	this._Line= this._handle.firstChild;
	this._rightPanel= right;

  this._MinimumWidth= 0;
  this._MaximumWidth= 100000;

  // Variables
  this._tracking= false;
  this._ismousedown= false;
  this._lastLeftPanelWidth= 0;
  this._lastClientX= 0;
  this._tgLeftPanelWidth= 0;

  this._currentX= 0;
  this._initX= 0;
  $addHandlers(this._handle, {
		'click': this._onclick,
		'dblclick': this._ondblclick
	}, this);
	this._onmousedownDelegate= Function.createDelegate(this, this._onmousedown);
  $addHandler(this._handle, 'mousedown', this._onmousedownDelegate);

  this._onmousemoveDelegate= Function.createDelegate(this, this._onmousemove);
  this._onmouseupDelegate= Function.createDelegate(this, this._onmouseup);
  this._onselectstartDelegate= Function.createDelegate(this, this._onselectstart);

	this.mouseHelper= null;
}

FM.UI.SplitterBehavior.prototype= {

  dispose : function() {
    if (this._onmousedownDelegate) {
      $removeHandler(this._handle, 'mousedown', this._onmousedownDelegate);
      this._onmousedownDelegate= null;
    }
    if (this._handle != null) $clearHandlers(this._handle);
    this._handle= null;

    if (this._onmousemoveDelegate) {
      if (this.tracking) $removeHandler(document, 'mousemove', this._onmousemoveDelegate);
      this._onmousemoveDelegate= null;
    }
    if (this._onmouseupDelegate) {
      if (this.tracking) $removeHandler(document, 'mouseup', this._onmouseupDelegate);
      this._onmouseupDelegate= null;
    }
    if(this._onselectstartDelegate) {
      if (this.tracking && (Sys.Browser.agent !== Sys.Browser.Safari)) $removeHandler(document, 'selectstart', this._onselectstartDelegate);
      this._onselectstartDelegate= null;
    }
  },

  _onmousedown : function(e) {
    if (!e) e= event;
    if (e.target.tagName == "IMG") return;
    this._onmousedownImplementation(e.clientX, e.clientY);
  },
  _onmousedownImplementation : function(clientX, clientY) {
    this._ismousedown= true;
		if (this.mouseHelper == null) {
	    this.mouseHelper= document.createElement("DIV");
      this.mouseHelper.style.position= "absolute"; this.mouseHelper.style.zIndex= 5000;
      this.mouseHelper.style.width= "100px"; this.mouseHelper.style.height= "100px";
      this.mouseHelper.style.backgroundColor= "#FFF";
      this.mouseHelper.style.filter= "alpha(opacity=1);";
      document.body.insertBefore(this.mouseHelper, document.body.firstChild); // was document.body.appendChild
		}
    $addHandler(document, 'mousemove', this._onmousemoveDelegate);
    $addHandler(document, 'mouseup', this._onmouseupDelegate);
    if (Sys.Browser.agent === Sys.Browser.Safari) {
      // Safari event handlers can't cancel unless added directly
      document.onselectstart= this._onselectstartDelegate;
		} else {
      $addHandler(document, 'selectstart', this._onselectstartDelegate);
    }
  },
  _ondblclick : function(e) {
		if (!e) e= event;
		this._ondblclickImplementation(e);
  },
  _onclick : function(e) {
		if (e.target.tagName == "IMG")
			this._ondblclickImplementation(e);
  },
  _ondblclickImplementation : function(e) {
		if (this._leftPanel.style.width == '0px') {
			if (this._tgLeftPanelWidth == 0) this._tgLeftPanelWidth= parseInt(this._leftPanel.getAttribute("defaultWidth"));
			if (this._tgLeftPanelWidth < 50) this._tgLeftPanelWidth= 50;
			this._leftPanel.style.width= this._tgLeftPanelWidth + "px";
		} else {
			this._tgLeftPanelWidth= this._leftPanel.offsetWidth;
			this._resizePanel(0, -this._tgLeftPanelWidth);
		}

  },

  _onmousemove : function(e) {
		if(!e) e= event;
		this._onmousemoveImplementation(e.clientX, e.clientY);
  },
  _onmousemoveImplementation : function(clientX, clientY) {
    if (this._ismousedown && clientX != this._lastClientX) {
			if (this._tracking == false) {
				this._lastClientX= clientX;
				this._initX= clientX;
				this._Line.style.display= "";
				this.mouseHelper.style.display= "";
			}
			this._tracking= true;
			var dx= clientX - this._initX;
			this._Line.style.left= dx + "px";
			this.mouseHelper.style.left= (clientX - 50) + "px"; this.mouseHelper.style.top= (clientY - 50) + "px";
			this._currentX= clientX;
    }
  },

  _onmouseup : function() {
    if (this._tracking) {
			this._Line.style.display= "none";
			this.mouseHelper.style.display= "none"; 
			this._resizePanel(this._currentX, (this._currentX - this._lastClientX));
			this._currentX= 0;
		}

    this._tracking= false;
    this._ismousedown= false;
    $removeHandler(document, 'mousemove', this._onmousemoveDelegate);
    $removeHandler(document, 'mouseup', this._onmouseupDelegate);
    if (Sys.Browser.agent === Sys.Browser.Safari) {
      document.onselectstart= null;
    } else {
      $removeHandler(document, 'selectstart', this._onselectstartDelegate);
    }
  },

  _onselectstart : function(e) {
    // Don't allow selection during drag
    e.preventDefault();
    return false;
  },

	_resizePanel : function(clientX, deltaX) {
		if (this._lastLeftPanelWidth == 0) {
			this._lastLeftPanelWidth= this._leftPanel.offsetWidth;
			this._rightPanel.style.width= "100%";
			this._MaximumWidth= this._tbl.offsetWidth - 8;
		}
		this._lastClientX= clientX;
    var _pWidth= Math.max(Math.min(this._lastLeftPanelWidth+deltaX, this._MaximumWidth), this._MinimumWidth);
    this._lastLeftPanelWidth= _pWidth;
    this._leftPanel.style.width= _pWidth + 'px';
  }

}

FM.UI.SplitterBehavior.registerClass('FM.UI.SplitterBehavior', null, Sys.IDisposable);

// GRID CONTAINER
//
FM.GridContainer= function(hostWindow, onRefreshCallback, inputParams) {
	FM.GridContainer._current= this;

	// Properties
	this.Window= hostWindow;
	this._currentGrid= null;

	var _panel= this.Window.GetBodyElement();
	var topDiv= getFirstElement(_panel);
	var menubar= getLastElement(topDiv);
	var grid= getLastElement(_panel);
	if (grid != null && grid.tagName == "DIV") {
		this._currentGrid= $create(FM.DataGrid, null, null, null, grid);
		this._currentGrid.OnRefresh= onRefreshCallback;
		this._currentGrid.InputParameters= inputParams;
	}
	if (menubar) {
		this._menubar= new FM.MenuBar(menubar, this._currentGrid);
	}
	var sType= topDiv.getAttribute('search');
	if (sType == 'ByForm') {
		this._searchcontrol= new FM.SFormContainer(getFirstElement(topDiv));
	} else if (sType == 'ByGrid') {
		this._searchcontrol= new FM.SGridContainer(getFirstElement(topDiv));
	}
}

FM.GridContainer.prototype= {
	dispose : function() {
		if (this._currentGrid) { this._currentGrid.dispose(); this._currentGrid= null; }
		if (this._menubar) { this._menubar.dispose(); this._menubar= null; }
		if (this._searchcontrol) {this._searchcontrol.dispose(); this._searchcontrol= null; }
	}
}

FM.GridContainer.registerClass('FM.GridContainer', null, Sys.IDisposable);
FM.GridContainer._current= null;
FM.GridContainer.getCurrent= function () { return FM.GridContainer._current; }


Sys.Application.notifyScriptLoaded();
