
// Main page script
//Utilities
var Utility = {

	ToMySqlDate: function (systemdate) {
		var dt = new Data();
		if (typeof systemdate == _UND || systemdate.Trim() == "") {
			//get the system date
			var dt = new Data();
			return dt.getFullYear + "-" + (dt.getMonth + 1) + "-" + dt.getDate;

		}
		//convert to mysqldate
		var dtarr = sysemdate.split("/");

		dtarr[0] = dtarr[0].ToNumber();
		if (dtarr[0] < 1) dtarr[0] = dt.getDate;
		if (typeof dtarr[1] == _UND || dtarr[1].ToNumber() < 1) dtarr[1] = (dt.getMonth + 1);
		if (typeof dtarr[2] == _UND || dtarr[2].ToNumber() < 1) dtarr[2] = dt.getFullYear;
		return dtarr[2] + "-" + dtarr[1] + "-" + dtarr[0];
	},

	FromMySqlDate: function (mysqldate) {
		if (typeof mysqldate == _UND || mysqldate.Trim() == "") return "";
		var dtarr = mysqldate.split("-");
		if (dtarr.length < 3) return "";
		$rdt = dtarr[2] + "/" + dtarr[1] + "/" + dtarr[0];
		return ($rdt == "00/00/0000") ? "" : $rdt;
		//convert from mysqldate to system date format	
	},

	LoadStudy: function (obj) {
		var dd = obj.id;
		TextBox.Load(dd + 'study', "ID", "Name", "SchoolType = (select Type from school_tb limit 1) AND StudySchID = " + _(dd).ValueContent(), "study_tb");
	}


}
//General School Detals loading object
//LE - 22-5-17 #1
var GenLoading = function (obj) {
	this.Datas = obj;
	this.LoadFac = function (obj) { //function to load department textbox based on selected faculty
		//var facID = _("studfac").ValueContent();
		//if(facID == null)return;select * from fac_tb order by FacName
		//alert(facID);
		//console.log(obj);
		//alert(window.sessionStorage)
		//Tracer.Start("Chain Loading");
		//alert(this.Datas.FacID);
		var studstudyobj = _(this.Datas.StudyID);
		var studstudy = studstudyobj == null ? 1 : studstudyobj.ValueContent();
		//alert(studstudy);
		//Tracer.Tag("Fac: "+this.Datas.FacID);
		studstudy = (studstudy == null || studstudy.Trim() == "") ? 1 : studstudy;
		var factb = _(this.Datas.FacID);
		if (factb == null) return;
		//check if to
		//Tracer.Tag("Onload of fac due to change of studyid = " + studstudy);
		TextBox.Load(this.Datas.FacID, "FacID", "FacName", "StudyID=" + studstudy, "fac_tb"); //Load:function(tb,key, val, cond, dbtb)
		//Exams.ResultUpload.LoadLevel(); //load level if a programe id is set
		//Tracer.End();
	}
	//*Student.BioData.LoadDepartment *BioData.LoadDepartment *Student.BioData.LoadDept *BioData.LoadDept
	this.LoadDept = function () { //function to load department textbox based on selected faculty
		//Tracer.Start();
		var facID = _(this.Datas.FacID).ValueContent();
		//Tracer.Tag("Faculty: "+facID);
		if (facID == null || facID.Trim() == "") facID = 0;
		//alert(facID);
		//alert(facID);
		//Tracer.Tag("Onload of dept due to change of fac = "+facID);
		TextBox.Load(this.Datas.DeptID, "DeptID", "DeptName", "FacID = " + facID, "dept_tb"); //Load:function(tb,key, val, cond, dbtb)
		//Tracer.End();
		//_('rstudprog')
	}
	//*Student.BioData.LoadProgramme *BioData.LoadProgramme
	this.LoadProg = function () { //function to load program textbox based on selected department
		//Tracer.Start();
		var deptID = _(this.Datas.DeptID).ValueContent();
		if (deptID == null || deptID.Trim() == "") deptID = 0;
		//Tracer.Tag("Onload of prog due to change of dept = " +deptID);
		//Tracer.Tag("Department: "+deptID);
		TextBox.Load(this.Datas.ProgID, "ProgID", "ProgName", "DeptID = " + deptID, "programme_tb"); //Load:function(tb,key, val, cond, dbtb)
		this.GetLevel(); //try to recalculate level
		//Tracer.End();
	}
	this.LoadLevel = function () { //function to load level based on programme and 
		//Tracer.Start();
		var progID = _(this.Datas.ProgID).ValueContent();

		if (progID == null || progID == "") progID = 0;
		//var studstudy = _(this.Datas.StudyID).ValueContent();
		var studstudyobj = _(this.Datas.StudyID);
		var studstudy = studstudyobj == null ? 0 : studstudyobj.ValueContent();
		if (studstudy == null || studstudy.Trim() == "") studstudy = 0;
		//alert(facID);
		//Tracer.Tag("Onload of level due to change of prog = "+progID+" or studyid = " + studstudy);
		//Tracer.Tag("Level: StudyID is "+studstudy);
		TextBox.Load(this.Datas.LevelID, configdata.Core + "cportal/Pages/Scripts/Gen/loadlevel.php?StudyID=" + escape(studstudy) + "&progID=" + escape(progID) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
		//_("semest").ClearText();
		//MessageBox.Show("Note: Level-Set Changed, confirm Student level before Save");
		//Load:function(tb,key, val, cond, dbtb)
		//Tracer.End();
	}
	this.LoadClass = function () { //function to load level based on programme and 
		//Tracer.Start();
		var progID = _(this.Datas.ProgID).ValueContent();

		if (progID == null || progID == "") progID = 0;

		TextBox.Load(this.Datas.ClassID, "ID", "Name", "ProgID = " + progID, "studentclass_tb");
		this.GetLevel(); //try to recalculate level
		//_("semest").ClearText();
		//MessageBox.Show("Note: Level-Set Changed, confirm Student level before Save");
		//Load:function(tb,key, val, cond, dbtb)
		//Tracer.End();
	}
	this.LoadStudy = function () {
		TextBox.Load(this.Datas.StudyID, configdata.Core + "cportal/Pages/Scripts/Gen/loadStudy.php?a=1" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
		this.GetLevel(); //try to recalculate level

	}

	this.LoadSemester = function () {

		TextBox.Load(this.Datas.SemID, "Num", "Sem", "Enable=1", "semester_tb");

	}

	this.GetLevel = () => {

		var oplvl = _(this.Datas.DisplayLevelID);
		var oplvlid = _(this.Datas.DisplayLevelIDNum);
		if (oplvl == null) return;
		oplvl.innerHTML = "--";

		//get the selected startses
		var startses = _(this.Datas.StartSesID).ValueContent();
		if (startses == null || startses == "") return;
		var studstudyobj = _(this.Datas.StudyID);
		var studstudy = studstudyobj == null ? 1 : studstudyobj.ValueContent();
		var progID = _(this.Datas.ProgID).ValueContent();

		if (progID == null || progID == "") progID = 0;
		oplvl.innerHTML = '<i class="fa fa-spin fa-cog"></i>';
		var aj = new Ajax();
		aj.Post({
			Action: configdata['Core'] + "cportal/Pages/Scripts/Gen/getlevel.php",
			PostData: "StartSes=" + encodeURIComponent(startses) + "&ProgID=" + encodeURIComponent(progID) + "&StudyID=" + encodeURIComponent(studstudy) + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']),
			OnComplete: function (res, url, param) {
				// alert(res);
				try {
					var dt = JSON.parse(res);
					oplvl.innerHTML = dt.ExLevelName;
					if (oplvlid != null) oplvlid.textContent = dt.ExLevelID;
				} catch (error) {
					oplvl.innerHTML = "--";
					if (oplvlid != null) oplvlid.textContent = '0';
				}
			},
			OnAbort: function (res) {
				oplvl.innerHTML = "--";
			}
		});
	}
}


//the Page loading object
//*Loading
var Loading = new function () {
	//animation state
	this.State = 0;

	this.DateTimeBox = null;
	this.WeekDays = [];
	this.WeekDays = ["SUN", "MON", "TEU", "WED", "THU", "FRI", "SAT"];
	this.Months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
	this.UpdateDate = function () {
		//get the current date
		var cdt = new Date();
		var tmstr = cdt.toLocaleTimeString();
		var brk1 = tmstr.split(" ");
		var time = brk1[0]; var am = brk1[1];
		//break down time
		var timebr = time.split(":");
		var dayw = Loading.WeekDays[cdt.getDay()];
		var datenum = cdt.getDate()
		var m = Loading.Months[cdt.getMonth()];
		Loading.DateTimeBox.innerHTML = '<span class="double white"> ' + timebr[0] + ':' + timebr[1] + '</span> <span class="big white">' + am + '</span> ' + dayw + ' ' + datenum + ', ' + m + ' ' + cdt.getFullYear() + '';
		setTimeout('Loading.UpdateDate()', 1000 * 60);
	}

	//start loading animation
	//*Loading.Start
	this.Start = function (func) {
		//alert("b");
		if (typeof func != "undefined") {
			if (typeof func == "function") {
				func();
			} else {
				eval(func);
			}
		}
		Loading.DateTimeBox = _("DateTime");

		Loading.UpdateDate();

		//start the date time
		//*Header.TimeAjax *AutoTime
		/* Header.TimeAjax = new Ajax();
		Header.TimeAjax.StartAutoDateTime('j:D:M:Y:g:i:s:A', function (res) {
			var resarr = res.split(":");
			if (resarr.length == 8) {
				_("DateTime").innerHTML = '<span class="double white"> ' + resarr[4] + ':' + resarr[5] + '</span> <span class="big white">' + resarr[7] + '</span> ' + resarr[1] + ' ' + resarr[0] + ', ' + resarr[2] + ' ' + resarr[3] + '';
			}
		}) */
		//Loading.StartAnimate(300);
		//Fender.LoadLeft();maincontreal
		Header.Show();
		//"newpg".HTML("Pages/Fender/left.php",function(){Header.Show()},function(){});
	}

	//display and start start the animation efect
	this.StartAnimate = function (num) {
		//_('movingbg').Hide();
		//alert(_('movingbg').style.marginLeft);
		_("mainLoader").Appear();
		Loading.State = 1;
		_('movingbg').Animate({ CSSRule: "margin-left:" + num + "px", Time: 6000, DoAt: 1, EndAction: "Loading.ChangeDirection()", Delay: 0 });
	}
	this.ChangeDirection = function () {
		if (Loading.State == 1) {
			var curNum = _('movingbg').style.marginLeft.ToNumber();
			//alert(curNum);
			if (curNum > 0) {
				Loading.StartAnimate(-160)
			} else {

				Loading.StartAnimate(300)
			}
		}
	}

	//function to stop and hide loading object
	//*Loading.Stop
	this.Stop = function (func) {
		_("mainLoader").Disappear();
		Loading.State = 0;
		if (typeof func != "undefined") {
			if (typeof func == "function") {
				func();
			} else {
				eval(func);
			}
		}
	}

	//function to display the general loading;

	this.Display = function (func, param) {
		if (typeof func != _UND) {
			param = typeof param == _UND ? _("genloading") : param
			func(param);
		}
		"genloading".Show();

	}

	//function to display the general loading;
	this.Close = function (func, param) {
		"genloading".Hide();
		if (typeof func != _UND) {
			param = typeof param == _UND ? _("genloading") : param
			func(param);
		}
	}
}

//object to handle fender displays
//*Fender
var Fender = new function () {
	this.OpenLeft = function () {
		//"Fender".HTML("Pages/Fender/left.php",function(){},function(res){});
		//aa=_(" MenuInfo    menubtn    SchoolName ");pgggg
		//"FenderLeft".Animate({CSSRule:"left:0px;top:0px;background-color:rgba(239,239,239,1)", Time:700});
		//"menubtn~SchoolName".Animate({CSSRule:"margin-top:0px", Time:700});

	}
	this.CloseLeft = function () {
		_("FenderLeft").Animate({ CSSRule: "left:-260px;background-color:rgba(239,239,239,.4)", Time: 400 });
	}
	this.OpenRight = function () {
		Page.Open(configdata.Core + "cportal/Pages/Fender/left.php", "pggg");
		//"FenderRight".Animate({CSSRule:"right:0px;background-color:rgba(239,239,239,1)", Time:700});
	}
	this.CloseRight = function () {
		_("FenderRight").Animate({ CSSRule: "right:-260px;background-color:rgba(239,239,239,.4)", Time: 400 });
	}
	this.Close = function () {
		Fender.CloseRight();
		Fender.CloseLeft();
	}

	this.LoadLeft = function () {
		"FenderLeft".HTML("Pages/Fender/left.php", function () { Header.Show() }, function () { });
	}

	this.SelectSub = function (obj) {
		//alert('sss');
		var allsub = _('exsubitems');
		allsub = IsArray(allsub) ? allsub : [allsub];
		for (var ss = 0; ss < allsub.length; ss++) {
			allsub[ss].classList.remove('sel')
		}
		//alert(obj);
		obj.classList.add('sel');
		//add the current tabname to Page.TabOpened array in Elements.js
		//get object tab name
		var idarr = obj.id.split('_');
		var tabName = idarr[1];
		//make sure the submenus is opened
		var gnameinp = _(obj.id + "_gn");
		if (gnameinp != null) {
			var gname = gnameinp.value;
			//get the main group menu
			var mainmenu = _('explorermainmenu_' + gname);
			if (mainmenu != null) {
				mainmenu.classList.remove('closesub');
			}
		}
	}
}

//*Header
var Header = new function () {
	this.TimeAjax = null;
	this.Show = function () {
		//Header.ShowMenuBtn();
		Header.ShowLoginBtn();
		document.body.Assign("click", function (e) {
			var t = e.target;
			if (!t.classList.contains('showExplorer')) {
				Page.HideAllFender()
			}
			//
		});
	}
	this.Hide = function () {
		"Header".Animate({ CSSRule: "top:-75px", Time: 800 });

	}

	this.ShowMenuBtn = function () {
		"Header".Animate({ CSSRule: "top:0px", Time: 200, EndAction: "", DoAt: 0.3 });
		"MenuInfo".Animate({ CSSRule: "margin-top:10px", Time: 500, EndAction: "Header.ShowName()", DoAt: 0.3 });
	}
	this.ShowName = function () {
		"Names".Animate({ CSSRule: "margin-top:0px", Time: 500, EndAction: "Header.ShowDate()", DoAt: 0.3 });
		"NamesAbbr".Animate({ CSSRule: "margin-top:0px", Time: 500, EndAction: "Header.ShowDate()", DoAt: 0.3 });
	}
	this.ShowDate = function () {
		//"DateTime".Animate({ CSSRule: "margin-top:0px", Time: 600, EndAction: "Header.ShowLoginBtn()", DoAt: 0.3 });
		"DateTime".Animate({ CSSRule: "margin-top:0px", Time: 600, EndAction: "", DoAt: 0.3 });
	}
	this.ShowLoginBtn = function () {
		"LoginInfo".Animate({ CSSRule: "margin-top:10px", Time: 700, EndAction: "Login.ShowMenus()", DoAt: 0.3 });
	}




}

//object to handle all login operations
//*Login 
var Login = function () {
	return {
		ShowHideMenus: function (menuid) {
			var menugrp = _(menuid);
			if (!Null(menugrp)) {
				if (menugrp.ClassIs("min")) {

					menugrp.className = menugrp.className.Replace(" min", "");
					//menugrp.Animate({CSSRule:"height:100%",Time:1000,DoAt:1.0,EndAction:'_("'+menuid+'").className = _("'+menuid+'").className.Replace(" minn","")'});
					//'mazimize'.__();
				} else {

					menugrp.className += " min";
					//menugrp.Animate({CSSRule:"height:0px",Time:1000,DoAt:1.0,EndAction:'_("'+menuid+'").className += " minn"'});
					//'minimize'.__();
				}
			}
		},
		User: function () {
			//current user login name
			var cuserdet = Cookie.Get("UserDet");
			if (cuserdet.Trim() == "") { MessageBox.Show("#Un-Identified User. Logout and Re-Login"); return null; }
			var cuserarr = cuserdet.split("~");
			if (cuserarr.length < 3) { MessageBox.Show("#Invalid User Details Found. Logout and Re-Login"); return null; }
			return cuserarr;
		},
		//display/loads the login screen
		//*Login.ShowScreen 
		ShowScreen: function () {
			/*if(!Null(_("mainMenuCont"))){
				Login.Logout();
				return;
			}*/
			Loading.Display();
			//var mainmenu = _("mainMenuCont");
			if (_("loginCont") == null) {
				var lgcont = document.createElement("div");
				lgcont.id = "loginCont";
				document.body.appendChild(lgcont);
			}

			//get current user det
			var cuserdet = Cookie.Get("UserDet");
			if (cuserdet != "") {
				var resarr = cuserdet.split("~");
				var userID = resarr[0]
			} else {
				var userID = 0;
			}

			//_("userloginimgsm").lowsrc = "TaquaLB/Elements/Images/loadingbtn2.gif";
			//load screen and set user to offline in screen.php if a user exist
			"loginCont".HTML(configdata['Core'] + "cportal/Pages/Login/screen.php?UID=" + userID + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']), function () {
				_('screentxt').textContent = "Sign In";
				Header.Hide();
				Cookie.Set("UserDet", "", -1000);
				Login.CurrentType = 0;
				Login.CurrentUserDet = ""; //clear all user details
				//Lock.StopAutoLock(); //stop auto screen lock
				Lock.CloseLogout();
				//_("userloginimgsm").src = "Resources/Images/user.jpg";
				"loginCont".Animate({ CSSRule: "opacity:1", Time: 600 });
				_("usernm").TextFocus();
				_("Userimg").style.marginTop = "0px";
				Loading.Close();//close the loading animation
				document.body.onmousemove = null;
				//document.body.classList.add('Default');
			}, function () { Loading.Close(); MessageBox.Show("#Error Loading Login Screen") });
		},
		//display/load menu items
		//*Login.ShowMenu
		ShowMenus: function () {
			Loading.Display();
			var cuserdet = Cookie.Get("UserDet");
			//console.log("Get: "+cuserdet);
			if (cuserdet == "") {
				Login.ShowScreen(); //show the login screen 
			} else {
				//reset the user det cookie to extend its expiring date

				var resarr = cuserdet.split("~");
				var userID = resarr[0];
				//'Get the login users name'.__();
				var userName = resarr[2];
				//('Username is '+ userName).__();
				var passpurl = "Files/UserImages/" + userID + ".jpg";
				_("userloginimgsm").src = passpurl;
				_("userloginimgsm").lowsrc = configdata['Core'] + "general/TaquaLB/Elements/Images/loadingbtn2.gif";
				_("userloginimgsm").title = userName;
				Login.CurrentUserDet = cuserdet;

				var mmc = document.createElement("div");
				mmc.id = "mainMenuCont";
				document.body.appendChild(mmc);
				var aj = new Ajax();
				//alert(JSON.stringify(configdata));
				//******************** */
				//alert("UID=" + userID+"&SubDir="+encodeURIComponent(configdata['SubDir'])+"&Core="+encodeURIComponent(configdata['Core']));
				aj.Post({
					Action: configdata['Core'] + "cportal/Pages/MainMenu/menu.php",
					PostData: "UID=" + userID + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']),
					OnProgress: function (delta) {
						//Tabs.Tab("Student").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
					},
					OnComplete: function (res, url, param) {
						//alert(JSON.stringify(param));
						//'loaded from server script'.__();
						// return;
						_("mainMenuCont").innerHTML = res;
						Header.ShowMenuBtn();
						"mainMenuCont".Animate({ CSSRule: "opacity:1", Time: 600 });
						var usdetobj = _('userdet');
						//alert(usdetobj);
						//if(usdetobj == null){Login.ShowScreen(); return; //show the login screen }
						var usdet = usdetobj.value; //get the new user det and set it
						Cookie.Set("UserDet", usdet, 1000 * 60 * 60 * 24 * 7);
						//console.log("Set in ShowMenus");
						Login.CurrentUserDet = usdet;
						var userdetarr = usdet.split("~");
						Lock.IdleTime = userdetarr[3].ToNumber() * 1000;
						Lock.Status = userdetarr[4].ToNumber();
						Lock.MaxRetry = userdetarr[5].ToNumber();
						var screenLk = Cookie.Get("ScreenLock");
						if (screenLk.Trim() != "") {
							Lock.Show(); //show the lock
						} else {
							Loading.Close();
						}
						Login.AutoDashBoardTimmer = setTimeout("Login.AutoDashBoard()", 2000);
						Lock.AutoLock();
						document.body.onmousemove = Lock.AutoLock;
						//	Student.BioData.LoadStudentGroup.Animate({ CSSRule: "opacity:1", Time: 400 });
						//CoverScreen.Close(_("ldst"));
					},
					OnAbort: function (res) {
						MessageBox.Show("Operation Aborted");
					},
					OnError: function (res) {
						Loading.Close(); MessageBox.Show("#Error Loading Menus - " + res);
					}
				});

				//******************* */
				//alert(userID);
				/* "mainMenuCont".HTML("Pages/MainMenu/menu.php?UID=" + userID, function () {
					//document.body.classList.remove('Default');
					Header.ShowMenuBtn();
					"mainMenuCont".Animate({ CSSRule: "opacity:1", Time: 600 });
					var usdetobj = _('userdet');
					//alert(usdetobj);
					//if(usdetobj == null){Login.ShowScreen(); return; //show the login screen }
					var usdet = usdetobj.value; //get the new user det and set it
					Cookie.Set("UserDet", usdet, 1000 * 60 * 60 * 24 * 7);
					Login.CurrentUserDet = usdet;
					var userdetarr = usdet.split("~");
					Lock.IdleTime = userdetarr[3].ToNumber() * 1000;
					Lock.Status = userdetarr[4].ToNumber();
					Lock.MaxRetry = userdetarr[5].ToNumber();
					var screenLk = Cookie.Get("ScreenLock");
					if (screenLk.Trim() != "") {
						Lock.Show(); //show the lock
					} else {
						Loading.Close();
					}
					Login.AutoDashBoardTimmer = setTimeout("Login.AutoDashBoard()", 2000);
					Lock.AutoLock();
					document.body.onmousemove = Lock.AutoLock;
				}, function (res) { Loading.Close(); MessageBox.Show("#Error Loading Menus - "+res) }); */
			}
		},
		SetDashBoard: function (dashitem, data) {
			var datatr = parseInt(data);
			if (isNaN(datatr)) { //if number not sent
				dashitem.innerHTML = data;
			} else {

				/*'<div class="progressbarbx">
	  <div class="progressbar">
		<div class="bar" style="width:'.$rtn.'%" id="regbar'.$pref.'"></div>
	  </div>
	  <div class="perc"  id="regbarperc'.$pref.'">'.$rtn.'%</div>
	</div>'*/
				var bar = _(dashitem.id + "Bar");

				if (!Null(bar)) {
					bar.Animate({ CSSRule: "width:" + data + "%", Time: 1000 });

					_(dashitem.id + "Perc").textContent = data + "%";
					// alert(data);
				} else {
					dashitem.innerHTML = '<div class="progressbarbx"><div class="progressbar"><div class="bar" style="width:' + data + '%" id="' + dashitem.id + 'Bar"></div></div><div class="perc"  id="' + dashitem.id + 'Perc">' + data + '%</div></div>';
				}
			}
		},
		AutoDashBoardTimmer: null,
		//function to perform auto dashbord loading
		//*Login.AutoDashBoard *Login.DashBoard
		AutoDashBoard: function () {
			var cuserdet = Cookie.Get("UserDet");
			if (cuserdet == "") {
				OptionBox.Show({
					Title: "Security Parameters not Found",
					Options: [{
						Logo: "sync",
						Title: "Reload Page",
						Info: "Reload the entire page",
						Function: function () {
							var adrr = document.location.toString();
							var resolve = adrr.UrlResolve();
							//Hash:"",Data:"",Url:"",File:"",Host:"",Ext:""
							/* ("Hash: "+resolve.Hash).__();
							 ("Data: "+resolve.Data).__();
							 ("Url: "+resolve.Url).__();
							 ("File: "+resolve.File).__();
							 ("Host: "+resolve.Host).__();
							 ("Ext: "+resolve.Ext).__();*/
							document.location = resolve.Host + "?rel=" + Math.random();
						}
					}]

				});

				//Login.Logout(); //show the login screen 
			} else {
				/*var resarr = cuserdet.split("~");
			  var userID = resarr[0];
			 var Ajaxd = new Ajax(); 
			  //call the post operation
			  Ajaxd.PostResponse("UID="+userID,"Pages/MainMenu/dashboradloader.php",
			  function(res,url,param){
				
				 // res.__();
				 var resarr = res.split(":::");
				  //resarr[6].__();
				 var entr = resarr[0];schreg=resarr[1];coursereg=resarr[2];feypay=resarr[3];mails=resarr[4];online=resarr[5];
				 Login.SetDashBoard(_("dashBEntrCont"),entr);
				 Login.SetDashBoard(_("dashBSchCont"),schreg);
				 Login.SetDashBoard(_("dashBCourseCont"),coursereg);
				 Login.SetDashBoard(_("dashBPayCont"),feypay);
				 Login.SetDashBoard(_("dashBMailCont"),mails);
				 Login.SetDashBoard(_("dashBOnlineCont"),online);*/

				/*_("dashBPayCont").innerHTML=feypay;
				_("dashBMailCont").innerHTML=mails;
				_("dashBOnlineCont").innerHTML=online;*/

				Login.AutoDashBoardTimmer = setTimeout("Login.AutoDashBoard()", 2000);
				/* }
			 , "text",function(res){
				 });*/

			}

		},
		CurrentType: 0,//holds the current verify type if email=0 or password=1
		//verify user email/username supplied
		//*Login.Verify  
		Verify: function () {
			//alert("ssss");
			var type = Login.CurrentType;
			if (_('veridybtn').ClassIs("loading")) return;
			//*Login.VerifyEmail
			if (type == 0) {//email
				var value = _("usernm").TextContent();
				if (value.Trim() == "") {
					MessageBox.Show("Kindly Provide a valid Email");
					return;
				}
				if (!IsEmail(value)) {
					MessageBox.Show("#The Email you supply is Invalid");
					return;
				}

				"Userimg".Animate({ CSSRule: "width:100px;height:100px;opacity:0", Time: 600 });
				"UserimgrCont".Animate({ CSSRule: "padding-top:50px;height:200px", Time: 600 });
				//return;
				//start the loading on the button
				_("veridybtn").StartLoading();
				_("usernm").TextDisable();
				//create a new ajax object
				var Ajaxs = new Ajax();
				//+"&SubDir="+encodeURIComponent(configdata['SubDir'])
				//call the post operation
				Ajaxs.PostResponse("email=" + value + "&SubDir=" + encodeURIComponent(configdata['SubDir']), configdata['Core'] + "cportal/Pages/Login/verifyEmail.php",
					function (res, url, param) {
						//alert(res + " ; " + at);
						// return;
						res = res.Trim();
						if (res == "##") { //if email not found

							MessageBox.Show("#The Email you supply is not Available");
							"Userimg".Animate({ CSSRule: "width:250px;height:250px;opacity:1", Time: 600 });
							"UserimgrCont".Animate({ CSSRule: "padding-top:0px;height:250px", Time: 600 });
							_("veridybtn").StopLoading();
							_("usernm").TextEnable();
							return;
						}
						var resarr = res.split("~");
						if (resarr.length < 2) { //if a wrong format responce is gotten
							MessageBox.Show("#Server Error, Try Again");
							"Userimg".Animate({ CSSRule: "width:250px;height:250px;opacity:1", Time: 600 });
							"UserimgrCont".Animate({ CSSRule: "padding-top:0px;height:250px", Time: 600 });
							_("veridybtn").StopLoading();
							_("usernm").TextEnable();
							return;
						}

						//email verified successfully


						//_("userimgInnerReal").lowsrc = "TaquaLB/Elements/Images/loadingbtn2.gif";
						"userLoginName".Animate({ CSSRule: "opacity:0", Time: 500 }); //fade out the user login name display div
						"usernm".Animate({ CSSRule: "opacity:0", Time: 500, EndAction: "Login.SwitchToPassword('" + res + "')", DoAt: 1 }); //fade out the email textbox

					}, "text", function (res) {
						if (res == "#") {
							MessageBox.Show("#Server Request Time, Check your Network Connection and Try Again");
						} else {
							MessageBox.Show("#Server Error, Connection Problem");
						}
						"Userimg".Animate({ CSSRule: "width:250px;height:250px;opacity:1", Time: 600 });
						"UserimgrCont".Animate({ CSSRule: "padding-top:0px;height:250px", Time: 600 });
						_("veridybtn").StopLoading();
						_("usernm").TextEnable();
					});
			} else {//password
				//*Login.VerifyPassword
				//load menu
				var psw = _("userpssw").TextContent();
				_("userpssw").ClearText();
				//alert(psw);
				if (psw.Trim() == "") {
					MessageBox.Show("Kindly Provide a valid Password");
					return;
				}
				var detarr = Login.CurrentUserDet.split("~");
				//start the loading on the button
				_("veridybtn").StartLoading();
				_("userpssw").TextDisable();
				var Ajaxs = new Ajax();
				var email = detarr[1];
				//call the post operation
				Ajaxs.PostResponse("email=" + escape(email) + "&pw=" + escape(psw) + "&SubDir=" + encodeURIComponent(configdata['SubDir']), configdata['Core'] + "cportal/Pages/Login/verifyPw.php",
					function (res) {
						res = res.Trim();
						//alert(res);
						//return;
						if (res == "#") { //if email not found
							MessageBox.Show("#The Password supplied is Invalid");
							_("veridybtn").StopLoading();
							_("userpssw").TextEnable();
							return;
						}
						if (res == "##") { //if email not found
							MessageBox.Show("#Invalid Parameters");
							_("veridybtn").StopLoading();
							_("userpssw").TextEnable();
							return;
						}
						var resarr = res.split("~");
						if (resarr.length < 2) { //if a wrong format responce is gotten
							MessageBox.Show("#Server Error, Try Again");
							_("veridybtn").StopLoading();
							_("userpssw").TextEnable();
							return;
						}

						var initIdleTime = resarr[3].ToNumber(); //get the idletime and set it
						Lock.IdleTime = initIdleTime * 1000;
						var pinstatus = resarr[4].ToNumber(); //get the pin status
						Lock.Status = pinstatus;
						Lock.MaxRetry = resarr[5].ToNumber();
						// MessageBox.Show(Lock.Status)
						//set the cookie
						Cookie.Set("UserDet", res, 1000 * 60 * 60 * 24 * 7);
						//console.log('set in password verification')
						//load the main menus
						Login.RemoveScreen();

					}, "text", function (res) { MessageBox.Show("#Server Error, Connection Problem"); });

			}

		},
		CurrentUserDet: "", //this variable holds the current user details trying to login
		SwitchToPassword: function (userinfo) { //this function switces the login textbox to password verification , sending all the userinfo
			Login.CurrentUserDet = userinfo;
			var arr = userinfo.split("~");
			var userName = arr[2];
			//"userLoginName".Text('<i class="fa fa-arrow-left fa-fw" style="padding:2px;display:inline-block;border-radius:50%;background-color:#eee;vertical-align:middle;margin-left:10px;font-size:0.8em;"></i> <span   style="display:inline-block;vertical-align:middle">'+userName+'</span>'); //set the user name to display
			_("userLoginName").innerHTML = '<i class="fa fa-arrow-left fa-fw" style="padding:3px;display:inline-block;border-radius:50%;background-color:#eee;vertical-align:middle;margin-left:10px;font-size:0.8em;cursor:pointer" onclick="Login.ShowScreen()"></i> <span   style="display:inline-block;vertical-align:middle">' + userName + '</span>'; //set the user name to display
			_('screentxt').textContent = "Enter Password";
			//load and set the user passport here
			//set the user passport photograph
			var userID = arr[0];
			var passpurl = "Files/UserImages/" + userID + ".jpg";
			_("userimgInnerReal").src = passpurl;

			// /////////////////////////////////////////////////////////////
			"userLoginName".Animate({ CSSRule: "opacity:1", Time: 500 });
			_("usernm").Hide();
			_("usernm").TextEnable();
			_("userpssw").Show();
			_("userpssw").TextFocus();
			"userpssw".Animate({ CSSRule: "opacity:1", Time: 500 });
			"Userimg".Animate({ CSSRule: "width:250px;height:250px;opacity:1", Time: 600 });
			"UserimgrCont".Animate({ CSSRule: "padding-top:0px;height:250px", Time: 600 });
			Login.CurrentType = 1; //change to password verification

			_("veridybtn").StopLoading();

			//userpssw
		},

		//*Login.RemoveScreen *Login.CloseScreen *Login.Close 
		RemoveScreen: function () { //function to close login screen and display menus page
			"loginCont".Animate({ CSSRule: "opacity:0", Time: 400, EndAction: "Login.DeleteScreen()", DoAt: 1.0 })
		},
		DeleteScreen: function () { //will be called from RemoveScreen function to complete its operation
			document.body.removeChild(_("loginCont"));
			Login.ShowMenus(); //show the menus page
		},

		//*Login.Logout *Logout
		Logout: function () { //function to close the menus page and show the login page
			//New Logout Logic
			//1. Clear Cookies
			Cookie.Set("UserDet", "", 1);
			//console.log("set to empty in logout");
			//console.log(Cookie.Get("UserDet"));
			//var cuserdet = Cookie.Get("UserDet");
			//alert(cuserdet);
			Login.CurrentType = 0;
			Login.CurrentUserDet = ""; //clear all user details

			//2. Reload the page
			window.location.reload();
			//clear/reset cookies, variables, costants, object here
			//close the currently opened image if it exist
			/* if (Page.CurrOpen.Trim() != "") {
				Page.Close(Page.CurrOpen);
			}
			// /////////////////////////////////////////////////////
			if (_("mainMenuCont") != null) {
				clearTimeout(Login.AutoDashBoardTimmer);
				Login.AutoDashBoardTimmer = null;
				"mainMenuCont".Animate({ CSSRule: "opacity:0", Time: 400, EndAction: "Login.DeleteMenus()", DoAt: 1.0 })
			} else {
				Login.ShowScreen(); //show the login screen 
			} */


		},
		Validate: function (res) {
			if (res.Trim() == "^##AD_eduporta##^") { return false };
			return true;
		},
		Authenticate: function (res) {
			if (res.Trim() == "^##AD_eduporta##^") {
				MessageBox.Show("Access Denied: Credentials no longer Valid");
				Login.Logout(); Page.MinimizeAll(); Page.HideTaskBar();
				return false
			}
			return true;

		},
		DeleteMenus: function () { //function to complete the Logout operation
			document.body.removeChild(_("mainMenuCont"));

			Login.ShowScreen(); //show the login screen
		},
		MainAjax: new Ajax(),

		//*Login.GetHint *Login.Hint 
		GetHint: function () { //get the passord hint 

			var email = _("usernm"); //get the username - email address
			if (email == null) { //no email/username field found
				MessageBox.Show("#Error on Page, Reload Page"); return;
			}
			//alert('aa');
			if (email.TextContent().Trim() == "") { //no email/username sent
				MessageBox.Show("Enter a valid Email Address"); return;
			}
			_("hintcont").innerHTML = "cog fa-spin".Icon();
			Login.MainAjax.Post(
				{
					"completeHandler": function (res) {
						MessageBox.Show(res);
						_("hintcont").innerHTML = "question".Icon();
					},
					"errorHandler": function (err) {
						MessageBox.Show("#Server Error, Try Again");
						_("hintcont").innerHTML = "question".Icon();
					},
					"abortHandler": function (obj) {
						_("hintcont").innerHTML = "question".Icon();
					},
					Data: "email=" + escape(email.TextContent()) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/Pages/Login/gethint.php"
				}
			)
		},
		LockAjax: new Ajax(),
		LockTimmer: null,
		//*Login.Pin.UnLock *Login.PinUnlock *Login.UnlockPin
		Unlock2: function (pin) {
			if (pin.Trim() == "") { return false; }
			if (Login.LockTimmer != null) {
				clearTimeout(Login.LockTimmer);
				Login.LockTimmer = null;
			}

			Login.LockTimmer = setTimeout(() => {
				Login.LockAjax.abort();
				var detarr = Login.CurrentUserDet.split("~");
				var email = detarr[1];
				//  alert(email);
				Login.LockAjax.Post(
					{
						OnProgress: function (delta) {

						},
						OnComplete: function (res) {
							//alert(res);
							if (res == "#") { //if email not found
								// MessageBox.Show("#The Pin supplied is Invalid");
								return;
							}
							if (res == "##") { //if email not found
								MessageBox.Show("#Invalid Parameters");
								// _("enterbtn").SetStyle("background-image:url(TaquaLB/Elements/Images/enter.png)");
								// _("userpssw").TextEnable();
								return;
							}
							var resarr = res.split("~");
							if (resarr.length < 3) { //if a wrong format responce is gotten
								MessageBox.Show("#Server Error, Try Again");
								// _("enterbtn").SetStyle("background-image:url(TaquaLB/Elements/Images/enter.png)");
								//_("userpssw").TextEnable();
								return;
							}
							Login.CurrentUserDet = res;
							//correct pin
							//Lock.KeyCancel();
							_("screen").SetText(""); //clear the content of the Lock screen
							Lock.Close();
							//_("Screen").SetText("");

						},
						OnError: function (err) {
							MessageBox.Show("#Server Error, Try Again");
						},
						OnAbort: function (obj) {

						},
						Data: "email=" + escape(email) + "&pin=" + escape(pin) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						Action: configdata['Core'] + "cportal/Pages/Login/verifyPin.php"
					});
			}, 100);

		},
		/*Unlockworking:0,*/
		Unlock: function (pin) {
			if (pin.Trim() == "") {
				MessageBox.Show("Please supply a valid Pin");
				Lock.Done();
				return;
			}
			/*if(Login.Unlockworking == 1){
			  MessageBox.Show("Still Validating ....");
			  Lock.Done();
			  return;	
			}*/
			var detarr = Login.CurrentUserDet.split("~");
			//set the working variable to 1 - meaning working
			// Login.Unlockworking = 1;

			var Ajaxs = new Ajax();
			var email = detarr[1];
			//alert(Login.CurrentUserDet)
			//call the post operation
			Ajaxs.PostResponse("email=" + escape(email) + "&pin=" + escape(pin) + "&SubDir=" + encodeURIComponent(configdata['SubDir']), configdata['Core'] + "cportal/Pages/Login/verifyPin.php",
				function (res) {
					res = res.Trim();
					//alert(res);
					Lock.Done();
					//_("enterbtn").SetStyle("background-image:url(TaquaLB/Elements/Images/enter.png)");
					if (res == "#") { //if email not found
						MessageBox.Show("#The Pin supplied is Invalid");
						return;
					}
					if (res == "##") { //if email not found
						MessageBox.Show("#Invalid Parameters");
						// _("enterbtn").SetStyle("background-image:url(TaquaLB/Elements/Images/enter.png)");
						// _("userpssw").TextEnable();
						return;
					}
					var resarr = res.split("~");
					if (resarr.length < 3) { //if a wrong format responce is gotten
						MessageBox.Show("#Server Error, Try Again");
						// _("enterbtn").SetStyle("background-image:url(TaquaLB/Elements/Images/enter.png)");
						//_("userpssw").TextEnable();
						return;
					}
					Login.CurrentUserDet = res;
					//correct pin
					Lock.Close();

				}, "text", function (res) { MessageBox.Show("#Server Error, Connection Problem"); Lock.Done(); });
		}
	}

}();


/************************************************************************************************** */
/*Student Object*/
//*Student
/************************************************************************************************** */
var Student = function () {
	return {
		PreLoad: {
			GenLoader: new GenLoading({ StudyID: "preloadstudy", FacID: "preloadfac", DeptID: "preloaddept", ProgID: "preloadprog", LevelID: "preloadlvl", SemID: "preloadsemest", ClassID: "preloadclass", DisplayLevelID: "DisplayLvl", StartSesID: "preloadstartses" }),
			GenLoaderMigrate: new GenLoading({ StudyID: "mpreloadstudy", FacID: "mpreloadfac", DeptID: "mpreloaddept", ProgID: "mpreloadprog", LevelID: "mpreloadlvl", SemID: "mpreloadsemest", ClassID: "mpreloadclass", DisplayLevelID: "mDisplayLvl", StartSesID: "mpreloadstartses" }),
			LoadAjax: new Ajax(),
			ExportAjax: new Ajax(),
			CurLoaded: [],
			ToggleErrorBox: (btn) => {
				var errbx = _('studclisterr');
				if (errbx.style.display == "none") {
					errbx.style.display = "block";
					btn.innerHTML = '<i class="fa fa-chevron-up"></i> Hide Error Log';
				} else {
					errbx.style.display = "none";
					btn.innerHTML = '<i class="fa fa-chevron-down"></i> Display Error Log';
				}
			},
			SendSMS: () => {
				var biodataPreload = _('biodataPreload');
				if (biodataPreload == null || Student.PreLoad.CurLoaded.length == 0) {
					MessageBox.Show("List not loaded");
					return;
				}
				/* var datas = Student.PreLoad.CurLoaded[0];
						   var pdata = datas+"&SubDir="+encodeURIComponent(configdata['SubDir'])+"&"+biodataPreload.GetDataString();
						   //alert(pdata);
						   //return;
							//MessageBox.Show("Module not Available");
							Student.PreLoad.SaveAjax.Post(
								{
									Action: configdata['Core']+"cportal/"+"Pages/Scripts/Student/savepreload.php",
									PostData: pdata,
									OnProgress: function (delta) {
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
									},
									OnComplete: function (res) {
										//if(!Login.Authenticate(res))return;
										//"Loaded".__();
										//_('preloadsheetbox').innerHTML = res;
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(100);
										
										rtn = JSON.parse(res);
										//console.log(rtn.Errors);
										_('preloaderrbx').innerHTML = rtn.Errors;
										if(rtn.Success == "TRUE"){//if loaded successfully
											//reload the lis
											Student.PreLoad.Load(Student.PreLoad.CurLoaded,true);
											
										}
										MessageBox.Show(rtn.Message)
										// MessageBox.Show(res);
										//"Populated".__();
										
									},
									OnAbort: function (res) {
										
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1,'MessageBox.Show("Operation Aborted");');
				
									},
									OnError: function (res) {
										//MessageBox.Show("" + res);
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1,'MessageBox.Show("#INTERNAL ERROR: '+res.Replace('"','\"')+'");');
									}
								}
							); */
				//get the phone numbers
				phnos = "";
				phnosarr = [];
				var phns = _('classphones');
				if (phns != null) {
					phnos = phns.textContent.Trim();
					phnosarr = phnos.split(",");
				}
				if (phnosarr.length < 1) {
					MessageBox.Show("No Valid Student Phone Number Found");
					return;
				}
				OptionBox.Show({
					Logo: "envelop",
					Title: "Send SMS",
					TitleHTML: OptionBox.Note('<b>' + phnosarr.length + ' Valid Class Student Phone Number Found</b>') + "" + OptionBox.TextBox({ id: 'msgsms', logo: 'pencil', title: 'Message', type: 'multiline', style: '' }),
					Options: [{
						Logo: "paper-plane",
						Title: "Send",
						Info: "Send SMS to all Class Student",
						Function: function (phonnums) {
							//get the message
							var msg = _('msgsms_inp').value;
							//alert(_('msgsms'));
							if (msg.Trim() == "") {
								MessageBox.Show("No Message Supplied"); return;
							}
							//alert(phonnums);
							var pdata = "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Phone=" + encodeURIComponent(phonnums) + "&Msg=" + encodeURIComponent(msg);
							Student.PreLoad.SaveAjax.Post(
								{
									Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Gen/sendsms.php",
									PostData: pdata,
									OnProgress: function (delta) {
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
									},
									OnComplete: function (res) {
										//if(!Login.Authenticate(res))return;
										//"Loaded".__();
										//_('preloadsheetbox').innerHTML = res;
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(100);
										MessageBox.Show(res)
										// MessageBox.Show(res);
										//"Populated".__();

									},
									OnAbort: function (res) {

										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

									},
									OnError: function (res) {
										//MessageBox.Show("" + res);
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
									}
								}
							);
						},
						Parameter: phnos
					},

					{
						Logo: "clone",
						Title: "Copy Numbers",
						Info: "Copy phone numbers of Class Student",
						Function: function (phnostr) {
							if (ClipBoard.CopyText('classphones')) {
								MessageBox.Show("*Class Student Phone Number Copied to Clipboard");
							} else {
								MessageBox.Show("#Copying Class Student Phone Number Failed");
							}
						},
						Parameter: phnos
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current process",
						Function: function () {

						}
					}]

				});
			},
			Load: function (datas, reload) {
				reload = reload || false;
				if (reload) {
					//console.log("Reload - "+datas);
				} else {
					//console.log("Load");
				}
				if (Tabs.Tab("Student").ProgressGet(1).ProgressState() != 0 && reload == false) {
					MessageBox.Show("#System Busy, Try again later");
					return;
				}
				if (typeof datas == _UND) {

					//get all parameters
					datasa = Page.DataStringArray("objgrpelempreload");
					datas = datasa['String'];
					var dataarr = datasa['Array'];
					//console.log("Fresh data - "+datas);
					// 'Fresh Load'.__();
				} else {
					var dataarr = datas[1];
					datas = datas[0];
				}

				//datas.__();
				//alert(datas);

				//cstudy=2&coursefac=5&coursedept=48&courseprog=49&courselvl=1&coursesemest=1
				if (dataarr['preloadprog'].ToNumber() < 1 || dataarr['preloadstartses'].ToNumber() < 1) {
					MessageBox.Show("#INVALID PARAMETER.<br/>Make sure you select all required field");
					return;
				}

				Student.PreLoad.CurLoaded = [datas, dataarr];
				Student.PreLoad.LoadAjax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Student/preload.php",
						PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnProgress: function (delta) {
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
						},
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							//"Loaded".__();

							_('preloadsheetbox').innerHTML = res;
							//"Populated".__();
							_('classlisthome').Hide();
							_('preloadsheet').Show();
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(100);
							Tabs.HideSideBar("Student", 1);
						},
						OnAbort: function (res) {

							Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

						},
						OnError: function (res) {
							//MessageBox.Show("" + res);
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
						}
					}
				);
			},
			Options: (RegNo, id) => {
				OptionBox.Show({
					Logo: "cogs",
					Title: "Perform Action (" + RegNo + ")",
					Options: [{
						Logo: " mbri-left-right",
						Title: "Migrate",
						Info: "Migrate Student to another Class/Batch",
						Function: function (StudID) {
							Student.PreLoad.Migrate(StudID);
						},
						Parameter: id
					},
					{
						Logo: "print",
						Title: "View/Print",
						Info: "Preview an print students academic details",
						Function: function (RegNo) {
							//set to globally update reg no setting 1
							Student.RegReport.PrintRc(RegNo);
						},
						Parameter: RegNo
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current Process",
						Function: function () {

						}
					}]

				});
			},
			SaveAjax: new Ajax(),
			Save: function () {
				var biodataPreload = _('biodataPreload');
				if (biodataPreload == null || Student.PreLoad.CurLoaded.length == 0) {
					MessageBox.Show("List not loaded");
					return;
				}
				//get the cur loaded data

				OptionBox.Show({
					Logo: "save",
					Title: "Save Class List",
					TitleHTML: OptionBox.Note('<b>Delete Operation not allowed</b> <br/> All Cleared or Deleted record will be ignored'),
					Options: [{
						Logo: "check",
						Title: "Continue",
						Info: "Save the loaded class list",
						Function: function (pdatas) {
							var datas = Student.PreLoad.CurLoaded[0];
							var pdata = datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&" + biodataPreload.GetDataString();
							//alert(pdata);
							//return;
							//MessageBox.Show("Module not Available");
							Student.PreLoad.SaveAjax.Post(
								{
									Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Student/savepreload.php",
									PostData: pdata,
									OnProgress: function (delta) {
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
									},
									OnComplete: function (res) {
										//if(!Login.Authenticate(res))return;
										//"Loaded".__();
										//_('preloadsheetbox').innerHTML = res;
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(100);
										/* console.log(res);
										return; */
										rtn = JSON.parse(res);
										//console.log(rtn.Errors);
										_('preloaderrbx').innerHTML = rtn.Errors;
										if (rtn.Success == "TRUE") {//if loaded successfully
											//reload the lis
											Student.PreLoad.Load(Student.PreLoad.CurLoaded, true);

										}
										MessageBox.Show(rtn.Message)
										// MessageBox.Show(res);
										//"Populated".__();

									},
									OnAbort: function (res) {

										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

									},
									OnError: function (res) {
										//MessageBox.Show("" + res);
										Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
									}
								}
							);
						},
						Parameter: null
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current process",
						Function: function () {

						}
					}]

				});

			},
			Print: function () {
				//get current user det
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet != "") {
					var resarr = cuserdet.split("~");
					var userID = resarr[0]
				} else {
					var userID = 0;
				}

				//var biodataPreload = _('biodataPreload');
				if (Student.PreLoad.CurLoaded.length == 0) {
					MessageBox.Show("List not loaded");
					return;
				}

				datas = Student.PreLoad.CurLoaded[1];


				datas['UID'] = userID;
				var datastr = JSON.stringify(datas);
				//console.log(datastr);
				PDFPrinter.Print(configdata.Core + "cportal/Reports/Student/classlist.php", "data=" + escape(datastr) + "&paper=A4&orientation=P&MT=4&MB=30&SubDir=" + encodeURIComponent(configdata.SubDir));

			},
			Export: function () {
				MessageBox.Show("Note: Export will export all records to Excel format");
				//get current user det
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet != "") {
					var resarr = cuserdet.split("~");
					var userID = resarr[0]
				} else {
					var userID = 0;
				}

				if (Student.PreLoad.CurLoaded.length == 0) {
					MessageBox.Show("List not loaded");
					return;
				}

				datas = Student.PreLoad.CurLoaded[1];


				datas['UID'] = userID;
				datas['export'] = "true";
				var datastr = JSON.stringify(datas);

				Student.PreLoad.ExportAjax.Post({
					Action: configdata['Core'] + "cportal/Reports/Student/classlist.php",
					PostData: "data=" + escape(datastr) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						if (res.Trim().substr(0, 6).toLowerCase() == "<table") {
							tableToExcel(res, 'Class List');
						} else {
							MessageBox.Show(res);
						}
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					},
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						_("Studenttab").ProgressGet(1).ProgressTo(perc);
					},
					OnError: function (res) {
						MessageBox.Show("#Error :" + res);
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					},
					OnAbort: function (res) {
						MessageBox.Show("Report Export Aborted");
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					}
				})
			},
			Migrate: StudID => {
				StudID = StudID || 0;
				if (StudID == 0) { //migrate all
					OptionBox.Show({
						Title: "Class Migration",
						TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Student/loadfields.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
						Options: [{
							Logo: "share-square",
							Title: "Migrate All",
							Info: "Move all Student to selected class",
							Function: function (StudID) {
								Student.PreLoad.PerformMigrate(StudID);
							},
							Parameter: StudID
						},

						{
							Logo: "times",
							Title: "Cancel Process",
							Info: "Cancel the current Process",
							Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
						}]

					});
				} else {
					OptionBox.Show({
						Title: "Class Migration",
						TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Student/loadfields.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
						Options: [{
							Logo: "share-square",
							Title: "Migrate Student",
							Info: "Move Student to selected class",
							Function: function (StudID) {
								Student.PreLoad.PerformMigrate(StudID);
							},
							Parameter: StudID
						},

						{
							Logo: "times",
							Title: "Cancel Process",
							Info: "Cancel the current Process",
							Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
						}]

					});
				}
				/* Student.PreLoad.LoadAjax.Post({
					Action: configdata['Core']+"cportal/Pages/Scripts/Student/loadfields.php",
					PostData: "SubDir="+encodeURIComponent(configdata['SubDir']),
					OnComplete: function (res) {
						//alert(res);
						//if(!Login.Authenticate(res))return;
						if (res.Trim().substr(0, 1).toLowerCase() == "#") {
							MessageBox.Show(res);
						} else {
						    
						}
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					},
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						_("Studenttab").ProgressGet(1).ProgressTo(perc);
					},
					OnError: function (res) {
						MessageBox.Show("#Error :" + res);
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					},
					OnAbort: function (res) {
						MessageBox.Show("Report Export Aborted");
						_("Studenttab").ProgressGet(1).ProgressTo(100);
					}
				}); */

			},
			PerformMigrate: StudID => {
				var biodataPreload = _('biodataPreload');
				if (biodataPreload == null || Student.PreLoad.CurLoaded.length == 0) {
					MessageBox.Show("List not loaded");
					return;
				}
				var datas = Student.PreLoad.CurLoaded[0];
				//get the migratte details
				//{ StudyID: "mpreloadstudy", FacID: "mpreloadfac", DeptID: "mpreloaddept", ProgID: "mpreloadprog", LevelID: "mpreloadlvl", SemID: "mpreloadsemest", ClassID:"mpreloadclass",DisplayLevelID:"mDisplayLvl", StartSesID:"mpreloadstartses" }
				var mpreloadstudy = _('mpreloadstudy').ValueContent();
				var mpreloadprog = _('mpreloadprog').ValueContent();
				var mpreloadclass = _('mpreloadclass').ValueContent();
				var mpreloadstartses = _('mpreloadstartses').ValueContent();
				if (mpreloadstudy == "" || mpreloadprog == "" || mpreloadstartses == "") {
					MessageBox.Show("Invalid Migration Class Selected"); return;
				}
				datas += "&mpreloadstudy=" + mpreloadstudy + "&mpreloadprog=" + mpreloadprog + "&mpreloadclass=" + mpreloadclass + "&mpreloadstartses=" + mpreloadstartses;
				if (StudID < 1) {
					var pdata = datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&" + biodataPreload.GetDataString();
				} else {
					pdata = datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&StudID=" + StudID;
				}

				// alert(pdata);
				//return;
				//MessageBox.Show("Module not Available");
				Student.PreLoad.LoadAjax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Student/migratepreload.php",
						PostData: pdata,
						OnProgress: function (delta) {
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
						},
						OnComplete: function (res) {
							//if(!Login.Authenticate(res))return;
							//"Loaded".__();
							//_('preloadsheetbox').innerHTML = res;
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(100);

							rtn = JSON.parse(res);
							//console.log(rtn.Errors);

							if (rtn.Success == true) {//if loaded successfully
								//reload the lis
								Student.PreLoad.Load(Student.PreLoad.CurLoaded, true);

							}
							MessageBox.Show(rtn.Message)
							// MessageBox.Show(res);
							//"Populated".__();

						},
						OnAbort: function (res) {

							Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

						},
						OnError: function (res) {
							//MessageBox.Show("" + res);
							Tabs.Tab("Student").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
						}
					}
				);
			}
		},
		GenLoader: new GenLoading({ StudyID: "studstudy", FacID: "studfac", DeptID: "studdept", ProgID: "studprog", LevelID: "studlvl", ClassID: "studclass", DisplayLevelID: "exlvl", StartSesID: "studstartses" }),
		GetLevel: () => {
			SRegNo = "";
			var srst = _("searchStud");
			if (!Null(srst)) {
				SRegNo = selectedRegNo = srst.SelectedStudent();
			}
			var oplvl = _('oplvl');
			var exlvl = _('exlvl');
			if (SRegNo == "") {
				oplvl.innerHTML = "--";
				exlvl.innerHTML = "--";
				return;
			}
			//get the selected startses
			var startses = _("studstartses").ValueContent();
			oplvl.innerHTML = '<i class="fa fa-spin fa-cog"></i>';
			exlvl.innerHTML = '<i class="fa fa-spin fa-cog"></i>';
			var aj = new Ajax();
			aj.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Student/loadStudLSDet.php",
				PostData: "RegNo=" + encodeURIComponent(SRegNo) + "&StartSes=" + encodeURIComponent(startses) + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']),
				OnComplete: function (res, url, param) {
					// alert(res);
					try {
						var dt = JSON.parse(res);
						oplvl.innerHTML = dt.OpLevelName + " | " + dt.OpSemesterName;
						exlvl.innerHTML = dt.ExLevelName + " | " + dt.ExSemesterName;
					} catch (error) {
						oplvl.innerHTML = "--";
						exlvl.innerHTML = "--";
					}


				},
				OnAbort: function (res) {
					oplvl.innerHTML = "--";
					exlvl.innerHTML = "--";
				}
			});
		},
		/*Biodata Module*/
		//*Student.BioData *Biodata
		BioData: {
			/*Biodata Search Module*/
			Fields: ["surnametxt", "firstnametxt", "othernametxt", "studDOB", "studgender", "studstatus", "studreligion", "studpassp", "stateorig", "lga", "nat", "bdemail", "studphone", "studaddr", "nkname", "nkphone", "nkaddr", "studregNo", "jambNo", "studstudy", "studprog", "studlvl", "modeentry", "jambscor", "studReglvl", "regDate", "adDate", "studfac", "studdept", "olvlRstDet", "olvlRst", "studaccescode"],
			Ajax: new Ajax(),
			SearchAjax: null, //ajax of object loading the search result
			SearchLoaded: 0, //holds the total number loaded
			CurSearcParam: "",//hold the current serach criterial and serach text
			SearchBoxSrolled: function () {
				if ((_("searchrst").scrollHeight - _("searchrst").scrollTop <= _("searchrst").style.height.ToNumber() + 10) && Student.BioData.SearchLoaded > 0) {
					Student.BioData.Search();
				}
				//document.getElementById().scrollHeight;
				//document.getElementById().scrollTop
				//Tracer.Tag("Scrolled");
			},
			ReSearch: function () {
				Student.BioData.SearchLoaded = 0;
				Student.BioData.Search();
			},
			//*Student.Biodata.Serach *Biodata.searchStudent
			Search: function (obj) {

				//Tracer.Start("Search Start");
				//Tracer.Tag("Start Index: "+Student.BioData.SearchLoaded);	
				var searchcrit = _("searchCriterial").ValueContent();
				//__(searchcrit);
				if (searchcrit == null || searchcrit.Trim() == "") { //if no criterial selected
					MessageBox.Show("Select a valid search criterial");
					//Tracer.Tag("No Search Criterial Supplied");
					return;
				}
				if (typeof obj != "undefined") { //if search criterial is selected, i.e is obj sent (onchange handler of the textbox)
					_("searchtxt").TextFocus();
				}


				var searchval = _("searchtxt").TextContent();
				//if the search parameter has changed and load search start index is greater than 0, reset it back to, meaning load a fresh search
				if (Student.BioData.CurSearcParam != searchcrit + ";" + searchval && Student.BioData.SearchLoaded > 0) {
					Student.BioData.SearchLoaded = 0;
					//Tracer.Tag("Search start index reset to zero(0) due to change in the start parameters, for fresh searching");
				}
				if (Student.BioData.SearchAjax != null) {
					Student.BioData.SearchAjax.abort();
					Student.BioData.SearchAjax = null;
					//Tracer.Tag("Current searching aborted, due to new search request");
				}
				var searchrst = _("searchrst");
				var totsearch = _("totsearch");
				var searchloadbx = _("searchloadbx");
				var moreloading = _('moreloading');

				var src = configdata['Core'] + "cportal/Pages/Scripts/Student/studsearch.php?crit=" + escape(searchcrit) + "&val=" + escape(searchval) + "&startindex=" + Student.BioData.SearchLoaded + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']);
				if (Student.BioData.SearchLoaded == 0) { //if searching for the first trip
					searchrst.FadeOut(200);
					searchloadbx.Animate({ CSSRule: "opacity:1;visibility:visible", Time: 300 });
					totsearch.Text("--");
					//clear the current result
					searchrst.innerHTML = "";
					//Tracer.Tag("First Trip Search");
				}
				Student.BioData.CurSearcParam = searchcrit + ";" + searchval; //set the search param (criterial and text)
				//Tracer.Tag(Student.BioData.SearchLoaded);
				if (Student.BioData.SearchLoaded > 0) moreloading.Animate({ CSSRule: "visibility:visible;opacity:1", Time: 200 });
				Student.BioData.SearchAjax = searchrst.AppendHTML(src, function (res) {
					// _("searchrst").Animate({CSSRule:"opacity:1",Time:300});
					//Tracer.Tag("Return from Server");
					totobj = _("totrw_searchStud");
					if (!Null(totobj)) { //loaded completely
						var rws = totobj.value.ToNumber() - 1;
						//alert(rws);
						if (rws > 0) {
							totsearch.Text(rws);
						} else {
							totsearch.Text("Empty Set");
						}
						Student.BioData.SearchLoaded = 0; //reset limit index back to 0 , meaning any subsequent load will start over
						//Tracer.Tag("Load/Search Complete");
					} else { //if loading not complete
						//Tracer.Tag("Search not complete");

						Student.BioData.SearchLoaded += 500; //increament load limit index to start from record 500
						totsearch.Text(Student.BioData.SearchLoaded + "*");
						//continue loading
						//Tracer.Tag("Trying to continue load for start index: "+Student.BioData.SearchLoaded);

					}
					searchrst.FadeIn(300);
					[searchloadbx, moreloading].Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 });
					// _().Animate({CSSRule:"visibility:visible;opacity:1",Time:200});
				}, function () { });

				// alert(searchcrit + ";" + searchval);
			},
			LoadLevelDet: 0, //the current loading detatls group id
			//load the student details
			//*Student.BioData.LoadStudent *BioData.LoadStudent
			LoadStudent: function (obj) {
				if (typeof obj == 'undefined') {
					_('studentrecdefault').Hide();
					_('biodatafrm').Show();
					return;
				}
				//#Loading Student'.__()
				//Start Student Data Loading'.__()
				//alert(obj.Text());return;
				var RegNo = obj.Data("id");
				//alert(RegNo);
				RegNo = RegNo.Trim();
				//	Student.BioData.StartLoadStudent(RegNo);
				Student.BioData.LoadStudentReal(RegNo);
			},
			NumLoaded: 0, //the number of group loaded
			StartLoadStudent: function (RegNo) {
				//if(_("Studenttab").ProgressGet(0).ProgressState() == 1){MessageBox.Show("System Busy");return;}


				//Start Loading by calling the real loading function (LoadStudentReal), moving 40% progress'.__()
				//_("Studenttab").ProgressGet(0).ProgressTo(30,'
				//$grpbxes = ["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg","bDatagrppayrec","bDatagrpcreg"];
				//	$grpbxes.Animate({ CSSRule: "opacity:0.2", Time: 700 });
				//	Student.BioData.NumLoaded = 0; //reset the total number of group loaded
				CoverScreen.Show("ldst", 'Please wait for a few seconds ...<div style="font-size:0.6em">while we load the Student Details</div>', function () {
					//for(var s=0;s <	$grpbxes.length;s++){
					//setTimeout("Student.BioData.LoadStudentReal('"+RegNo+"', "+s+")",10);
					Student.BioData.LoadStudentReal(RegNo, s);
					//	}
					/* Student.BioData.LoadStudentReal(RegNo, 0);Student.BioData.LoadStudentReal(RegNo, 1); Student.BioData.LoadStudentReal(RegNo, 2); Student.BioData.LoadStudentReal(RegNo, 3); Student.BioData.LoadStudentReal(RegNo, 4); Student.BioData.LoadStudentReal(RegNo, 5); Student.BioData.LoadStudentReal(RegNo, 6);*/
				});
				//'); //start the progress bar 
			},
			LoadStudentGroup: ["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg", "bDatagrppayrec", "bDatagrpcreg"],
			loadstage: 0,
			loadData: null,
			SetHTML: function () {
				if (Student.BioData.loadData != null) {
					_(Student.BioData.LoadStudentGroup[Student.BioData.loadstage] + "bx").innerHTML = Student.BioData.loadData[Student.BioData.LoadStudentGroup[Student.BioData.loadstage]];
					Student.BioData.loadstage++;
					if (Student.BioData.loadstage < Student.BioData.LoadStudentGroup.length) {
						var de = Math.floor((Student.BioData.loadstage / (Student.BioData.LoadStudentGroup.length - 1)) * 50);
						Tabs.Tab("Student").ProgressGet(0).ProgressTo(de, "Student.BioData.SetHTML()");
					} else {
						Student.BioData.loadData = null;
						Student.BioData.loadstage = 0;
					}

				}
			},
			LoadStudentReal: function (RegNo, loadlvl) {
				//'function to realy perform the load operation'.__()
				var dat = "regNo=" + escape(RegNo) + "&loadlevel=" + loadlvl + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']);
				//	var dat = "regNo="+escape(RegNo)+"&loadlevel="+Student.BioData.LoadLevelDet;
				//'Student data for update: '+dat .__();
				//'Loading from server script' .__();
				var aj = new Ajax();
				Tabs.ProgressSetAbort("Student", 0, aj);
				Student.BioData.loadstage = 0;
				//	_("Studenttab").ProgressGet(0).ProgressTo(100,'MessageBox.Show("#Student not Found");');
				aj.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/loadStudData.php",
					PostData: dat,
					OnProgress: function (delta) {
						Tabs.Tab("Student").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
					},
					OnComplete: function (res, url, param) {
						//'loaded from server script'.__();
						// return;
						//console.log(res);
						var jobj = JSON.parse(res);
						Student.BioData.loadData = jobj;
						if (typeof jobj['Error'] != _UND) {
							MessageBox.Show("#" + jobj['Error']);
							Tabs.Tab("Student").ProgressGet(0).ProgressTo(0);
						} else {
							//Student.BioData.SetHTML();
							for (var df = 0; df < Student.BioData.LoadStudentGroup.length; df++) {
								setTimeout('_(Student.BioData.LoadStudentGroup[' + df + ']+"bx").innerHTML = Student.BioData.loadData[Student.BioData.LoadStudentGroup[' + df + ']];Tabs.Tab("Student").ProgressGet(0).ProgressTo(50 + Math.floor(((' + df + '+1)/Student.BioData.LoadStudentGroup.length) * 50));', 100);
								//_(Student.BioData.LoadStudentGroup[df]+"bx").innerHTML = jobj[Student.BioData.LoadStudentGroup[df]];
								//	Student.BioData.LoadStudentGroup[df].Animate({ CSSRule: "opacity:1", Time: 400 });
							}

						}
						_('studentrecdefault').Hide();
						_('biodatafrm').Show();
						Tabs.HideSideBar('Student', 0);
						//	Student.BioData.LoadStudentGroup.Animate({ CSSRule: "opacity:1", Time: 400 });
						//CoverScreen.Close(_("ldst"));
					},
					OnAbort: function (res) {
						MessageBox.Show("Operation Aborted");
					}
				});
				//Student.BioData.Ajax
				/* 	aj.PostResponse(dat, "Pages/Scripts/Student/loadStudData.php",
						function (res, url, param) {
							//'loaded from server script'.__();
							// return;
							 var jobj = JSON.parse(res);
							 if(typeof jobj['Error'] != _UND){
								 MessageBox.Show("#"+jobj['Error']);
								
								
							 }else{
				  for(var df=0; df<Student.BioData.LoadStudentGroup.length;df++){
					  _(Student.BioData.LoadStudentGroup[df]+"bx").innerHTML = jobj[Student.BioData.LoadStudentGroup[df]];
									//	Student.BioData.LoadStudentGroup[df].Animate({ CSSRule: "opacity:1", Time: 400 });
								}
							 }
							 Student.BioData.LoadStudentGroup.Animate({ CSSRule: "opacity:1", Time: 400 });
							 CoverScreen.Close(_("ldst"));
	
	//alert(res);
							 return; */
				/* res = res.Trim();
				if (res.Trim() == "0") {
					//'Cannot Load Student'.__();
					//Tracer.End();
					// _("Studenttab").ProgressGet(0).ProgressTo(100,'MessageBox.Show("#Student not Found"); ["bDatagrpDet","bDatagrpSch","bDatagrpPassp","bDatagrpCont","bDatagrpNOK","bDatagrpRstDet","bDatagrpReg"].Animate({CSSRule:"opacity:1",Time:700});');
					MessageBox.Show("#Student not Found");
					["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg","bDatagrppayrec","bDatagrpcreg"].Animate({ CSSRule: "opacity:1", Time: 400 });
				//var ldst = _("ldst");
					CoverScreen.Close(_("ldst"));
					return;
				}
				//'Split data from server'.__();
				var resarr = res.split("@#@!");

				if (resarr.length > 0) {
					// alert(param);
					var loadlevel = param["loadlevel"].ToNumber();

					var regNo = param["regNo"];
					//('Load group :'+loadlevel).__();
					// ('Student.BioData.LoadNextGroup('+loadlevel+',"'+regNo+',"'+res+'")').__();

					//_("Studenttab").ProgressGet(0).ProgressTo(70 + (loadlevel * 10),'Student.BioData.LoadNextGroup('+loadlevel+',"'+regNo+'","'+res+'")');
					Student.BioData.LoadNextGroup(loadlevel, regNo, res);

				
				} else {
					MessageBox.Show("#Student Record not Found");
					["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg","bDatagrppayrec","bDatagrpcreg"].Animate({ CSSRule: "opacity:1", Time: 400 });
					CoverScreen.Close(_("ldst"));
					// _("Studenttab").ProgressGet(0).ProgressTo(100);
					return;
				}
				// Tracer.End();
				// alert(res); */
				/* 	}, "text", function (res) {
						MessageBox.Show("#Server Error, Connection Problem");
						// _("Studenttab").ProgressGet(0).ProgressTo(100);
						// ["bDatagrpDet","bDatagrpSch","bDatagrpPassp","bDatagrpCont","bDatagrpNOK","bDatagrpRstDet","bDatagrpReg"].Animate({CSSRule:"opacity:1",Time:700});
						//Student.BioData.Clear();
						["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg","bDatagrppayrec","bDatagrpcreg"].Animate({ CSSRule: "opacity:1", Time: 400 });
						CoverScreen.Close(_("ldst"));
					}); */
				//alert(RegNo);
			},
			GroupCurrent: new Array(),//holds the current data of each group
			LoadVal: 0,
			ProgressLoaded: function (increm) {
				//setTimeout('Student.BioData.ProgressLoadedReal('+increm+')',100);
				Student.BioData.LoadVal += increm;
				//_("Studenttab").ProgressGet(0).ProgressTo(Student.BioData.LoadVal);
				//console.log("+"+increm+" = "+ Student.BioData.LoadVal);
				if (Student.BioData.LoadVal >= 100) {
					Student.BioData.LoadVal = 0;
					CoverScreen.Close(_("ldst"));
				}
			},
			/* ProgressLoadedReal:function(increm){
				
			}, */
			LoadNextGroup: function (loadlevel, regNo, res) {
				//'function to load student data on level bases'.__()
				/*if(res == "#"){ //try again
					'Error Loading, Try Again'.__()
					Student.BioData.LoadStudentReal(regNo);
					return;
				}*/
				var resarr = res.split("@#@!");
				var grpbxarr = ["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg", "bDatagrppayrec", "bDatagrpcreg"];
				var grpnmarr = ["Details", "School", "Passport", "Contact", "Next of Kin", "Result Details", "Registration", "Payment Records", "Course Registration"];
				var currentlyDisplayed = false;
				//_(grpbxarr[loadlevel] + "_grpdata").value.Trim()
				//console.log(grpbxarr[loadlevel]);
				var lvlobj = _(grpbxarr[loadlevel] + "_grpdata");
				if (lvlobj.value.Trim() != "") {
					if (lvlobj.value.Trim() == res) { //check if curent display is the loaded
						//currentlyDisplayed = true;
					}
				}
				//"#Compare loaded and saved".__();
				switch (loadlevel) {
					case 0://basicdetails
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							/* var fileds = ['surnametxt','firstnametxt','othernametxt','studDOB','studgender','studstatus','studreligion'];
							
							for(var s=0;s<7;s++){
								var pr = ";Student.BioData.ProgressLoaded(3)";
								if(s == 3)
								{resarr[s] = Utility.FromMySqlDate(resarr[s]);//pr=""
							}
							   setTimeout("_('"+fileds[s]+"').SetText('"+resarr[s]+"')"+pr,10);  
							}
							
							lvlobj.value = res; //set the current group data */
							_('bDatagrpDetbx').innerHTML = res;
							Student.BioData.ProgressLoaded(21);
						} else {
							Student.BioData.ProgressLoaded(21);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// Student.BioData.NumLoaded++;
						//_(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						// Student.BioData.LoadLevelDet++; **
						//_(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						// Student.BioData.LoadStudentReal(regNo); **
						//_("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						break;
					case 2://passport
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed || resarr[0].Trim() == "") {
							// _("uploadpw").StartLoading();
							// resarr[0] = resarr[0].Trim() == ""?"TaquaLB/Elements/Images/defaultpassport.png":resarr[0];
							// _("studpassp").SetImage(resarr[0],function(){_("uploadpw").StopLoading()},function(){MessageBox.Show("#Invalid Image");_("uploadpw").StopLoading()});
							//console.log(resarr[0]);
							/* if (resarr[0].Trim() == "") {
								setTimeout('_("studpassp").ClearImagePad();Student.BioData.ProgressLoaded(6)',10);
							} else {
								setTimeout('_("studpassp").SetPadImage("'+resarr[0]+'");Student.BioData.ProgressLoaded(6)',10);
							}
							lvlobj.value = res; //set the current group data */
							_('bDatagrpPasspbx').innerHTML = res;
							Student.BioData.ProgressLoaded(6);
						} else {
							Student.BioData.ProgressLoaded(6);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// _("temppass").value = ""; //reset the change paassport filename to empty

						// _(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						// Student.BioData.LoadLevelDet++; **
						// _(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						// Student.BioData.LoadStudentReal(regNo); **
						// _("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						//	Student.BioData.NumLoaded++;
						break;
					case 3://contact
						//("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							/* setTimeout('_("stateorig").SetText("'+resarr[0]+'", "lga:'+resarr[1]+'");Student.BioData.ProgressLoaded(4)',10); 
							setTimeout('_("nat").SetText("'+resarr[2]+'");Student.BioData.ProgressLoaded(4)',10); 
							setTimeout('_("bdemail").SetText("'+resarr[3]+'");Student.BioData.ProgressLoaded(3)',10);
							setTimeout('_("studphone").SetText("'+resarr[4]+'");Student.BioData.ProgressLoaded(3)',10); 
							setTimeout('_("studaddr").SetText("'+resarr[5]+'");Student.BioData.ProgressLoaded(4)',10);
							lvlobj.value = res; //set the current group data */
							_('bDatagrpContbx').innerHTML = res;
							Student.BioData.ProgressLoaded(18);
						} else {
							Student.BioData.ProgressLoaded(18);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// _(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						//Student.BioData.LoadLevelDet++; **
						// _(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						// Student.BioData.LoadStudentReal(regNo); **
						//_("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						// Student.BioData.NumLoaded++;
						break;
					case 4://NK
						//("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							/* 	setTimeout('_("nkname").SetText("'+resarr[0]+'");Student.BioData.ProgressLoaded(3)',10); 
								setTimeout('_("nkphone").SetText("'+resarr[1]+'");Student.BioData.ProgressLoaded(3)',10); 
								setTimeout('_("nkaddr").SetText("'+resarr[2]+'");Student.BioData.ProgressLoaded(3)',10); */

							//lvlobj.value = res; //set the current group data
							_('bDatagrpNOKbx').innerHTML = res;
							Student.BioData.ProgressLoaded(9);
						} else {
							Student.BioData.ProgressLoaded(9);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						//_(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						// Student.BioData.LoadLevelDet++; **
						//_(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						// Student.BioData.LoadStudentReal(regNo); **
						//_("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						// Student.BioData.NumLoaded++;
						break;
					case 1://school det
						//("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							/* setTimeout('_("studregNo").SetText("'+resarr[0]+'");Student.BioData.ProgressLoaded(3)',10); 
							setTimeout('_("jambNo").SetText("'+resarr[1]+'");Student.BioData.ProgressLoaded(3)',10);
							setTimeout('_("studstudy").SetText("'+resarr[2]+'", "studfac:'+resarr[3]+';studdept:'+resarr[4]+';studprog:'+resarr[5] +';studlvl:'+resarr[6]+'");Student.BioData.ProgressLoaded(4)',10); 
							setTimeout('_("modeentry").SetText("'+resarr[7]+'");Student.BioData.ProgressLoaded(4)',10); */
							_('bDatagrpSchbx').innerHTML = res;
							Student.BioData.ProgressLoaded(14);
							//lvlobj.value = res; //set the current group data
						} else {
							Student.BioData.ProgressLoaded(14);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// _(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						// Student.BioData.LoadLevelDet++; **
						//_(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						//Student.BioData.LoadStudentReal(regNo); **
						//_("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						//Student.BioData.NumLoaded++;
						break;
					case 5://Result
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							//resarr[0] = escape(resarr[0]);
							//resarr[1] = escape(resarr[1]);
							//console.log(resarr[1]);
							/* setTimeout('_("jambscor").SetText("'+resarr[0]+'");Student.BioData.ProgressLoaded(2)',10);
							setTimeout('Student.BioData.SetOlevelDet("'+resarr[1]+'");Student.BioData.ProgressLoaded(4)',10);
							setTimeout('Student.BioData.SelectOlevelRst("'+resarr[2]+'");Student.BioData.ProgressLoaded(4)',10); *///
							_('bDatagrpRstDetbx').innerHTML = res;
							//lvlobj.value = res; //set the current group data
							Student.BioData.ProgressLoaded(10);
						} else {
							Student.BioData.ProgressLoaded(10);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// _(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						//Student.BioData.LoadLevelDet++; **
						// _(grpbxarr[Student.BioData.LoadLevelDet]).Animate({CSSRule:"opacity:0.3",Time:700});
						// Student.BioData.LoadStudentReal(regNo); **
						// _("Studenttab").ProgressGet(0).ProgressTo(50 + (loadlevel * 10));
						break;
					case 6://reg
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							//console.log(resarr);
							/* setTimeout('_("studReglvl").SetText("'+resarr[0]+'");Student.BioData.ProgressLoaded(4)',10); 
							setTimeout('_("regDate").SetText(Utility.FromMySqlDate("'+resarr[1]+'"));Student.BioData.ProgressLoaded(2)',10);
							//console.log("Start");
							setTimeout('_("adDate").SetText(Utility.FromMySqlDate("'+resarr[2]+'"));Student.BioData.ProgressLoaded(2)',10);
							//console.log("End");
							setTimeout('_("studaccescode").SetText("'+resarr[3]+'");Student.BioData.ProgressLoaded(2)',10);  */
							_('bDatagrpRegbx').innerHTML = res;
							Student.BioData.ProgressLoaded(10);
							//lvlobj.value = res; //set the current group data
						} else {
							Student.BioData.ProgressLoaded(10);
							//MessageBox.Show("No change found for group <strong>" + grpnmarr[loadlevel] + "</strong>, Save Changes and Reload");
						}
						// _(grpbxarr[loadlevel]).Animate({CSSRule:"opacity:1",Time:700});
						// Student.BioData.LoadLevelDet = 0;
						//_("Studenttab").ProgressGet(0).ProgressTo(100);
						// "".__();
						// 'Load Completed'.__();
						//Tracer.End();
						//Student.BioData.LoadStudentReal(param["regNo"]);
						break;
					case 7://paydetails
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							//console.log(resarr);
							_('studpayrecbx').innerHTML = resarr[0];

							//lvlobj.value = res; //set the current group data
						} //else {
						Student.BioData.ProgressLoaded(6);
						break;

					case 8://courseregdetails
						// ("Loaded "+grpnmarr[loadlevel]+" = " + res).__();
						if (!currentlyDisplayed) {
							//console.log(resarr);
							_('studcourserecbx').innerHTML = resarr[0];

							lvlobj.value = res; //set the current group data
						} //else {
						Student.BioData.ProgressLoaded(6);
						break;
				}
				_(grpbxarr[loadlevel]).Animate({ CSSRule: "opacity:1", Time: 600 });
				Student.BioData.NumLoaded++;
				if (Student.BioData.NumLoaded >= 6) {
					//CoverScreen.Close(_("ldst"));
				}
			},
			//function to set olevel details
			//*Login.BioData.SetOlevelDetails *BioData.SetOlevelDetails
			SetOlevelDet: function (olvlDet) {
				var rstdet = unescape(olvlDet).Trim(); //get the result details
				if (rstdet == "") { Student.BioData.ClearOlevelDet(); return; }
				//split sittings
				var rstdetsittigs = rstdet.split("###");
				for (var w = 0; w < 2; w++) {
					//for (var w = 0; w < rstdetsittigs.length; w++) {
					if (typeof rstdetsittigs[w] != "undefined") {
						if (rstdetsittigs[w].Trim() != "") {
							ssittingdet = rstdetsittigs[w];
							var rstdetarr = ssittingdet.split("`~");
							if (rstdetarr.length >= 4) {
								var schnme = rstdetarr[0];
								var exmyear = rstdetarr[1];
								var exmno = rstdetarr[2];
								var exmtp = rstdetarr[3].ToNumber();
								exmtp = exmtp == 0 ? 1 : exmtp;
								var exmbtch = typeof rstdetarr[4] == _UND ? 1 : rstdetarr[4];

								// alert(w);
								//olvrstxamtype , olvrstxamyear , olvrstschn
								_("olvrstschn" + (w + 1)).SetText(schnme);
								_("olvrstxamyear" + (w + 1)).SelectText(exmyear);
								_("olvrstxamtype" + (w + 1)).SelectText(exmtp);
								_("olvexmbatch" + (w + 1)).SelectText(exmbtch);
								_("olvexamno" + (w + 1)).SetText(exmno);
							} else {
								Student.BioData.ClearOlevelDet((w + 1)); return;
							}
						} else { Student.BioData.ClearOlevelDet((w + 1)); return }
					} else { Student.BioData.ClearOlevelDet((w + 1)); return }
				}

				// var ssittingdet = ""; //second sitting dets




				//return true;
			},
			//*Student.Biodata.ClearOlevelDetails *Biodata.ClearOlevelDetails
			ClearOlevelDet: function (sitting) {//function to clear the olevel details
				sit = typeof sitting == _UND ? 0 : sitting;
				var setter = function (sitnum) {
					_("olvrstschn" + sitnum).ClearText();
					_("olvrstxamyear" + sitnum).ClearText();
					_("olvrstxamtype" + sitnum).ClearText();
					_("olvexmbatch" + sitnum).ClearText();
					_("olvexamno" + sitnum).ClearText();

					/* 	_("olvrstschn" + (w + 1)).SetText(schnme);
								_("olvrstxamyear" + (w + 1)).SelectText(exmyear);
								_("olvrstxamtype" + (w + 1)).SelectText(exmtp);
								_("olvexmbatch" + (w + 1)).SelectText(exmbtch);
								_("olvexamno" + (w + 1)).SetText(exmno); */
				}
				if (sit != 0) {
					setter(sit);
				} else {//clear all
					setter(1); setter(2);
				}
			},
			//*Student.Biodata.ClearOlevelResult *Biodata.ClearOlevelResult
			ClearOlevelRst: function () { //function to clear all Olevel Result
				//clear the school names fields
				//_("olvrstxamtype1").ClearText();

				totRecinput = _("totrw_olevelrst");
				if (!IsNull(totRecinput)) { //if the total rows input element exist
					var totrw = totRecinput.value.ToNumber(); //get the total rows
					if (totrw > 0) { //if rows exist
						//totrw = totrw - 1; //remove the header
						for (var h = 2; h < totrw; h++) {
							var firstcell = _("olevelrst_rw_" + h + "_1");
							if (!IsNull(firstcell)) {
								if (firstcell.Text() != "") {
									var color = Student.BioData.GetGradeColor("");
									firstcell.SetStyle("color:" + color[0]);
									firstcell.Text("");
								}
							}
							var secondcell = _("olevelrst_rw_" + h + "_3");
							if (!IsNull(secondcell)) {
								if (secondcell.Text() != "") {
									var color = Student.BioData.GetGradeColor("");
									secondcell.SetStyle("color:" + color[0]);
									secondcell.Text("");
								}
							}
						}
						//reset total result to zero
						//_("olevelrst_rw_"+totrw+"_2").Text("P0|F0|T0");
						//_("olevelrst_rw_"+totrw+"_3").Text("P0|F0|T0");
					}
				}
				//return true;
			},
			CalculateTotals: function () {//function to calculate total results
				var totrw = _("olevelrst").TotalRows();
				var p = [0, 0], f = [0, 0], column = [1, 3];
				for (var g = 2; g < totrw; g++) {
					for (var c = 0; c < column.length; c++) {
						var cl = column[c];
						//get the cell
						var curcell = _("olevelrst_rw_" + g + "_" + cl);
						if (!Null(curcell)) {
							var currgrd = curcell.Text().Trim();
							//alert(currgrd);
							if (currgrd == "") { continue; };
							var grdtp = Student.BioData.GetGradeColor(currgrd);
							//grdtp = grdtp[1]
							p[c] = (grdtp[1] == "P") ? p[c] + 1 : p[c]; //increament pass if pass
							f[c] = (grdtp[1] == "F") ? f[c] + 1 : f[c];//increament fail if fail
							//alert(grdtp[1]);
						}
					}
				}
				t = [p[0] + f[0], p[1] + f[1]]
				_("olevelrst_rw_" + totrw + "_1").Text("P" + p[0] + "|F" + f[0] + "|T" + t[0]);
				_("olevelrst_rw_" + totrw + "_3").Text("P" + p[1] + "|F" + f[1] + "|T" + t[1]);
				//return true;
			},
			//*Student.BioData.FormOlevelResult *Student.BioData.GetOlevelResult *BioData.GetOlevelResult *BioData.FormOlevelResult
			FormOlevelRst: function () {//function to get all seleceted result
				var totrw = _("olevelrst").TotalRows();
				var p = [0, 0], f = [0, 0], column = [1, 3];
				var firstsit = ""; secondsit = "";
				for (var g = 2; g < totrw; g++) {
					var subjcell = _("olevelrst_rw_" + g + "_2");
					if (!Null(subjcell)) {
						var firstcell = _("olevelrst_rw_" + g + "_1");
						var secondcell = _("olevelrst_rw_" + g + "_3");
						var subj = subjcell.Text().Trim();
						var frst = firstcell.Text().Trim();
						var srst = secondcell.Text().Trim();
						if (frst != "") firstsit += subj + "=" + frst + ";";
						if (srst != "") secondsit += subj + "=" + srst + ";";
					}

				}
				firstsit = (firstsit.Trim() != "") ? firstsit.TrimRight(";") : firstsit.Trim();
				secondsit = (secondsit.Trim() != "") ? "###" + secondsit.TrimRight(";") : secondsit.Trim();

				return firstsit + secondsit;
			},
			//*Student.BioData.FormOlevelDetails *Student.BioData.GetOlevelDetails *BioData.GetOlevelDetails *BioData.FormOlevelDetails
			FormOlevelDet: function () {//get the olevel details
				//olvrstxamtype1 olvrstxamyear1 olvrstschn1 Etinan Institute, Etinan`~2009`~4040705070`~WAEC###
				var firstsit = ""; secondsit = "";
				firstsit = _("olvrstschn1").TextContent() + "`~" + _("olvrstxamyear1").ValueContent() + "`~" + _("olvexamno1").TextContent() + "`~" + _("olvrstxamtype1").ValueContent() + "`~" + _("olvexmbatch1").ValueContent();
				var schtype2 = _("olvrstxamtype2").ValueContent();
				if (schtype2.Trim() != "") {
					secondsit = "###" + _("olvrstschn2").TextContent() + "`~" + _("olvrstxamyear2").ValueContent() + "`~" + _("olvexamno2").TextContent() + "`~" + schtype2 + "`~" + _("olvexmbatch2").ValueContent();
				}
				return firstsit + secondsit;
			},

			//*Student.BioData.SetOlevelResult *BioData.SetOlevelResult 
			SelectOlevelRst: function (rst) {//function to select the olevel result as required
				//console.log(rst);
				rst = unescape(rst);
				var cl = Student.BioData.ClearOlevelRst();
				if (rst.Trim() == "") return true; //if no restult sent
				rstarr = rst.split("###"); //get the sittings
				if (rstarr.length > 0) { //if result exist
					var cursitting = 1; //hold the current sitting loading
					//var p=0,f=0;
					for (var s = 0; s < rstarr.length; s++) { //loop throug each sitting
						var indrst = rstarr[s]; //get result
						var indrstarr = indrst.split(";");//get the individual subject results
						if (indrstarr.length > 0) {
							for (var d = 0; d < indrstarr.length; d++) { //loop through all individual subject result
								var rstsubj = indrstarr[d]; //get the individual subject result
								var rstsubjarr = rstsubj.split("="); //breack down to get the subject and the equivalent grade
								if (rstsubjarr.length == 2) {
									var subj = rstsubjarr[0].Replace(".", ""); //subject , handle the old crk format c.r.k
									var grd = rstsubjarr[1]; //grade
									var rwuserid = "olevelrst_" + subj.toLowerCase().Replace(" ", ".") + "_" + cursitting; //form the user supplied id string
									var hiddenobj = _(rwuserid);
									if (hiddenobj != null) { //if the subject exist
										var cellid = hiddenobj.value; //get the table cell id
										var curcell = _(cellid);
										if (curcell != null) {
											var color = Student.BioData.GetGradeColor(grd);
											curcell.SetStyle("color:" + color[0]);
											if (color[1] != "") curcell.Text(grd);

											//p=(color[1] == "P")?p+1:p; //increament pass if pass
											//	f=(color[1] == "F")?f+1:f;//increament fail if fail

										}
									}
								}
							}
						}
						// var tot = p + f;
						//var totrw = _("olevelrst").TotalRows();
						//set total
						// _("olevelrst_rw_"+totrw+"_"+cursitting).Text("P"+p+"|F"+f+"|T"+tot);
						// p=0;f=0;
						cursitting += 2;
					}
				}
				//return true
			},
			CurrentGradeCell: null,
			//*Student.BioData.ShowGrade *BioData.ShowGrade *Student.BioData.OlevelResult.ShowGrade	*BioData.OlevelResult.ShowGrade *BioData.OlevelResult.Grade	*Student.BioData.OlevelResult.Grade	
			ShowGrade: function (obj) { // function to display the grade box
				//alert(obj.id);
				var selid = obj.id; //get the cell object
				var selarr = selid.split("_");
				if (selarr[3].ToNumber() == 2) return; //if cel selected is second cell, which holds the subject return
				Student.BioData.CurrentGradeCell = obj; //set the selected cell as the current grade cell
				_("gradebx").Animate({ CSSRule: "opacity:1;visibility:visible", Time: 500 }); //display grade box
				//obj.Text("A1");
			},
			GetGradeColor: function (selgrade) { //get the grade color
				//selgrade = selgrade.Trim().toUpperCase();
				if (selgrade == "") return ["black;font-weight:lighter", ""];
				var strarr = ["F", "P"];
				var strstylearr = ["#FF6835;font-weight:bold", "rgba(86,176,55,1)" + ";font-weight:bold"];
				var parsgr = parseInt(selgrade);
				var passdtstr;
				if (isNaN(parsgr)) {
					passdtstr = _('PassDataStr').value.ToDataArray();
				} else {
					passdtstr = _('PassDataStrID').value.ToDataArray();
				}
				//console.log(selgrade);
				//console.log(_('PassDataStr').value.ToDataArray());
				if (typeof passdtstr[selgrade] == _UND) return ["black;font-weight:lighter", ""]; //if invalid grade supply
				var passdata = passdtstr[selgrade].ToNumber();
				return [strstylearr[passdata], strarr[passdata]];

				/*if(selgrade == "A1" || selgrade == "B2" || selgrade == "B3" || selgrade == "C4" || selgrade == "C5" || selgrade == "C6"){
						 
						return ["rgba(86,176,55,1)"+";font-weight:bold","P"];
					}else if(selgrade == ""){
						return ["black;font-weight:lighter",""];
					}else{
						return ["#FF6835;font-weight:bold","F"];
					}*/
			},
			//*Student.BioData.SetGrade *BioData.SetGrade *Student.BioData.OlevelResult.SetGrade *BioData.OlevelResult.SetGrade
			SetGrade: function (obj) { //function to set the grade of a garde cell when a particular grade is selected on the grade box
				var selgrade = obj.Text().Trim();
				//alert(selgrade);
				if (Student.BioData.CurrentGradeCell != null) { //check if a grade cell exist
					Student.BioData.CurrentGradeCell.textContent = (selgrade == "NA") ? "" : selgrade; //change the content of the cell to the newly selected grade
					var curcell = Student.BioData.CurrentGradeCell; //temp hold the cell involve
					//check the type of grade selected and color as required
					var color = Student.BioData.GetGradeColor(selgrade);
					curcell.SetStyle("color:" + color[0]);
					//var totgrd = Student.BioData.CalculateTotals();
					//get the total rw of the result table
					/*var totrw = _("olevelrst").TotalRows();
					var grdetp = color[1];
					//breakdown the id of the current cell to determine the column
					var idbrkdwn = curcell.id.split("_");
					var colum = idbrkdwn[3];
					//get the total current content
					var totcell = _("olevelrst_rw_"+totrw+"_"+colum);
					if(!IsNull(totcell)){
						var currtext = totcell.Text();
						//break down totals to get P,F,T
						var currtextarr = currtext.split("|");
						if(currtextarr.length == 3){
							
						}
					}*/

					/*if(selgrade == "A1" || selgrade == "B2" || selgrade == "B3" || selgrade == "C4" || selgrade == "C5" || selgrade == "C6"){
						curcell.SetStyle("color:rgba(86,176,55,1)");
					}else if(selgrade == "NA"){
						curcell.SetStyle("color:");
					}else{
						curcell.SetStyle("color:#FF6835");
					}*/
					Student.BioData.CurrentGradeCell = null; //reset current grade cell variable back to null
				}
				_("gradebx").Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 });

			},//function to turn grade to NA of a particular cell

			ClearGrade: function (obj) {
				obj.Text("");
				obj.SetStyle("color:black");
			},//function to change student passport
			ChangePassport: function () {
				var uploabtn = _("uploadpw");
				if (!uploabtn.IsLoading()) {
					uploabtn.StartLoading();
					var tempnm = Login.CurrentUserDet.split("~")[0]; //use the userid as the temp passp name so for every upload done in temp only the last will be availabe(overights), to manage redundancies
					//var regno = _("studregNo").TextContent().Trim();

					/*if(regno == ""){
						MessageBox.Show("Passport Update, Requires Registration Number");
						return;
					}*/
					//Tracer.Tag(tempnm);
					var Filer = new FileUpload(300000, "epconfig/Temps/cportal/uploadimg/", "jpg");
					//the file upload load folder should start from the server root folder
					Filer.Upload(tempnm, function (res) {

						res = res.Trim();
						var resarr = res.split("~");
						var status = resarr[0];
						if (status.Trim() != "1") {
							MessageBox.Show(resarr[2]);
							_("uploadpw").StopLoading();
						} else {

							var src = resarr[1];
							var dt = new Date();
							var tm = dt.getTime();
							_("studpassp").SetImage("../" + src + "?" + tm, function () { _("uploadpw").StopLoading() });
							//Tracer.Tag("../"+src+"?"+tm);
							_("temppass").value = src;
							//alert(src);
						}

					});
				} else {
					MessageBox.Show("Busy, Try Again Later");
				}
			}, ChainDept: "",//variable to pre hold the dept id to select for chain selecttion(select after complete loading of option by the faculty oncahange
			ChainProg: "",//variable to pre hold the prog id to select for chain selecttion(select after complete loading of option by the dept oncahange

			//*Student.BioData.LoadFaculty *BioData.LoadFaculty
			LoadFac: function () { //function to load department textbox based on selected faculty
				//var facID = _("studfac").ValueContent();
				//if(facID == null)return;select * from fac_tb order by FacName
				//alert(facID);

				//alert(window.sessionStorage)
				//Tracer.Start("Chain Loading");

				var studstudy = _("studstudy").ValueContent();
				//Tracer.Tag("Study: "+studstudy);
				studstudy = (studstudy == null || studstudy.Trim() == "") ? 1 : studstudy;
				//Tracer.Tag("Onload of fac due to change of studyid = " + studstudy);
				TextBox.Load("studfac", "FacID", "FacName", "StudyID=" + studstudy + " order by FacName", "fac_tb"); //Load:function(tb,key, val, cond, dbtb)
				//Student.BioData.LoadLevel(); //load level if a programe id is set
				//Tracer.End();
			},
			//*Student.BioData.LoadDepartment *BioData.LoadDepartment *Student.BioData.LoadDept *BioData.LoadDept
			LoadDept: function () { //function to load department textbox based on selected faculty
				//Tracer.Start();
				var facID = _("studfac").ValueContent();
				//Tracer.Tag("Faculty: "+facID);
				if (facID == null || facID.Trim() == "") facID = 0;
				//alert(facID);
				//alert(facID);
				//Tracer.Tag("Onload of dept due to change of fac = "+facID);
				TextBox.Load("studdept", "DeptID", "DeptName", "FacID = " + facID, "dept_tb"); //Load:function(tb,key, val, cond, dbtb)
				//Tracer.End();
			},
			//*Student.BioData.LoadLGA *BioData.LoadLGA
			LoadLGA: function () { //function to load department textbox based on selected faculty
				//Tracer.Start();
				var stateID = _("stateorig").ValueContent();
				//Tracer.Tag("Faculty: "+facID);
				if (stateID == null || stateID.Trim() == "") stateID = 0;
				//alert(facID);
				//alert(facID);
				//Tracer.Tag("Onload of dept due to change of fac = "+facID);
				TextBox.Load("lga", "LGAID", "UPPER(LGAName)", "StateID = " + stateID, "lga_tb"); //Load:function(tb,key, val, cond, dbtb)
				//Tracer.End();
			},
			//*Student.BioData.LoadProgramme *BioData.LoadProgramme
			LoadProg: function () { //function to load program textbox based on selected department
				//Tracer.Start();
				var deptID = _("studdept").ValueContent();
				if (deptID == null || deptID.Trim() == "") deptID = 0;
				//Tracer.Tag("Onload of prog due to change of dept = " +deptID);
				//Tracer.Tag("Department: "+deptID);
				TextBox.Load("studprog", "ProgID", "ProgName", "DeptID = " + deptID, "programme_tb"); //Load:function(tb,key, val, cond, dbtb)
				//Tracer.End();
			},
			//*Student.BioData.LoadLevel *BioData.LoadLevel
			LoadLevel: function () { //function to load level based on programme and 
				//Tracer.Start();
				var progID = _("studprog").ValueContent();
				var studstudy = _("studstudy").ValueContent();
				if (progID == "") return;
				if (studstudy == null || studstudy.Trim() == "") studstudy = 0;
				//alert(facID);
				//Tracer.Tag("Onload of level due to change of prog = "+progID+" or studyid = " + studstudy);
				//Tracer.Tag("Level: StudyID is "+studstudy);
				TextBox.Load("studlvl", configdata.Core + "cportal/Pages/Scripts/Gen/loadlevel.php?StudyID=" + escape(studstudy) + "&progID=" + escape(progID) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
				//MessageBox.Show("Note: Level-Set Changed, confirm Student level before Save");
				//Load:function(tb,key, val, cond, dbtb)
				//Tracer.End();
			}, //function to handle save
			//*Student.BioData.Save *BioData.Save
			Save: function () {
				//__("Selected Stud: "+selectedRegNo);
				//alert(_("searchStud").SelectedStudent());
				// return;

				_("biodatafrm").submit();
				//alert(Student.BioData.FormOlevelDet() + " ; " + Student.BioData.FormOlevelRst());
			},
			PSave: () => {
				if (_("Studenttab").ProgressGet(0).ProgressState() == 0) {
					_("Studenttab").ProgressGet(0).ProgressTo(10, 'Student.BioData.StartSave()');
				} else {
					MessageBox.Show("Busy, Try Again Later");
				}
			},
			StartSave: function () { //function to start save

				var selectedRegNo = ""; SRegNo = "";
				var srst = _("searchStud");
				if (!Null(srst)) {
					SRegNo = selectedRegNo = srst.SelectedStudent();
				}

				//alert(selectedRegNo) //studregNo
				//alert(_("studregNo").TextContent());
				var ERegNo = _("studregNo").TextContent().Trim();
				var EJambNo = _("jambNo").TextContent().Trim();
				if (ERegNo == "" && EJambNo == "") {

					_("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Invalid Registration or Entrance Number Entered")');
					return;
				}
				var CurRegNoPre = ERegNo != "" ? "R" : "J";
				var reqired = _("textBx & BioDataelem & req err"); //get all element which there require status is still on i.e user has not entered any value

				//__("Confirm Required fields");
				//console.log(reqired);
				if (Null(reqired)) {//if no invalid data supplied
					//if Student Selected
					if (SRegNo.Trim() != "") {
						//if RegNo Set
						//if(ERegNo != ""){

						if ((CurRegNoPre == "R" && ERegNo.toLowerCase() != SRegNo.toLowerCase()) || (CurRegNoPre == "J" && EJambNo.toLowerCase() != SRegNo.toLowerCase())) { //if RegNo Modified
							OptionBox.Show({
								Title: "Registration Number Mismatch",
								Options: [{
									Logo: "user-plus",
									Title: "Local Update",
									Info: "Add as a new Student or Update if Student Exist, Excluding Reg./Entrance Number",
									Function: function (oprattionID) {
										_("Studenttab").ProgressGet(0).ProgressTo(20, 'Student.BioData.PerformSave(' + oprattionID[0] + ',"' + oprattionID[1] + '")');
									},
									Parameter: [1, CurRegNoPre]
								},
								{
									Logo: "user",
									Title: "Global Update",
									Info: "Continue selected Student record update process, including Reg./Entrance Number",
									Function: function (selreg) {
										//set to globally update reg no setting 1
										_("Studenttab").ProgressGet(0).ProgressTo(20, 'Student.BioData.PerformSave(' + selreg[0] + ',"' + selreg[1] + '")');
									},
									Parameter: [2, CurRegNoPre]
								},
								{
									Logo: "times",
									Title: "Cancel Process",
									Info: "Cancel the current Process",
									Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
								}]

							});
						} else { //if RegNo Not Modified
							//update student info only
							_("Studenttab").ProgressGet(0).ProgressTo(20, 'Student.BioData.PerformSave(' + 3 + ',"' + CurRegNoPre + '")');
						}
						/* }else if(EJambNo != ""){ //if RegNo not set and JambNo is set
							//if JambNo Modified
							if(EJambNo.toLowerCase() != SRegNo.toLowerCase()){

							}
						} */
					} else { //if no selected student
						//$CurRegNoPre
						OptionBox.Show({
							Title: "New Student",
							Options: [{
								Logo: "user-plus",
								Title: "Soft Update",
								Info: "Add as a new Student or Update if New Registration Number Exist",
								Function: function (oprattionID) {
									_("Studenttab").ProgressGet(0).ProgressTo(20, 'Student.BioData.PerformSave(' + oprattionID[0] + ',"' + oprattionID[1] + '")');
								},
								Parameter: [4, CurRegNoPre]
							},
							{
								Logo: "times",
								Title: "Cancel Process",
								Info: "Cancel the current Process",
								Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
							}]

						});
						//_("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave(' + 4 + ',"'+$CurRegNoPre+'")')
					}
					/* var studreg = _("studregNo").TextContent().Trim();
					var estudreg = ERegNo == "" ? EJambNo : ERegNo;
					//"Start Save".__();
					if (selectedRegNo.toUpperCase() == estudreg.toUpperCase()) { //'Selected is Entered'.__();
						//"No Reg Mismatch".__();
						_("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave("' + selectedRegNo + '")');
					} else {
						//__('Check if no stud selected')
						if (selectedRegNo == "") {
							//__('No student select')
							OptionBox.Show({
								Title: "New Student",
								Options: [{
									Logo: "user-plus",
									Title: "Add/Update New",
									Info: "Add as a new Student or Update if Registration Number Exist",
									Function: function (selreg) { _("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave("' + selreg + '")'); },
									Parameter: selectedRegNo
								},
								{
									Logo: "times",
									Title: "Cancel Process",
									Info: "Cancel the current Process",
									Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Process Canceled")'); }
								}]

							});
						} else { //if exist a selected student and entered regno is not same
							OptionBox.Show({
								Title: "Registration Number Mismatch",
								Options: [{
									Logo: "user-plus",
									Title: "Add/Update New",
									Info: "Add as a new Student or Update if New Registration Number Exist",
									Function: function (selreg) {
										_("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave("' + selreg + '")');
									},
									Parameter: selectedRegNo
								},
								{
									Logo: "user-times",
									Title: "Ignore",
									Info: "Update selected student record and ignore entered Registration Number",
									Function: function (selreg) {
										
										_("studregNo").SetText(selreg);
										_("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave("' + selreg + '")');
									},
									Parameter: selectedRegNo
								},
								{
									Logo: "user",
									Title: "Update",
									Info: "Continue selected Student record update process including Registration Number",
									Function: function (selreg) {
										//set to globally update reg no setting 1
										_("Studenttab").ProgressGet(0).ProgressTo(70, 'Student.BioData.PerformSave("' + selreg + '",1)');
									},
									Parameter: selectedRegNo
								},
								{
									Logo: "times",
									Title: "Cancel Process",
									Info: "Cancel the current Process",
									Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Process Canceled")'); }
								}]

							});
						}
					} */


				} else if (IsArray(reqired)) {
					var erritems = "";
					for (var q = 0; q < reqired.length; q++) {
						var currel = reqired[q];
						var op = "";
						if (q < reqired.length - 1 && q != 0) {
							op = " , ";
						} else if (q == reqired.length - 1) {
							op = " and ";
						}
						erritems += op + currel.title;
					}
					MessageBox.Show("#INVALID DATA: " + erritems);
					_("Studenttab").ProgressGet(0).ProgressTo(100);
				} else {
					MessageBox.Show("#INVALID DATA: " + reqired.title);
					_("Studenttab").ProgressGet(0).ProgressTo(100);
				}
			},
			PerformSave: function (selectedRegNo, updatereg) {
				var proccessID = selectedRegNo;
				var RegType = updatereg;
				SRegNo = "";
				var srst = _("searchStud");//SelectedObject
				if (!Null(srst)) {
					SRegNo = selectedRegNo = srst.SelectedStudent();
				}
				/* MessageBox.Show("Testing => ProcessID-"+proccessID+" ; RegType-"+RegType);
					_("Studenttab").ProgressGet(0).ProgressTo(100);
					return; */

				//'Enter perform save'.__();
				//_("Studenttab").ProgressGet(0).ProgressStepTo(10)
				updatereg = typeof updatereg == _UND ? 0 : updatereg;
				// if(selectedRegNo == ""){MessageBox.Show("No Student Selected"); return;};
				// if(_("studregNo").TextContent().Trim() == selectedRegNo){MessageBox.Show("Registration Number Mismatch");}
				var textstr = Page.DataString("BioDataelem ~ searchStudsearchCriterial ~ searchStudsearchtxt");
				var olveldet = "olvelDet=" + escape(Student.BioData.FormOlevelDet());
				var olvelRst = "olvelRst=" + escape(Student.BioData.FormOlevelRst());
				//var passwrdpth =escape(_("temppass").value.Trim());

				var Data = textstr + "&" + olveldet + "&" + olvelRst + "&selstudid=" + encodeURIComponent(SRegNo) + "&updreg=" + encodeURIComponent(updatereg) + "&PID=" + proccessID + "&RegType=" + encodeURIComponent(RegType) + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
				//check if image set
				var imgpd = _("studpassp");
				if (imgpd.IsSet()) {
					/* MessageBox.Show("No Student Passport Set");
					_("Studenttab").ProgressGet(0).ProgressTo(100);
					return; */
					var passpFileobj = imgpd.GetPadFile();
					if (passpFileobj != null) {
						Data += "&" + passpFileobj.PostData;
					}
				} else {

					_("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("No Student Passport Set");');
					return;
				}

				//console.log(Data);
				//return;
				// _("Studenttab").ProgressGet(0).ProgressStepTo(90);
				// alert(Data);
				//__("Data Before: "+Data);

				aj = new Ajax();
				//set up abort operation
				Tabs.ProgressSetAbort("Student", 0, aj);
				// ("Package Data For Save => "+Data).__();
				//var dt = "file1=?";
				aj.Post({
					OnProgress: function (delta) {
						var percent = (delta * 50) + 20;
						_("Studenttab").ProgressGet(0).ProgressTo(Math.round(percent));
						//_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//"Complete Save".__();
						//	res.__();
						res = res.Trim();
						//__("Data Returned: "+res);
						//_("temppass").value = "";
						//_("Studenttab").ProgressGet(0).ProgressTo(100,'MessageBox.Show("'+res+'")');
						//MessageBox.Show(res);
						Student.BioData.GroupCurrent = new Array();
						res = res.Replace("'", "\'");
						//alert(res) 
						_("Studenttab").ProgressGet(0).ProgressTo(100, "MessageBox.Show('" + res + "')");

					},
					OnError: function (res) {
						res = res.Replace("'", "\'");
						_("Studenttab").ProgressGet(0).ProgressTo(100, "MessageBox.Show('" + res + "')");
						//MessageBox.Show(res);
					},
					OnAbort: function (res) {
						_("Studenttab").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Save Aborted")');

					},
					PostData: Data,
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/updatestud.php"
				});

				/* Student.BioData.Ajax.PostResponse(Data,"Pages/Scripts/Student/updatestud.php",
				   function(res){
					   //alert(res);
					   //return;
					   res = res.Trim();
					   //__("Data Returned: "+res);
					   _("temppass").value = "";
					   _("Studenttab").ProgressGet(0).ProgressTo(100,'MessageBox.Show("'+res+'")');
					   Student.BioData.GroupCurrent = new Array();
					   //__();
				   },"text",function(res){MessageBox.Show("#Server Error, Connection Problem");_("Studenttab").ProgressGet(0).ProgressTo(100)});  */

				// alert(Data);
				//MessageBox.Show(Data);

			},//function to handle clear all
			//*Student.BioData.Clear *BioData.Clear
			Clear: function () {
				if (_('studentrecdefault').style.display != "none") { //if still in home screen display
					_('studentrecdefault').Hide();
					_('biodatafrm').Show();
					return;
				}
				if (_("Studenttab").ProgressGet(0).ProgressState() == 0) {
					//	CoverScreen.Show("clerstud",'Please wait for a few seconds ...<div style="font-size:0.6em">while we clear all data on Page</div>',function(){
					_("Studenttab").ProgressGet(0).ProgressTo(30, "Student.BioData.ClearText()");
					Student.BioData.GroupCurrent = new Array();//reset the current display datastr of group array
					//	});
				} else {
					MessageBox.Show("Busy, Try Again Later");
				}

			},//function to clear text
			ClearText: function () {

				_("textBx & BioDataelem  ~ searchStudsearchtxt").ClearText(); //clear all textbox
				_("Studenttab").ProgressGet(0).ProgressTo(60, "Student.BioData.ClearPadPassP()");


			},//function to text pads and passport
			ClearPadPassP: function () {
				_("studaddr nkaddr").ClearPad(); //clear all text pads
				_("studpassp").ClearImagePad();
				// _("temppass").value = "";
				_("Studenttab").ProgressGet(0).ProgressTo(70, "Student.BioData.ClearRem()");
			},//function to text pads and passport
			ClearRem: function () {
				Student.BioData.ClearOlevelRst();
				//clear all olvel result
				//unselect the selected cell of the serach result table

				var rsttable = _("searchStud");
				//if (rsttable != null) rsttable.Deselect();
				var grps = ["bDatagrpDet", "bDatagrpSch", "bDatagrpPassp", "bDatagrpCont", "bDatagrpNOK", "bDatagrpRstDet", "bDatagrpReg"];
				for (var d = 0; d < grps.length; d++) {
					_(grps[d] + "_grpdata").value = "";
				}
				if (rsttable != null) {
					var selectedcell = rsttable.SelectedObject(true);
					if (selectedcell != null) {
						//selectedcell.click(); //click it to unselect it
						Table.Deselect(selectedcell);
					}
				}

				_("Studenttab").ProgressGet(0).ProgressTo(100);
				_('studentrecdefault').Hide();
				_('biodatafrm').Show();
				//CoverScreen.Close(_('clerstud'));

			},//function to handle print
			//*Student.BioData.Print *BioData.Print
			Print: function () {
				//regno
				var selectedRegNo = Student.BioData.IsSelected();
				if (selectedRegNo) {
					// var BioDataPrint = new Printer();
					// BioDataPrint.Preview("Registration Slip","../portal/Admin/Slip.php?regno="+selectedRegNo+"&folder=Form",function(){});
					//alert(configdata.Core);
					PDFPrinter.Print(configdata.Core + "general/Slip.php", "regno=" + selectedRegNo + "&folder=Form&paper=A4&orientation=P&MT=4&MB=14&SubDir=" + encodeURIComponent(configdata.SubDir), "RCS_" + selectedRegNo.Replace('/', '_') + ".pdf")
				} else {
					MessageBox.Show("No Student Selected");
				}
			},//function to check if a student is selected
			IsSelected: function () {
				var srst = _("searchStud");
				var selectedRegNo = "";
				if (!Null(srst)) {

					selectedRegNo = srst.SelectedStudent();

				}
				if (selectedRegNo == "") {
					//MessageBox.Show("No Student Selected");
					return false;
				}
				return selectedRegNo

			},//function to Delete Student
			//*Student.BioData.Delete *BioData.Delete
			Delete: function () {
				if (_("Studenttab").ProgressGet(0).ProgressState() == 0) {
					var selectedRegNo = Student.BioData.IsSelected()
					if (selectedRegNo) {
						_("Studenttab").ProgressGet(0).ProgressTo(40, "Student.BioData.SendDelete('" + selectedRegNo + "')");
					} else {
						MessageBox.Show("No Student Selected");
					}
					//Student.BioData.GroupCurrent = new Array();//reset the current display datastr of group array
				} else {
					MessageBox.Show("Busy, Try Again Later");
				}

			},//function to check selection for delete
			SendDelete: function (selectedRegNo) {
				//var selectedRegNo = Student.BioData.IsSelected()
				//if(selectedRegNo){
				OptionBox.Show({
					Title: "Delete Student",
					Options: [{
						Logo: "trash",
						Title: "Continue Delete",
						Info: "Deletes all students records globally",
						Function: function (selreg) { _("Studenttab").ProgressGet(0).ProgressTo(50, 'Student.BioData.PerformDelete("' + selreg + '")'); },
						Parameter: selectedRegNo
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current Process",
						Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
					}]

				});
				/*}else{
					_("Studenttab").ProgressGet(0).ProgressTo(100);
				}*/
			},//function to perform delete
			PerformDelete: function (regnum) {
				//alert(regnum);
				Student.BioData.Ajax.PostResponse("RegNo=" + regnum + "&SubDir=" + encodeURIComponent(configdata['SubDir']), configdata['Core'] + "cportal/Pages/Scripts/Student/deletestud.php",
					function (res) {
						res = res.Trim();
						if (!Login.Authenticate(res)) return;
						//__("Data Returned: "+res);
						//_("temppass").value = "";
						_("Studenttab").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res + '");SSBObject("searchStud").Search()');
						//__();
					}, "text", function (res) { MessageBox.Show("#Server Error, Connection Problem"); _("Studenttab").ProgressGet(0).ProgressTo(100) });
			},//function to perform copy
			//*Student.BioData.Copy *BioData.Copy
			Copy: function () {
				//alert(_("searchStud").Selected().outerHTML);
				var selectedRegNo = Student.BioData.IsSelected()
				if (selectedRegNo) {
					ClipBoard.Copy(selectedRegNo, "Student");
					MessageBox.Show("*Student Copied");
				} else {
					MessageBox.Show("No Student Selected");
				}
			},//function to perform paste
			//*Student.BioData.Paste *BioData.Paste
			Paste: function () {
				var copystud = ClipBoard.Paste("Student");
				if (copystud == "") {
					MessageBox.Show("No Student Copied");
				} else {
					/*var srst = _("searchStud");
					var selectedRegNo = "";
					if(!Null(srst)){
						var selectedd = srst.SelectedObject();
						if(!Null(selectedd)){
							selectedRegNo = selectedd.Text().Trim();
						}
					}
					if(selectedRegNo != "" && selectedRegNo != copystud.Trim()){
					   selectedd.click(); //deselect it
					}
					if(selectedRegNo != copystud.Trim()){ //if paste student not seleceted
					Student.BioData.StartLoadStudent(copystud);
					}*/
					var txt = _("searchStudsearchtxt").SetText(copystud);
					var obj = window["obj_searchStud"];
					if (obj) {
						obj.ReSearch(function () {
							var items = _("class_searchStud");
							var items = IsArray(items) ? items[0] : items;
							if (items) {
								items.click();
							}
						});
					}
				}
			},
			ClearRegNo: RegNo => {
				/* var srst = _("searchStud");//SelectedObject
				console.log(srst.SelectedObject(true));
				return; generateregdet*/
				RegNo = RegNo.getAttribute('data-regno');
				OptionBox.Show({
					Title: "Clear Registration Number",
					TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Student/basicdet.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + '&RegNo=' + encodeURIComponent(RegNo) },
					Options: [{
						Logo: "trash",
						Title: "Continue",
						Info: "Clear student Current Registration Number",
						Function: function (RegNo) {
							Student.BioData.PerformRegNoClear(RegNo);
						},
						Parameter: RegNo
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current Process",
						Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
					}]

				});
			},
			RegNoManageAjax: new Ajax(),
			PerformRegNoClear: RegNo => {
				Student.BioData.RegNoManageAjax.Post({
					OnProgress: delta => {
						_("Studenttab").ProgressGet(0).ProgressTo(Math.round(delta * 80));
					},
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/clearRegNo.php",
					Data: 'RegNo=' + encodeURIComponent(RegNo) + '&SubDir=' + encodeURIComponent(configdata['SubDir']),
					OnComplete: res => {
						resobj = JSON.parse(res);
						if (resobj.Success) {
							//Cleared Successfully
							//Reload the student details
							var NewRegNo = resobj.RegNo;
							var srst = _("searchStud");//SelectedObject
							if (srst != null) {
								var selectedrw = srst.SelectedObject(true);
								selectedrw.setAttribute('data-id', NewRegNo);
								_(selectedrw.id + "_1").textContent = NewRegNo;
								_('studregNo_inp').value = "";
								var clearregno = _('clearregno');
								clearregno.style.display = 'none';
								clearregno.setAttribute('data-regno', NewRegNo);
								var generateregno = _('generateregno');
								generateregno.style.display = 'inline-block';
								generateregno.setAttribute('data-regno', NewRegNo);
							}

							MessageBox.Show("*Student Registration Number Cleared Successfully");
							_("Studenttab").ProgressGet(0).ProgressTo(100);
						} else {
							MessageBox.Show(resobj.Message);
							_("Studenttab").ProgressGet(0).ProgressTo(-1);
						}
					}
				})
			},
			GenerateRegNo: RegNo => {
				/* var srst = _("searchStud");//SelectedObject
				console.log(srst.SelectedObject(true));
				return; */
				RegNo = RegNo.getAttribute('data-regno');
				OptionBox.Show({
					Title: "Generate Registration Number",
					TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Student/generateregdet.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + '&RegNo=' + encodeURIComponent(RegNo) },
					Options: [{
						Logo: "trash",
						Title: "Continue",
						Info: "Generate Student Registration Number",
						Function: function (RegNo) {
							Student.BioData.PerformRegNoGenerate(RegNo);
						},
						Parameter: RegNo
					},
					{
						Logo: "times",
						Title: "Cancel Process",
						Info: "Cancel the current Process",
						Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Process Canceled")'); }
					}]

				});
			},
			PerformRegNoGenerate: RegNo => {
				Student.BioData.RegNoManageAjax.Post({
					OnProgress: delta => {
						_("Studenttab").ProgressGet(0).ProgressTo(Math.round(delta * 80));
					},
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/generateRegNo.php",
					Data: 'RegNo=' + encodeURIComponent(RegNo) + '&SubDir=' + encodeURIComponent(configdata['SubDir']),
					OnComplete: res => {
						//alert(res);
						resobj = JSON.parse(res);
						if (resobj.Success) {
							//Cleared Successfully
							//Reload the student details
							var NewRegNo = resobj.RegNo;
							var srst = _("searchStud");//SelectedObject
							if (srst != null) {
								var selectedrw = srst.SelectedObject(true);
								selectedrw.setAttribute('data-id', NewRegNo);
								_(selectedrw.id + "_1").textContent = NewRegNo;
								_('studregNo_inp').value = NewRegNo;

								var clearregno = _('clearregno');
								clearregno.style.display = 'inline-block';
								clearregno.setAttribute('data-regno', NewRegNo);
								var generateregno = _('generateregno');
								generateregno.style.display = 'none';
								generateregno.setAttribute('data-regno', NewRegNo);
								OptionBox.Show({
									Title: "Registration Number Generated",
									TitleHTML: '<h1>' + NewRegNo + '</h1>',
									Options: [{
										Logo: "print",
										Title: "Print",
										Info: "Reprint Student Record",
										Function: function () {
											Tabs.Toolbox.Perform('Student', 'Print');
										}
									},
									{
										Logo: "times",
										Title: "Close",
										Info: "Close Popup",
										Function: function () { }
									}]
								});
							}

							MessageBox.Show("*Student Registration Number Generated Successfully");
							_("Studenttab").ProgressGet(0).ProgressTo(100);
						} else {
							MessageBox.Show(resobj.Message);
							_("Studenttab").ProgressGet(0).ProgressTo(-1);
						}
					}
				})
			}

		},

		/* Student registration Report */
		RegReport: {
			Ajax: new Ajax(),


			LoadUnSel: function (obj) {
				obj.click();
			},
			NullFunc: function (obj) {

			},
			Load: function () {
				var studbx = _("studregrpttyp");
				if (studbx == null) { MessageBox.Show("#Error on Page: Reload Page"); return }
				var obj = studbx.Selected();
				if (obj == null) MessageBox.Show("Select the Report Type");
				//return;
				//alert(selected.id); return;
				if (typeof obj == _UND) {
					MessageBox.Show("#Invalid Parameter");
					return;
				}
				if (typeof obj.id == _UND) {
					obj.id = "tr_" + Math.Random() * 2000000;
				}
				var rptType = obj.Data('id');
				// alert(rptType);
				//return;
				//get the session
				var ses = _('studrptset').ValueContent();
				var entry = _('studrptmode').ValueContent();
				var gender = _('studrptgender').ValueContent();
				var mstatus = _('studrptmstatus').ValueContent();

				var datastr = "reportType=" + rptType + "&set=" + ses + "&entr=" + entry + "&gender=" + gender + "&mstatus=" + mstatus + "&objid=" + obj.id;

				//check type of report
				if (rptType == "rpttypefac") {
					datastr += "&displaytext=REGISTERED STUDENT REPORT BY FACULTY/SCHOOL";
				}

				if (rptType == "rpttypestate") {
					datastr += "&displaytext=REGISTERED STUDENT REPORT BY STATE OF ORIGIN";
					// MessageBox.Show("Note: Computing Report Based on Faculty/School might take a few minute.");
				}

				if (rptType == "studregall") {
					datastr += "&displaytext=ADMMITTED STUDENT REPORT";
				}

				if (rptType == "studregreg") {
					datastr += "&displaytext=REGISTERED STUDENT REPORT";
				}
				var currdatastr = _('studrpt_curdatastr');
				if (currdatastr != null) currdatastr.textContent = "";
				Student.RegReport.LastDataStr = [];
				Student.RegReport.PerformLoad(datastr);

			},
			SearchPress: function (e) {
				if (window.event) { // IE                 
					keynum = e.keyCode;
				} else if (e.which) {
					// Netscape/Firefox/Opera                   
					keynum = e.which;
				}
				if (keynum == 13) {
					//alert(keynum);
					//_('studrptsearchbtn').click();
					//get the current datastring
					var currdatastr = _('studrpt_curdatastr');
					if (currdatastr != null) {
						Student.RegReport.Search(currdatastr.textContent);
					}

				}
			},
			Back: function () {
				if (Student.RegReport.LastDataStr.length > 0) {
					var lststr = Student.RegReport.LastDataStr.pop();

					Student.RegReport.PerformLoad(lststr, true);
				} else {
					MessageBox.Show("No More History data Found");
				}
				//console.log(Student.RegReport.LastDataStr);
			},
			Search: function (datastr) {
				var str = _('studregrptsearch').TextContent().Trim();
				if (str != "") {
					//alert(str);
					Student.RegReport.PerformLoad(datastr + "&str=" + escape(str));
				} else {
					Student.RegReport.PerformLoad(datastr);
				}
			},
			LastDataStr: [],
			PerformLoad: function (datastr, back) {
				back = back || false;
				//get current display text
				var curdis = _('regrptdistxt');
				if (curdis == null) {
					curdis = "REPORT";
				} else {
					curdis = curdis.textContent;
				}
				datastr += "&LastDis=" + escape(curdis);
				var currdatastr = _('studrpt_curdatastr');
				if (currdatastr != null) {
					//keep the loaded as last before loading new
					if (currdatastr.textContent.Trim() != "" && back == false) {
						Student.RegReport.LastDataStr.push(currdatastr.textContent);
					}
				}

				//console.log(datastr);
				//alert(datastr);
				Student.RegReport.Ajax.Post({
					PostData: datastr + "&hist=" + Student.RegReport.LastDataStr.length + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/loadReport.php",
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						_("Studenttab").ProgressGet(3).ProgressTo(perc);
					},
					OnComplete: function (res, url, param) {
						if (!Login.Authenticate(res)) return;
						_("Studenttab").ProgressGet(3).ProgressTo(100);
						_('regreportbx').innerHTML = res;
						//console.log(res);
						if (typeof param['displaytext'] != _UND) {
							_('regrptgrpbx_title').innerHTML = Icon('list-alt') + " <span id=\"regrptdistxt\">" + param['displaytext'] + "</span>";
						} else {
							_('regrptgrpbx_title').innerHTML = Icon('list-alt') + " <span id=\"regrptdistxt\">REPORT</span>";
						}

						var searchtb = _('studregrptsearch_inp');
						//searchtb.value = searchtb.value;
						searchtb.focus();
						_('studreporthome').Hide();
						_('regrptgrpbx').Show();
						Tabs.HideSideBar('Student', 3);
						//SpreadSheet.SelectText(searchtb);
					},
					OnError: function (res) {
						res = res.Replace('"', '\"');
						_("Studenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("#Internal Error: ' + res + '");');

					},
					OnAbort: function (res) {
						_("Studenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');

					}
				})
			},
			PrintRc: function (RegNo) {
				//res = "RegNo="+itemNum;

				PDFPrinter.Print(configdata.Core + "general/Slip.php", "regno=" + RegNo + "&folder=Form&paper=A4&orientation=P&MT=4&MB=14&SubDir=" + encodeURIComponent(configdata.SubDir), "RCS_" + RegNo.Replace('/', '_') + ".pdf")
			},

			Print: function () {
				//get current user det
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet != "") {
					var resarr = cuserdet.split("~");
					var userID = resarr[0]
				} else {
					var userID = 0;
				}

				var rptprintdata = _('regrptprintdata');
				if (rptprintdata == null) {
					MessageBox.Show("Load Report and Click Print");
					return;
				}
				//alert(rptprintdata.textContent);
				rptprintdataobj = JSON.parse(rptprintdata.textContent);

				rptprintdataobj['UID'] = userID;
				var datastr = JSON.stringify(rptprintdataobj);
				PDFPrinter.Print(configdata.Core + "cportal/Reports/Student/studreport.php", "data=" + escape(datastr) + "&paper=A4&orientation=P&MT=4&MB=30&SubDir=" + encodeURIComponent(configdata.SubDir));

			},

			Export: function () {
				MessageBox.Show("Note: Export will export all records to Excel format");
				//get current user det
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet != "") {
					var resarr = cuserdet.split("~");
					var userID = resarr[0]
				} else {
					var userID = 0;
				}

				var rptprintdata = _('regrptprintdata');
				if (rptprintdata == null) {
					MessageBox.Show("Load Report before Exporting");
					return;
				}
				//alert(rptprintdata.textContent);
				rptprintdataobj = JSON.parse(rptprintdata.textContent);

				rptprintdataobj['UID'] = userID;
				rptprintdataobj['export'] = "true";
				var datastr = JSON.stringify(rptprintdataobj);
				Student.RegReport.Ajax.Post({
					Action: configdata['Core'] + "cportal/Reports/Student/studreport.php",
					PostData: "data=" + escape(datastr) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						if (res.Trim().substr(0, 6).toLowerCase() == "<table") {
							tableToExcel(res, 'Registered Student Report');
						} else {
							MessageBox.Show(res);
						}
						_("Studenttab").ProgressGet(3).ProgressTo(100);
					},
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						_("Studenttab").ProgressGet(3).ProgressTo(perc);
					},
					OnError: function (res) {
						MessageBox.Show("#Error :" + res);
						_("Studenttab").ProgressGet(3).ProgressTo(100);
					},
					OnAbort: function (res) {
						MessageBox.Show("Report Export Aborted");
						_("Studenttab").ProgressGet(3).ProgressTo(100);
					}
				})
			}
		},// Student Report End
		Settings: {
			Ajax: new Ajax(),
			Save: () => {
				var studrecdispsprsht = _('studrecdispsprsht').GetDataString();
				//alert(studrecdispsprsht);
				var passportcpreq = _('passportcpreq').GetStatus();
				var AdminVerifyPay = _('AdminVerifyPay').GetStatus();
				var AutoAdmission = _('AutoAdmission').GetStatus();
				studrecdispsprsht += "&PassportReq=" + passportcpreq + "&AdminVerifyPay=" + AdminVerifyPay + "&AutoAdmission=" + AutoAdmission + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
				Student.Settings.Ajax.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Student/saveset.php",
					PostData: studrecdispsprsht,
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;

						MessageBox.Show(res);

						_("Studenttab").ProgressGet(5).ProgressTo(100);
					},
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						_("Studenttab").ProgressGet(5).ProgressTo(perc);
					},
					OnError: function (res) {
						MessageBox.Show("#Error :" + res);
						_("Studenttab").ProgressGet(5).ProgressTo(100);
					},
					OnAbort: function (res) {
						MessageBox.Show("Operation Aborted");
						_("Studenttab").ProgressGet(5).ProgressTo(100);
					}
				});
				//alert(passportcpreq);
			}

		},

		/*
		=================================================================================
		Student PreLoader*/
		//*PreLoader

		//Group  Control/ Tools handlers
		//*Student.Save 
		Save: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: _("biodatafrm").submit(); break;//Student.BioData.Save();//biodata
				//  1: Student.StudPreLoad.Save(); break;//preloader

			}
		},
		//*Student.Print
		Print: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: Student.BioData.Print(); break;//biodata
				case 3: Student.RegReport.Print(); break;//biodata

			}
		},
		//*Student.Clear
		Clear: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: Student.BioData.Clear(); break;//biodata
			}
		},
		//*Student.Delete
		Delete: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: Student.BioData.Delete(); break;//biodata
			}
		},
		//*Student.Copy
		Copy: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: Student.BioData.Copy(); break;//biodata
			}
		},
		//*Student.Paste
		Paste: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 0: Student.BioData.Paste(); break;//biodata
			}
		},
		//*Student.Export
		Export: function (pageid) {
			var selecttabInd = _(pageid).PageSelectedIndex()
			switch (selecttabInd) {
				case 3: Student.RegReport.Export(); break;//biodata
			}
		}
	}
}();

/*function Swa(pgid){
	ind = _(pgid).PageSelectedIndex();
	
	MessageBox.Show(ind);
}

function Sw(obj,val){
	_("mma").style.width =  Math.round(val * 800) + "px";
}

function Sh(obj,val){
	_("mma").style.height =  Math.round(val * 800) + "px";
}

function dsd(obj){
	alert(obj.id);
	alert(_('tab1').SelectedID())
}*/


/************************************************************************************************** */
//*Setup
/************************************************************************************************** */
var Setup = function () {
	return {
		//*Setup.Verify *Setup.Login
		Verify: function () {
			//_("newdb").CheckDisable(); return;
			if (_('veridybtn').ClassIs("loading")) return;
			var host = _("hostnm").TextContent();
			if (host.Trim() == "") { MessageBox.Show("INVALID HOST NAME"); return }
			var db = _("dbnm").TextContent();
			if (db.Trim() == "") { MessageBox.Show("INVALID DATABASE NAME"); return }
			var user = _("usernm").TextContent();
			if (user.Trim() == "") { MessageBox.Show("INVALID USER NAME"); return }
			var pw = _("pwnm").TextContent();
			var newdb = _("newdb").Checked();
			//if(pw.Trim() == ""){MessageBox.Show("INVALID PASSWORD"); return}
			var constr = "server=" + host + ";db=" + db + ";user=" + user + ";pw=" + pw;
			if (constr.Trim() == "") { MessageBox.Show("INVALID DATABASE CONNECTION STRING"); return }
			_('veridybtn').StartLoading("Working ...");
			_("dbnm").TextDisable();
			_("usernm").TextDisable();
			_("pwnm").TextDisable();
			_("hostnm").TextDisable();
			_("newdb").CheckDisable();
			var Ajaxs = new Ajax();
			//call the post operation
			Ajaxs.PostResponse("tid=" + constr + "&newdb=" + newdb, "../Pages/Setup/verifysetup.php",
				function (res, url, param) {
					res = res.trim();
					//alert(res.TrimLeft(1));
					// var symbol = res.substr(0,1);
					//var mes = res=="*"?"Database Configured successfully":"Cann"
					_('veridybtn').StopLoading();
					_("dbnm").TextEnable();
					_("usernm").TextEnable();
					_("pwnm").TextEnable();
					_("hostnm").TextEnable();
					_("newdb").CheckEnable();
					if (res == "***") {
						MessageBox.Show("#empty Database".toUpperCase());
						return;
					}
					if (res == "**") {
						MessageBox.Show("#Invalid Database".toUpperCase());
						return;
					}
					if (res == "*") {
						_('contgen').HTML("../Pages/Setup/redirector.php");
						MessageBox.Show("*Database Configured".toUpperCase());
						return;
					}
					if (res == "#") {
						//cannot Connect 
						MessageBox.Show("#Connection Failed".toUpperCase());
						_("hostnm").ClearText();
					} else if (res == "##") {
						//invalid database
						MessageBox.Show("#Invalid Database or User Supplied".toUpperCase());
					} else {
						alert(res);
						//MessageBox.Show(res.toUpperCase());
					}

					_("dbnm").ClearText();
					_("usernm").ClearText();
					_("pwnm").ClearText();




				}, "text", function (res) {
					MessageBox.Show(res);
					_('veridybtn').StopLoading();
				});
		},
		Cportal: function () {

		},
		Test: function () {
			if (_('testconbtn').ClassIs("loading")) return;
			var host = _("hostnm").TextContent();
			if (host.Trim() == "") { MessageBox.Show("INVALID HOST NAME"); return }
			var db = _("dbnm").TextContent();
			if (db.Trim() == "") { MessageBox.Show("INVALID DATABASE NAME"); return }
			var user = _("usernm").TextContent();
			if (user.Trim() == "") { MessageBox.Show("INVALID USER NAME"); return }
			var pw = _("pwnm").TextContent();
			//if(pw.Trim() == ""){MessageBox.Show("INVALID PASSWORD"); return}
			var constr = "server=" + host + ";db=" + db + ";user=" + user + ";pw=" + pw;
			if (constr.Trim() == "") { MessageBox.Show("INVALID DATABASE CONNECTION STRING"); return }
			_('testconbtn').StartLoading();
			var Ajaxs = new Ajax();
			//call the post operation
			Ajaxs.PostResponse("tid=" + constr + "&txt=1", "../Pages/Setup/verifysetup.php",
				function (res, url, param) {
					// res = res.trim();
					MessageBox.Show(res);


					_('testconbtn').StopLoading();

				}, "text", function (res) {
					MessageBox.Show(res);
					_('testconbtn').StopLoading();
				});
		}/* ,
		Publish:function(){
			var host = _("hostnm").TextContent();
			if (host.Trim() == "") { MessageBox.Show("INVALID HOST NAME"); return }
			var db = _("dbnm").TextContent();
			if (db.Trim() == "") { MessageBox.Show("INVALID DATABASE NAME"); return }
			var user = _("usernm").TextContent();
			if (user.Trim() == "") { MessageBox.Show("INVALID USER NAME"); return }
			var pw = _("pwnm").TextContent();
			var constr = "server=" + host + ";db=" + db + ";user=" + user + ";pw=" + pw;
			
		} */,
		NewDbChecked: function (obj) {
			//alert("checked");
		},
		NewDbUnChecked: function (obj) {
			//alert("Unchecked");
		}
	}

}();

/************************************************************************************************** */
//The Account Object
//*Account
/************************************************************************************************** */
var Account = function () {
	return {
		//*Account.Password
		Password: {
			//*Account.Password.Generate *Password.Generate
			Generate: function () {
				var charLenght = _("genlenth").RangeValue();
				var conc = _("genconc").RangeValue();
				var domain = _("gendomain").RangeValue();
				var userdet = Cookie.Get("UserDet");
				var userdetjoin = userdet.split("~").join("");
				var numspecialChar = Math.floor((conc / 100) * charLenght);
				var knowndomain = 50 - domain;
				var numknownChar = Math.floor((knowndomain / 100) * charLenght);
				var specialChar = "`~!@#$%^&*()_-+={[\|:;\"' <,>.?/]}";
				var num = "0123456789";
				var knownChar = "";
				var specialch = "";

				//form the known words
				if (numknownChar >= userdetjoin.length) {
					knownChar = userdetjoin;
				} else {
					var availlen = userdetjoin.length - numknownChar;
					var startind = Generator.Random.Number(availlen);
					knownChar = userdetjoin.substr(startind, numknownChar);
				}

				//form the special character
				if (conc <= 25) { //use only numbers
					specialch = Generator.Random.String(numspecialChar, num);
				} else { //use both number and special characters
					specialch = Generator.Random.String(numspecialChar, num + specialChar);
				}
				//get the total already formed character
				var knwnlenght = knownChar.length + specialch.length;
				var genpassw = knownChar + specialch;
				var remstr = "";
				//if formed not up to selected lenght form remaining
				if (knwnlenght < charLenght) {
					remstr = Generator.Random.String(charLenght - knwnlenght);
					genpassw += remstr;
				} else if (knwnlenght > charLenght) {
					genpassw = genpassw.substr(0, charLenght);
				}
				_('genrst').textContent = genpassw;
				//alert(Generator.Random.String(charLenght));
				//var email = userdetarr[1];
				//var loginName = userdetarr[2];

			},
			//*Account.Password.ClearGenerate *Password.ClearGenerate
			ClearGenerate: function () {
				_('genrst').textContent = "";
			}
			,

			UseGenerate: function () {
				var gen = _('genrst').textContent.Trim();
				if (gen != "") {
					_('npassw').SetText(gen);
					_('cnpassw').SetText(gen);
					_('genrst').textContent = "";
					MessageBox.Show("*Generated Password Selected");
				}


			},
			Clear: function () {
				_("cpassw ccpassw npassw cnpassw secureemail seccontact hint").ClearText();
			},
			PasswAjax: new Ajax(),
			//save new password Information
			Save: function () {
				_("passwordfrm").submit(); //submit the form which the action will run SaveReal
			},
			//*Account.Password.Save *Password.Save
			SaveReal: function () {
				//alert('save');
				//alert(Tabs.Tab("account"))
				if (Tabs.Tab("Account").ProgressGet(0).ProgressState() != 0) {
					MessageBox.Show("System Busy, Try Again Later"); return;
				}
				//Get Data and Validate them
				var cpassw = _("cpassw").TextContent();
				if (cpassw.Trim() == "") { MessageBox.Show("Enter your Password"); return; }
				//var ccpassw = _("ccpassw").TextContent();
				//if (cpassw != ccpassw) { MessageBox.Show("Password Confirmation Failed, Check your Password"); return; }
				var npassw = _("npassw").TextContent();
				var cnpassw = _("cnpassw").TextContent();
				if (npassw != cnpassw) { MessageBox.Show("New Password Confirmation Failed, Check your New Password"); return; }
				var remail = _("secureemail").TextContent();
				if (remail.Trim() == "" || !IsEmail(remail)) { MessageBox.Show("Invalid Recovery Email"); return; }
				var rphone = _("seccontact").TextContent();
				if (rphone.Trim() == "" || !IsPhoneNumber(rphone)) { MessageBox.Show("Invalid Recovery Phone Number"); return; }
				var hint = _("hint").TextContent();
				//current user login name
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet.Trim() == "") { MessageBox.Show("#Un-Identified User. Logout and Re-Login"); return; }
				var cuserarr = cuserdet.split("~");
				if (cuserarr.length < 3) { MessageBox.Show("#Invalid User Details Found. Logout and Re-Login"); return; }
				var userlogname = cuserarr[1];
				//alert(cuserdet);
				//Package Data
				var data = "cpassw=" + escape(cpassw) +
					"&ccpassw=" + escape(cpassw) +
					"&npassw=" + escape(npassw) +
					"&cnpassw=" + escape(cnpassw) +
					"&remail=" + escape(remail) +
					"&rphone=" + escape(rphone) +
					"&hint=" + escape(hint) +
					"&userlogname=" + escape(userlogname) + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
				//alert(data);
				//Send/Post to server
				Account.Password.PasswAjax.Post(
					{
						OnProgress: function (delta) {
							Tabs.Tab("Account").ProgressGet(0).ProgressTo(Math.floor(delta * 95));
						},
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							if (res.Trim() == "#") {
								res = "*Updated Succesfully";
								//_("cpassw ccpassw npassw cnpassw").ClearText();
								_("cpassw npassw cnpassw").ClearText();
							}
							res = res.Replace('"', '\"');
							Tabs.Tab("Account").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res + '");');
						},
						OnAbort: function (res) {

							Tabs.Tab("Account").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
						},
						OnError: function (res) {
							res = res.Replace('"', '\"');
							//MessageBox.Show("Server Error: " + res);
							Tabs.Tab("Account").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Server Error: ' + res + '");');
						},
						Action: configdata['Core'] + "cportal/Pages/Scripts/Account/updpassw.php",
						PostData: data
					}
				)
			}
		},
		//*Account.Settings
		Settings: {
			SettingsAjax: new Ajax(),
			Save: function () {
				_("psettingfrm").submit();
			},
			SaveReal: function () {
				//alert('save');
				var logname = _("asettingLName").TextContent();
				if (logname.Trim() == "") { MessageBox.Show("Invalid Login Name"); return; }
				//var img = 
				var pspt = _('userpst');
				//alert(pspt.IsSet());
				if (!pspt.IsSet()) { MessageBox.Show("Set a valid Passport"); return; }
				var passprtFile = pspt.GetPadFile();
				var passportstr = "";
				if (passprtFile != null) {
					passportstr = "&" + passprtFile.PostData;
				}
				var userdet = Login.User();
				if (userdet == null) { return; }
				var userID = userdet[0];
				var data = "asettingLName=" + logname + "&UID=" + userID + passportstr + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
				Account.Settings.SettingsAjax.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Account/updateset.php",
					PostData: data,
					OnProgress: function (delta) {
						Tabs.Tab("Account").ProgressGet(2).ProgressTo(Math.floor(delta * 95));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						if (res == "#") {
							res = "*Updated Successfully";
							var userdet = Login.User();
							// if(userdet == null){return;}
							// var userID = userdet[0];
							//var dt = new Date();
							var newimgsrc = _("userpst_image").src
							_("All_userloginboximg").src = newimgsrc;
							_('userloginimgsm').src = newimgsrc;
							// _("Account_userloginboximg").src = "Files/UserImages/"+userID+".jpg?"+dt.getTime();userpst
						}
						res = res.Replace("'", "\'");
						Tabs.Tab("Account").ProgressGet(2).ProgressTo(100, "MessageBox.Show('" + res + "');");

					},
					OnAbort: function (res) {

						Tabs.Tab("Account").ProgressGet(2).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
					},
					OnError: function (res) {
						res = res.Replace('"', '\"');
						Tabs.Tab("Account").ProgressGet(2).ProgressTo(100, 'MessageBox.Show("Server Error: ' + res + '");');
					}
				})
			}

		},
		//*Account.Pin
		Pin: {
			//*Pin ajax object
			PinAjax: new Ajax(),
			//*Account.Pin.Focus *Pin.Focus
			Focus: "",//hold the id of the currently focus textbox 
			//*Account.Pin.OnFocus *Pin.OnFocus
			OnFocus: function (obj) {
				Account.Pin.Focus = obj.id;
				if (obj.id.Trim() == "cpin_inp") {
					_("selfield").textContent = "Old Pin";
				} else if (obj.id.Trim() == "npin_inp") {
					_("selfield").textContent = "New Pin";
				} else if (obj.id.Trim() == "cnpin_inp") {
					_("selfield").textContent = "Confirm New Pin";
				} else {
					_("selfield").textContent = "";
				}


				//MessageBox.Show("focus:"+obj.id);
			},
			//*Account.Pin.KeyPress *Pin.KeyPress
			KeyPress: function (obj, clear) {
				//get the textbox that has the focus
				if (Account.Pin.Focus.Trim() != "") {
					var focustb = _(Account.Pin.Focus);
					if (focustb == null) {
						MessageBox.Show("No Entering Field Selected"); return;
					}
					//alert(focustb.value.length);
					if (typeof clear != _UND) {
						if (focustb.value.length > 0) {
							focustb.value = focustb.value.substr(0, focustb.value.length - 1);
						}

						return;
					}
					var num = obj.textContent.Trim();
					if (num.Trim() == "C") {
						focustb.value = "";
						//Account.Pin.Retry();

					} else {
						focustb.value += num;
					}
					//alert(focustb);

				} else {
					MessageBox.Show("No Entering Field Selected");
				}

			},
			//*Account.Pin.KeyClear *Pin.KeyClear
			KeyClear: function () {

			},
			//*Account.Pin.OnFocus *Pin.OnFocus
			OnBlur: function (obj) {
				//Account.Pin.Focus = "";
				//MessageBox.Show("blur:"+obj.id);
			},
			//*Account.Pin.Clear
			Clear: function () {
				_("cpin npin cnpin").ClearText();
				Account.Pin.Focus = "";
				_("selfield").textContent = "";
			},
			//*Account.Pin.Save *Pin.Save
			Save: function () {
				//get all data
				var cpin = _('cpin').TextContent();
				if (cpin.Trim() == "") { MessageBox.Show("Enter your Pin"); return; }
				var npin = _('npin').TextContent();
				var cnpin = _('cnpin').TextContent();
				if (npin != cnpin) { MessageBox.Show("New Pin Confirmation Failed, Check your New Pin"); return; }
				var maxentry = _('pmaxtry').RangeValue();
				var idleTime = _('pidletime').RangeValue();
				var pinstate = _('locksw').GetStatus();
				var cuserdet = Cookie.Get("UserDet");
				if (cuserdet.Trim() == "") { MessageBox.Show("#Un-Identified User. Logout and Re-Login"); return; }
				var cuserarr = cuserdet.split("~");
				if (cuserarr.length < 3) { MessageBox.Show("#Invalid User Details Found. Logout and Re-Login"); return; }
				var userID = cuserarr[0];
				var data = "cpin=" + cpin +
					"&npin=" + npin +
					"&cnpin=" + cnpin +
					"&pmaxtry=" + maxentry +
					"&locksw=" + pinstate +
					"&pidletime=" + idleTime +
					"&userID=" + userID + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
				Account.Pin.PinAjax.Post({
					OnProgress: function (delta) {
						Tabs.Tab("Account").ProgressGet(1).ProgressTo(Math.floor(delta * 95));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						if (res.Trim() == "#") {
							Account.Pin.Clear();
							res = "*Updated Succesfully";
							var idl = _('pidletime').RangeValue();
							var pinstatus = _('locksw').GetStatus();
							Lock.Status = pinstatus.ToNumber();
							//alert(Lock.Status);
							Lock.IdleTime = 1000 * idl.ToNumber(); //set the new idletime
							Lock.AutoLock();

						}
						res = res.Replace("'", "\'");

						Tabs.Tab("Account").ProgressGet(1).ProgressTo(100, "MessageBox.Show('" + res + "');");
					},
					OnError: function (err) {
						err = err.Replace('"', '\"');
						Tabs.Tab("Account").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("#Server Error: ' + err + '");');
					},
					OnAbort: function (res) {

						Tabs.Tab("Account").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
					},
					PostData: data,
					Action: configdata['Core'] + "cportal/Pages/Scripts/Account/updpin.php"
				})
				//alert(data);
			}
		}//,
		//Group General functions
		//*Account.Save
		/*Save:function(pgid){
			// alert(pgid); 
			var selecttabInd = _(pgid).PageSelectedIndex();
			//alert(selecttabInd);
					switch (selecttabInd){
						case 0: _("passwordfrm").submit();break;
						case 1: Account.Pin.Save();break;//psettigelem
						case 2: _("psettingfrm").submit();break;
				}
		},
		//*Account.Clear
		Clear:function(pgid){
			//alert(pgid); 
		   // var selecttabInd = _(pgid).PageSelectedIndex();
			//alert(selecttabInd);
				  alert(_(pgid).SelectedName());
					switch (_(pgid).PageSelectedIndex()){
						case 0: break;
						case 1: Account[pgid].Clear();break;//psettigelem
						case 2: break;
				}
		}*/



	}

}();

/************************************************************************************************** */
//*Payment
/************************************************************************************************** */
var Payment = {
	//*Payment.Save
	/*Save:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: _("manualPayfrm").submit();break;//perform Manual Pay Save operation
					//case 1: SpreadSheet.AddRow(_('biodataPreload'));break;//preloader		
			}
	},
	//*Payment.Print
	Print:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: Payment.ManualPay.Print();break;//perform Manual Pay Print operation		
			} 
	},
	//*Payment.Clear
	Clear:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: Payment.ManualPay.Clear();break;//perform Manual Pay Clear operation		
			} 
	},
	//*Payment.Delete
	Delete:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: Payment.ManualPay.Delete();break;//perform Manual Pay Delete operation		
			} 
	},
	//*Payment.Copy
	Copy:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: Payment.ManualPay.Copy();break;//perform Manual Pay Delete operation		
			} 
	},
	//*Payment.Paste
	Paste:function(pgid){
		var selecttabInd = _(pgid).PageSelectedIndex();
		//alert(selecttabInd);
				switch (selecttabInd){
					case 4: Payment.ManualPay.Paste();break;//perform Manual Pay Delete operation		
			} 
	},*/
	//*Payment.ManualPay
	ManualPay: {
		RequestByRef: ()=>{
			OptionBox.Show({
				Title: "Send Payment Request",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/loadrequestbyref.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
				Options: [{
					Logo: "plane",
					Title: "Send Request",
					Info: "Send Ofline Payment Request",
					Function: function () {
						Payment.ManualPay.SendRequestByRef();
					},
					Parameter: null
				},
				{
					Logo: "times",
					Title: "Cancel Process",
					Info: "Cancel the current Process",
					Function: function () { }
				}]

			});
		},
		delayTimmer:null,
		LoadDetailsByRef: (e)=>{
			const ref = _('reqpayref').TextContent().Trim();
			
			if(Payment.ManualPay.delayTimmer)clearTimeout(Payment.ManualPay.delayTimmer);
			Payment.ManualPay.delayTimmer = setTimeout(()=>{
				Payment.ManualPay.PerformLoadDetailsByRef(ref);
			},500)
		},
		PerformLoadDetailsByRef:ref=>{
			const payreqdetailsBx = _('payreqdetailsBx');
			datastr = "Ref="+ encodeURIComponent(ref)+"&SubDir=" + encodeURIComponent(configdata['SubDir']);
			Payment.ManualPay.Ajax.Abort();
			if(ref != ""){
			Payment.ManualPay.Ajax.Post(
				{
					OnProgress: function (delta) {
						var perc = Math.floor(delta * 95);
						payreqdetailsBx.innerHTML = Widget.Loading();
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//alert(res);
						// return;
						payreqdetailsBx.innerHTML = res;
					},
					OnError: function (err) {
						err = err.Replace('"', '\"');
						payreqdetailsBx.innerHTML = '';
					},
					OnAbort: function (obj) {

						payreqdetailsBx.innerHTML = '';
					},
					Data: datastr,
					Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/loadrequestbyref.php"
				});	
			}else{
				payreqdetailsBx.innerHTML = '';
			}
			
		},
		Ajax: new Ajax(1000 * 60 * 30),
		SelectStud: function () {
			_('offlinepay').Hide();
			_('payofflinebx').Show();
			Payment.ManualPay.ClearAll();
			Tabs.HideSideBar('Payment', 4);
		},
		//*Payment.ManualPay.LoadLevel *ManualPay.LoadLevel 
		Load: function (obj) { //load the level when paytypechange
			if (_("mpss") == null) { MessageBox.Show("Select a Student in the Search Box"); return; }
			var RegNo = _("mpss").SelectedStudent();
			if (RegNo.Trim() == "") { MessageBox.Show("Select a Student in the Search Box"); return; }
			//var RegNo =_(selectedrw.id + "_1").Text().Trim();
			//_("mpleveltb").ClearText();
			var PayId = _("paytypetb").ValueContent();
			//alert(PayId);
			TextBox.Load("mpleveltb", configdata.Core + "cportal/Pages/Scripts/Gen/loadlevel.php?RegNo=" + escape(RegNo) + "&PayID=" + escape(PayId) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
			Payment.ManualPay.ClosePayDetBox();
			_("imgpd").ClearImagePad();
		},
		//*Payment.ManualPay.LoadPayPol *Payment.ManualPay.LoadPaymentPolicy *ManualPay.LoadPayPol *ManualPay.LoadPaymentPolicy
		LoadPayPol: function (obj, selectrw) { //load payment policy when levelchange
			if (_("mpss") == null) { MessageBox.Show("Select a Student in the Search Box"); return; }
			var RegNo = _("mpss").SelectedStudent();
			if (RegNo.Trim() == "") { MessageBox.Show("Select a Student in the Search Box"); return; }
			//var RegNo =_(selectedrw.id + "_1").Text().Trim();
			var Lvl = obj.ValueContent();
			var PayId = _("paytypetb").ValueContent();
			if (PayId.Trim() == "") { MessageBox.Show("Select the Payment Type"); return; }
			selectrw = typeof selectrw == _UND ? "" : selectrw;
			//alert(PayId); return;
			TextBox.Load("mppaypolicytb", configdata.Core + "cportal/Pages/Scripts/Gen/loadPayPol.php?RegNo=" + escape(RegNo) + "&Lvl=" + escape(Lvl) + "&PayID=" + escape(PayId) + "&Sel=" + escape(selectrw) + "&SubDir=" + encodeURIComponent(configdata.SubDir), function (obj) {
				//var sss = obj.innerHTML;
				//_("txtbxxx").innerHTML = obj.innerHTML;
				var tbid = obj.id.split("_")[0]; //get the textbox id from the drop down box id
				//alert(tbid);
				/*var sss = obj.innerHTML.Replace(tbid,"textin");
					_("txtbxxx").innerHTML = sss;*/

				var tb = _(tbid);
				if (_('selectseen') == null) {
					tb.ClearText();
				}

				var drpdwn = _(tbid + "_drpd");
				var inner = drpdwn.innerHTML.Trim();
				if (inner == "#") {
					drpdwn.innerHTML = "";
					MessageBox.Show("Complete Payment Already Made");
				}
				tb.HideLoading();
				//Payment.ManualPay.ClosePayDetBox();
			});
			if (selectrw == "") { //if no selection found, i.e just reloading the dropdown cos a successful payment update done
				Payment.ManualPay.ClosePayDetBox();
				_("imgpd").ClearImagePad();
			}

		},
		//*Payment.ManualPay.PayTypeChange *Payment.ManualPay.PaymentTypeChange *ManualPay.PayTypeChange *ManualPay.PaymentTypeChange 
		PayTypeChange: function () {
			//alert("change");
			Payment.ManualPay.Load();
			_("mppaypolicytb").ClearText();
			//Payment.ManualPay.ClosePayDetBox();
			//_("imgpd").ClearImagePad();
		},
		//*Payment.ManualPay.LoadPayDetails *Payment.ManualPay.LoadPaymentDetails *ManualPay.LoadPayDetails *ManualPay.LoadPaymentDetails
		LoadPayDetails: function (obj) { //function to load payment details when paypol change
			if (_("mpss") == null) { MessageBox.Show("Select a Student in the Search Box"); return; }
			//var RegNo = _("mpss").SelectedStudent();
			//if(RegNo.Trim() == ""){MessageBox.Show("Select a Student in the Search Box");return;}
			var selectedrw = _("mpss").SelectedObject(); //get the selected object (return the selected row for table)
			if (selectedrw == null) { MessageBox.Show("Select a Student in the Search Box"); return; }
			var studtypenum = _(selectedrw.id + "_det").value.ToNumber(); //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
			var studtype = studtypenum > 0 ? "" : "p";
			var loadcriteria = _("mpss").Data("type");

			var RegNo = selectedrw.Text().Trim();


			var PayPol = obj.ValueContent().Replace("-", "_");
			var PayId = _("paytypetb").ValueContent();
			var Lvl = _("mpleveltb").ValueContent();
			if (PayId.Trim() == "") { MessageBox.Show("Select the Payment Type"); return; }
			if (Lvl.Trim() == "") { MessageBox.Show("Select the Student Payment Level"); return; }
			var op = _("disanalysbx").style.opacity.ToNumber();
			var datastr = "RegNo=" + encodeURIComponent(RegNo) + "&PayID=" + PayId + "&Lvl=" + Lvl + "&PayPol=" + PayPol + "&studType=" + studtype;

			//"Display Loading".__();
			_('panalyLoading').Animate({ CSSRule: "opacity:1;visibility:visible", Time: 200 });
			if (op > 0) {
				_("disanalysbx").Animate({ CSSRule: "opacity:0", Time: 500, DoAt: 1, EndAction: "Payment.ManualPay.LoadPayDetailsReal('" + datastr + "')" });
			} else {
				Payment.ManualPay.LoadPayDetailsReal(datastr);
			}
			//alert(RegNo + " ; "+PayPol+" ; "+PayId+" ; "+Lvl);
		}, LoadPayDetailsReal: function (datastr) {
			/* Payment.ManualPay.Ajax.PostResponse("RegNo="+objdet.RegNo+"&PayID="+objdet.PayID+"&Lvl="+objdet.Lvl+"&PayPol="+objdet.PayPol,"Pages/Scripts/Payment/loadPayDet.php",
			  function(res,url,param){
				    
					_("disanalysbx").Animate({CSSRule:"opacity:1",Time:500});
				  }
			  , "text",function(res){
				  }); */
			_("disanalysbx").HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadPayDet.php?" + datastr + "&SubDir=" + encodeURIComponent(configdata.SubDir), function (obj) {
				obj.Animate({ CSSRule: "opacity:1", Time: 500 });
				//get the reciept details
				//receiptnumtb=768788999&receiptbanktb=firstbank&receiptbankbrtb=uyo&receiptdatetb
				var ReceiptNum = _('ReceiptNum');
				_('receiptnumtb').SetText(ReceiptNum != null ? ReceiptNum.value : "");
				var ReceiptBank = _('ReceiptBank');
				_('receiptbanktb').SetText(ReceiptBank != null ? ReceiptBank.value : "");
				var ReceiptBranch = _('ReceiptBranch');
				_('receiptbankbrtb').SetText(ReceiptBranch != null ? ReceiptBranch.value : "");
				var ReceiptDate = _('ReceiptDate');
				_('receiptdatetb').SetText(ReceiptDate != null ? ReceiptDate.value : "");

				var receipt = _("preceipt");

				//console.log(receipt.value);
				var setimg = false;
				if (receipt != null) {
					if (receipt.value.Trim() != "") {
						//alert(receipt.value);
						_("imgpd").SetPadImage(receipt.value);
						setimg = true;
					}
				}

				if (!setimg) _("imgpd").ClearImagePad();

				//"Hide Loading".__();
				_('panalyLoading').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 });
			}, function () { MessageBox.Show("#Error Loading Payment Details"); _('panalyLoading').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 }); });
		},
		//*Payment.ManualPay.ClearAll *ManualPay.ClearAll
		Clear: function () {
			Payment.ManualPay.ClearAll();
		},
		ClearAll: function () {
			_("paytypetb").ClearText();
			_("mpleveltb").ClearText();
			_("mppaypolicytb").ClearText();
			//receiptnumtb=768788999&receiptbanktb=firstbank&receiptbankbrtb=uyo&receiptdatetb
			_("receiptnumtb").ClearText();
			_("receiptbanktb").ClearText();
			_("receiptbankbrtb").ClearText();
			_("receiptdatetb").ClearText();
			_("imgpd").ClearImagePad();
			Payment.ManualPay.ClosePayDetBox();
		}, ClosePayDetBox: function () {
			_("disanalysbx").Animate({ CSSRule: "opacity:0", Time: 500, DoAt: 1, EndAction: "_('disanalysbx').innerHTML = ''" });
		},
		//*Payment.ManualPay.SetStatus *ManualPay.SetStatus
		SetStatus: function (obj) {
			var currState = obj.GetStatus();
			//var paidamtbtncont = _('paidamtbtncont');
			if (currState == 0) {
				if (_('TopPaid').value.ToNumber() == 1) {
					MessageBox.Show("Invalid Operation: Higher Payment Already Made");
					obj.Undo();
					return;
				}
				MessageBox.Show("Warning: Revoking Offline Payment Approval Request, will delete all Payment Information");
				// MessageBox.Show("Warning: Revoking Payment , will delete all Payment Information");
				// if(paidamtbtncont != null)paidamtbtncont.Show();
			} else {
				if (_("imgpd").GetPadFile() == null) {
					MessageBox.Show("Set the Payment Receipt Details");
					_("imgpd").ClearImagePad();
				}

				//if(paidamtbtncont != null)paidamtbtncont.Hide();
			}
			//alert(obj.GetStatus());
			//obj.StartWork();
		},
		//function to handle print
		//*Payment.ManualPay.Print *ManualPay.Print
		Print: function () {
			if (_("Paymenttab").ProgressGet(4).ProgressState() == 0) {
				var tn = _('CurTransNum');
				if (tn == null) {
					MessageBox.Show("No Payment Object Found");
				} else {
					if (tn.value.Trim() == "") {
						MessageBox.Show("No Payment Found");
					} else {
						var transno = tn.value;
						/*var PrinterObj = new Printer();
						PrinterObj.Preview("Payment Slip","../portal/Admin/Slip.php?ItemNo="+transno+"&folder=Payment",function(){});*/
						PDFPrinter.Print(configdata.Core + "general/Slip.php", "ItemNo=" + transno + "&folder=Payment&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
					}
				}


			} else {
				MessageBox.Show("Busy, Try Again Later");
			}
		},
		//*Payment.ManualPay.Copy  *ManualPay.Copy
		Copy: function () {
			if (_("Paymenttab").ProgressGet(4).ProgressState() == 0) {
				var tn = _('CurTransNum');
				if (tn == null) {
					MessageBox.Show("No Payment Object Found");
				} else {
					if (tn.value.Trim() == "") {
						MessageBox.Show("No Payment Found");
					} else {
						ClipBoard.Copy(tn.value, "TransNum");
						MessageBox.Show("*Payment Copied");
					}

				}

			}
		},
		//*Payment.ManualPay.Paste *ManualPay.Paste
		Paste: function () {
			MessageBox.Show("Invalid Opertaion");
		},
		//*Payment.ManualPay.Delete *ManualPay.Delete
		Delete: function () {
			var mainst = _('MainPayStatus').value.ToNumber();
			var isOffline = _('isOffline').value.ToNumber();
			///get the payment status Switcher
			var PayStatusSwitch = _("mpPayStatus");
			if (PayStatusSwitch == null) {
				var dis = mainst == 1 && isOffline == 1 ? "INVALID OPERATION: Request Already Approved" : "No Valid Request Found";
				// MessageBox.Show("No Payment Loaded"); return
				MessageBox.Show(dis); return
			}


			var st = PayStatusSwitch.GetStatus();
			if (mainst == 0 && isOffline == 0) { MessageBox.Show("Payment Information Not Exist"); return; } //if no payment maid, do nothing, cos no payment to delete
			if (_('TopPaid').value.ToNumber() == 1) { MessageBox.Show("Invalid Operation: Higher Payment Already Made"); return; }
			if (st == 1) { //if switcher is currently on
				//undo it, meaning set it to off, i.e delete payment
				var nwst = PayStatusSwitch.Undo();
			}
			//alert(PayStatusSwitch.GetStatus());
			//confirm if mainstaus is 1 and switch status is 0
			if (isOffline == 1 && st == 0) {
				Payment.ManualPay.Save(); //perform the save operation to delete it
			} else {
				MessageBox.Show("#Operation Not Allowed, Request already under-going Verification");
			}

		},
		//*Payment.ManualPay.Save *ManualPay.Save
		Save: function () {
			_("manualPayfrm").submit();
		},
		SavePerform: function () {
			var PayStatusSwitch = _("mpPayStatus");
			var mainst = _('MainPayStatus').value.ToNumber();
			var isOffline = _('isOffline').value.ToNumber();
			if (_('paytypetb').ValueContent().ToNumber() == 0 || _('mpleveltb').ValueContent().ToNumber() == 0 || _('mppaypolicytb').ValueContent().ToNumber() == 0) {
				MessageBox.Show("Select all Payment Details to Load Analysis");
				return;
			}
			if (PayStatusSwitch == null) { //if the payment status switch not exist
				//check if payment already maid
				if (_('paymade') != null) { MessageBox.Show("Payment Already Approved"); return; }
				var paynowbtn = _('paynowbtn');
				if (paynowbtn == null) { //if pay now btn not exist too
					var dis = (mainst == 1 && isOffline == 1) ? "INVALID OPERATION: Offline Request Already Approved" : "Select Payment Details to Load Analysis";
					MessageBox.Show(dis); return
				} else { //click it, cause that is the only action available
					paynowbtn.click();
					return;
				}
			}

			var st = PayStatusSwitch.GetStatus();
			if ((mainst == 1 || isOffline == 1) && st == 0) { //if delete operation display option box
				//prompt 
				OptionBox.Show({
					Title: "Delete Payment Request",
					Options: [{
						Logo: "trash",
						Title: "Continue Delete",
						Info: "Delete the Payment Details.<br /> <span class=\"altColor\">*Cannot be Reversed*</span>",
						Function: function () {
							//_('delorder').value = "0";
							Payment.ManualPay.SaveReal();
						}
					},
					{
						Logo: "times",
						Title: "Cancel Operation",
						Info: "Cancel the Delete Operation",
						Function: function () {
							_("mpPayStatus").Undo();
							_('paidamtbtncont').Hide();
						}
					}]

				});
			} else {
				Payment.ManualPay.SaveReal();
			}
		},
		SaveReal: function () {
			if (_("Paymenttab").ProgressGet(4).ProgressState() == 0) {
				//Validation
				//1. Student Selected
				var studbx = _("mpss");
				if (studbx == null) { MessageBox.Show("Search and Select Student"); return }
				var selected = studbx.SelectedObject();
				var RegNo = "";
				if (selected != null) {
					RegNo = selected.Text().Trim();

				} else {
					MessageBox.Show("No Selected Student");
					return;
				}

				var studtypenum = _(selected.id + "_det").value.ToNumber(); //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
				//alert(studtypenum);
				var studType = studtypenum < 1 ? "p" : "";
				//2. Payment Status Switcher Selected 
				var PayStatusSwitch = _("mpPayStatus");
				if (PayStatusSwitch == null) {
					MessageBox.Show("Select Payment Details to Load Analysis"); return
				}
				//3. Payment Recipt
				var payst = PayStatusSwitch.GetStatus();
				if (payst == 1) { //if student payment made, receipt must be selected
					//var PadFile = _("imgpd").GetPadFile();
					if (_('receiptnumtb').TextContent().Trim() == "") {
						MessageBox.Show("No Payment Receipt Number Set"); return
					}
					/* if (!_("imgpd").IsSet()) {
						MessageBox.Show("No Payment Receipt Set"); return
					} */
				}

				if (payst == 0 && _('delorder').value == "1") { //if current status is off and student has place order but not paid display prompt cos the order details will be deleted
					/* alert(studtypenum);
					OptionBox.Show({
						Title: "Payment Analysis/Order Found",
						Options: [{
							Logo: "trash",
							Title: "Delete Payment Information",
							Info: "Delete the Payment Analysis/Order placed by Student",
							Function: function () {
								_('delorder').value = "0";
								Payment.ManualPay.Save();
							}
						},
						{
							Logo: "times",
							Title: "Cancel Operation",
							Info: "Retain the Payment Analysis/Order placed by Student",
							Function: function () {

							}
						}]

					});
					return; */
				}

				var datastr = Page.DataString("paytypeMPelem switchbox");
				//get the manual anount if set
				var disanalysis = _('disanalysis');
				if (disanalysis != null) {
					if (disanalysis.GetStatus() == 0) {
						datastr = datastr + "&Amt=" + _('manualamttb').TextContent().ToNumber();
					}
				}
				//	alert(datastr);
				//return;
				var userdet = Login.User();
				if (userdet == null) { return; }
				var userID = userdet[0];
				datastr = datastr + "&RegNo=" + RegNo + "&studType=" + studType + "&UID=" + userID + "&SubDir=" + encodeURIComponent(configdata['SubDir']);


				Payment.ManualPay.Ajax.Post(
					{
						OnProgress: function (delta) {
							var perc = Math.floor(delta * 95);
							_("Paymenttab").ProgressGet(4).ProgressTo(perc);
						},
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							//alert(res);
							// return;
							var addfunc = "";
							if (res.Trim() == "#") {//*All Payment Details Deleted Successfully
								res = "*Offline Payment Request Deleted Successfully";
								addfunc = "Payment.ManualPay.ClearAll()";
							} else if (res.substr(0, 2) == "##") {//*Manual Payment Updated Successfully
								var TransNum = res.substr(2);
								var trnsnHid = _('CurTransNum');
								var mainPaySt = _('MainPayStatus');
								if (trnsnHid != null) trnsnHid.value = TransNum;
								if (mainPaySt != null) mainPaySt.value = "1";
								res = "*Offline Payment Request Sent Successfully";
								addfunc = "Payment.ManualPay.LoadPayPol(_('mpleveltb'),_('mppaypolicytb').ValueContent())";
							} else if (res.Trim() == "") {
								res = "#Uknown Error";
							}

							_("Paymenttab").ProgressGet(4).ProgressTo(100, "MessageBox.Show('" + res + "');" + addfunc);
						},
						OnError: function (err) {
							err = err.Replace('"', '\"');
							_("Paymenttab").ProgressGet(4).ProgressTo(100, 'MessageBox.Show("#Server Error: ' + err + '");');
						},
						OnAbort: function (obj) {

							_("Paymenttab").ProgressGet(4).ProgressTo(100, 'MessageBox.Show("Process Aborted");');
						},
						Data: datastr,
						Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/updatePayDet.php"
					});
				//MessageBox.Show(RegNo);
				//alert(Page.DataString("paytypeMPelem"))
				//_("Paymenttab").ProgressGet(4).ProgressStepTo(40);
				//get the selected RegNo
			} else {
				MessageBox.Show("Busy, Try Again Later");
			}
		},
		/**
		  The AutoAmount Display
		 */
		AutoAmount: function (st) {
			var state = st.GetStatus();
			if (state == 0) {
				_('manualamt').Show();
				_('autoamt').Hide();
				_('manualamttb').SetText(_('sysamt').value);
				_('manualamttb').TextFocus();
			} else {
				_('autoamt').Show();
				_('manualamt').Hide();
				var paidamt = _('paidamt');
				if (paidamt != null) paidamt.textContent = _('sysamt').value;
				var paidamtbtn = _('paidamtbtn');
				if (paidamtbtn != null) paidamtbtn.textContent = _('sysamt').value;
			}
		},
		ChangeAmountW: function () {
			//alert('sss');
			var num = _('wmanualamttb').TextContent().ToNumber();
			var paidamt = _('paidamt');
			if (paidamt != null) paidamt.textContent = num;
			var paidamtbtn = _('paidamtbtn');
			if (paidamtbtn != null) paidamtbtn.textContent = num;
		},
		ChangeAmount: function (a) {
			//alert('sss');
			var num = _('manualamttb').TextContent().ToNumber();
			var paidamt = _('paidamt');
			if (paidamt != null) paidamt.textContent = num;
			var paidamtbtn = _('paidamtbtn');
			if (paidamtbtn != null) paidamtbtn.textContent = num;
		}, PayNow: function () {

			var studbx = _("mpss");
			if (studbx == null) { MessageBox.Show("Search and Select Student"); return }
			var selected = studbx.SelectedObject();
			var RegNo = "";
			if (selected != null) {
				RegNo = selected.Text().Trim();

			} else {
				MessageBox.Show("No Selected Student");
				return;
			}


			var studtypenum = _(selected.id + "_det").value.ToNumber(); //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
			var studType = studtypenum < 1 ? "p" : "";
			var regid = _(selected.id + "_regid").value.ToNumber();
			var paytype = _('paytypetb').ValueContent().ToNumber();
			var paylvl = _('mpleveltb').ValueContent().ToNumber();
			var paypol = _('mppaypolicytb').ValueContent();
			if (paytype == 0 || paylvl == 0 || paypol.ToNumber() == 0) {
				MessageBox.Show("Select all Payment Details to Load Analysis");
				return;
			}
			var paypolsplit = paypol.split("_");
			var sempart = 3
			if (paypolsplit.length == 2) {
				paypol = paypolsplit[0];
				sempart = paypolsplit[1];
			}
			var datastr = "RegNo=" + RegNo + "&RegID=" + regid + "&PayId=" + paytype + "&Sem=" + paypol + "&pre=" + studType + "&lvl=" + paylvl + "&sempart=" + sempart + "&from=1";
			var disanalysis = _('disanalysis');
			if (disanalysis != null) {
				if (disanalysis.GetStatus() == 0) {
					datastr = datastr + "&Amt=" + _('manualamttb').TextContent().ToNumber();
				}
			}
			//console.log(datastr);
			Payment.ManualPay.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/mesPayOption.php",
				PostData: datastr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;

					try {
						var obj = JSON.parse(res);
						roption = [];
						if (obj.length > 1) {
							for (var d = 0; d < obj.length; d++) {
								var cur = obj[d];
								roption.push({
									Logo: cur.Logo,
									Title: cur.Name,
									Info: cur.Title,
									Function: function (param) {
										eval(param);
									},
									Parameter: cur.Action
								});
							}
							roption.push({
								Logo: "times",
								Title: "Cancel Operation",
								Info: "Terminate Payment",
								Function: function () {

								}
							});
							OptionBox.Show({
								Title: "Make Payment",
								Options: roption
							});
						} else {
							var resdis = "#Error Cannot Load Payment Types";
							//MessageBox.Show("#Error Cannot Load Payment Types");
						}

						//alert(obj.length);
					} catch (e) {
						//MessageBox.Show("#" + res);
						var resdis = "#" + res;
						resdis = resdis.Replace('"', '\"');
					}
					_('mppaypolicytb').ClearText();
					_("Paymenttab").ProgressGet(4).ProgressTo(100, 'MessageBox.Show("' + resdis + '")');
				},
				OnProgress: function (delta) {
					var perc = Math.floor(delta * 95);
					_("Paymenttab").ProgressGet(4).ProgressTo(perc);
				},
				OnError: function (res) {
					//MessageBox.Show("#Error : " + res);
					res = res.Replace('"', '\"');
					_("Paymenttab").ProgressGet(4).ProgressTo(100, 'MessageBox.Show("#Error : ' + res + '");');
				},
				OnAbort: function (res) {

					_("Paymenttab").ProgressGet(4).ProgressTo(100, 'MessageBox.Show("Payment process Aborted");');
				}

			});

		}


	},//Manual Pay

	//Payment Report
	PaymentReport: {
		GenLoader: new GenLoading({ StudyID: "preloadstudyp", FacID: "preloadfacp", DeptID: "preloaddeptp", ProgID: "preloadprogp", LevelID: "preloadlvlp", SemID: "preloadsemestp", ClassID: "preloadclassp", DisplayLevelID: "DisplayLvlp", StartSesID: "preloadstartsesp" }),
		Ajax: new Ajax(),
		EnableDateFilter: function (obj) {
			_('payrptdatefilter').style.display = "table";
			/* var sel =  _('payrpttypstb').Selected();
			 if(sel != null){
				 sel.click();
			 }*/
		},
		DisableDateFilter: function (obj) {
			_('payrptdatefilter').style.display = "none";
			/*var sel =  _('payrpttypstb').Selected();
			if(sel != null){
				sel.click();
			}*/
		},
		LoadUnSel: function (obj) {
			obj.click();
		},
		NullFunc: function (obj) {

		},
		PreLoad: () => {
			var studbx = _("payrpttypstb");
			if (studbx == null) { MessageBox.Show("#Error on Page: Reload Page"); return }
			var obj = studbx.Selected();
			var rptType = obj.Data('id');
			if (rptType == "paytypeclass" || rptType == "paytypeclassp" || rptType == "paytypeclassup" || rptType == "paytypeclassdet" || rptType == "paytypeclassdetdual") {
				OptionBox.Show({
					Title: "Select Class",
					TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/selectclass.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&type="+rptType },
					Logo: "users",
					Options: [
						{
							Title: "LOAD REPORT", Logo: "list-alt", Info: "Load the Report",
							Function:  (ref) => {
								var preloadprogp = _('preloadprogp').ValueContent();
								var preloadsemestp = _('preloadsemestp').ValueContent();
								var preloadclassp = _('preloadclassp').ValueContent();
								var preloadlvlp = _('preloadlvlp').ValueContent();//
								var preloadstartsesp = _('preloadstartsesp').ValueContent();
								var preloadmoep = _('preloadmoep').ValueContent();
								var paytypep = _('paytypep').ValueContent();
								var preloadstudyp = _('preloadstudyp').ValueContent();//
								var classlistfeetype = _('classlistfeetype').ValueContent();
								//var orderrept = _('orderrept').ValueContent();
								var payitems = _('payitemsreport').GetDataString();
								//alert(payitems);
								//
								if (Number(preloadprogp) < 1 || Number(preloadlvlp) < 1 || Number(preloadsemestp) < 1 || Number(preloadstartsesp) < 1 || Number(preloadstudyp) < 1) {
									MessageBox.Show("#Invalid Class Details Supplied");
									return;
								}

								if (Number(paytypep) < 1) {
									MessageBox.Show("#Select a Valid Payment Type");
									return;
								}
								preloadclassp = Number(preloadclassp);
								preloadmoep = Number(preloadmoep) < 1 ? 1 : preloadmoep;
								Payment.PaymentReport.Load("ProgID=" + preloadprogp + "&Lvl=" + preloadlvlp + "&Sem=" + preloadsemestp + "&ClassID=" + preloadclassp + "&StartSes=" + preloadstartsesp + "&MOE=" + preloadmoep + "&PayID=" + paytypep + "&StudyID=" + preloadstudyp + "&Fields=" + encodeURIComponent(payitems) + "&ReportFilter=" + classlistfeetype, obj, rptType=="paytypeclassdetdual"?"paytypeclassdetdual":"paytypeclassdet");
								/* Payment.PaymentReport.Load("ProgID="+preloadprogp+"&Lvl="+preloadlvlp+"&Sem="+preloadsemestp+"&ClassID="+preloadclassp+"&StartSes="+preloadstartsesp+"&MOE="+preloadmoep+"&PayID="+paytypep+"&StudyID="+preloadstudyp+"&OrderBy="+orderrept+"&Fields="+encodeURIComponent(payitems),obj,classlistfeetype); */
								//alert(preloadprogp + " - "+preloadsemestp+ " - "+preloadclassp + " - " + preloadlvlp);
							}
						}
					]
				});
				/* Payment.PaymentType.Ajax.Post({
					Action:configdata['Core']+"cportal/Pages/Scripts/Payment/selectclass.php",
					PostData:"SubDir="+encodeURIComponent(configdata['SubDir']),
					OnProgress:function(delta){
			// TitleHTML:res,
					},
					OnComplete:function(res){
						
					}
				}); */

			} else if (rptType == "payitems") { //items based report
				OptionBox.Show({
					Title: "Select Payment Item",
					TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/selectpayitem.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
					Logo: "shopping-basket",
					Options: [
						{
							Title: "LOAD REPORT", Logo: "list-alt", Info: "Load the Report",
							Function: function (ref) {
								var preloadsemestp = parseInt(_('preloadsemestp').ValueContent());
								var payitems = _('payitemsreport').GetDataString();
								Payment.PaymentReport.Load("Sem=" + preloadsemestp + "&Fields=" + encodeURIComponent(payitems), obj, "payitems");
								/* Payment.PaymentReport.Load("ProgID="+preloadprogp+"&Lvl="+preloadlvlp+"&Sem="+preloadsemestp+"&ClassID="+preloadclassp+"&StartSes="+preloadstartsesp+"&MOE="+preloadmoep+"&PayID="+paytypep+"&StudyID="+preloadstudyp+"&OrderBy="+orderrept+"&Fields="+encodeURIComponent(payitems),obj,classlistfeetype); */
								//alert(preloadprogp + " - "+preloadsemestp+ " - "+preloadclassp + " - " + preloadlvlp);
							}
						}
					]
				});
			} else {
				OptionBox.Show({
					Title: "Payments via Wallet",
					Logo: "credit-card",
					Options: [
						{
							Title: "EXCLUSIVE", Logo: "user", Info: "Exclude all payment made via wallet Channel",
							Function: function (ref) {
								Payment.PaymentReport.Load("loadwallet=0", obj);
							}
						}, {
							Title: "INCLUSIVE", Logo: "user-plus", Info: "Include all payment made via wallet Channel",
							Function: function (ref) {
								Payment.PaymentReport.Load("loadwallet=1", obj);
							}
						},
						{
							Title: "WALLET ONLY", Logo: "user-plus", Info: "Payment made via wallet Channel only",
							Function: function (ref) {
								Payment.PaymentReport.Load("loadwallet=2", obj);
							}
						}
					]
				});

				//Payment.PaymentReport.Load("",obj);
			}
		},
		Load: function (data, obj, rptType) {
			data = data || "";

			if (typeof obj == "undefined") {
				var studbx = _("payrpttypstb");
				if (studbx == null) { MessageBox.Show("#Error on Page: Reload Page"); return }
				var obj = studbx.Selected();
			}

			if (obj == null) MessageBox.Show("Select the Report Type");
			//alert(selected.id); return;
			if (typeof obj == _UND) {
				MessageBox.Show("#Invalid Parameter");
				return;
			}
			if (typeof obj.id == _UND) {
				obj.id = "tr_" + Math.Random() * 2000000;
			}
			var rptType = rptType || obj.Data('id');
			//get the session
			var ses = _('payrptses').ValueContent();
			var fr = "", to = "";

			//get if date filter is enabled
			if (_('datefilterch').Checked()) {
				//alert('ss');
				//get the selected date
				fr = _('frmdate').TextContent().Trim();
				to = _('todate').TextContent().Trim();
			}

			var offlinemode = _('payrptoffline').GetStatus();
			var onlinemode = _('payrptonline').GetStatus();

			//alert(offlinemode);
			var datastr = "reportType=" + rptType + "&ses=" + ses + "&fr=" + escape(fr) + "&to=" + escape(to) + "&objid=" + obj.id + "&offline=" + offlinemode + "&online=" + onlinemode + ((data != "") ? ("&" + data) : "");

			/* 
			"paytypeclass" || rptType == "paytypeclassp" || rptType == "paytypeclassup"
			 */
			var titleset = { "paytypesumrpt": "PAYMENT REPORT", "paytypefac": "SCHOOL STRUCTURE REPORT", "paytypeclass": "CLASS FEE LIST (SUMARIZED-ALL)", "paytypeclassp": "CLASS FEE LIST (SUMARIZED-PAID)", "paytypeclassup": "CLASS FEE LIST (SUMARIZED-DEBTOR)", "paytypeclassdet": "CLASS FEE LIST", "paytypeclassdetp": "CLASS FEE LIST (DETAILED-PAID)", "payitems": "PAYMENT ITEM REPORT","paytypeclassdetdual": "CLASS FEE LIST - DUAL" }

			datastr += "&displaytext=" + titleset[rptType];

			//check type of report
			/* 	if (rptType == "paytypesumrpt") {
					datastr += "&displaytext=PAYMENT REPORT";
				}
	
				if (rptType == "paytypefac") {
					datastr += "&displaytext=SCHOOL STRUCTURE REPORT";
					// MessageBox.Show("Note: Computing Report Based on Faculty/School might take a few minute.");
				} */
			var currdatastr = _('payrpt_curdatastr');
			if (currdatastr != null) currdatastr.textContent = "";
			Payment.PaymentReport.LastDataStr = [];
			//alert(datastr);
			Payment.PaymentReport.PerformLoad(datastr);
			/*else if(rptType == "paytypefac"){
			   //get the faculty infos
			 var facs = JSON.parse(_('facsdata').textContent);
			 var Optionsarr = [];
			 if(facs.length > 0){
				 for(var s=0; s<facs.length; s++){
					 var fac = facs[s];
					 Optionsarr.push({
						 Logo:"list-alt",
						 Title:fac.FacName.toUpperCase(),
						 Info:"Select to load Report",
						 Function:function(datastr){
							 //alert(datastr);
						  Payment.PaymentReport.PerformLoad(datastr)
						 },
						 Parameter:datastr+"&facID="+fac.FacID
					 })
				 }
				 Optionsarr.push({Logo:"times",
				 Title:"Cancel Operation",
				 Info:"Abort Report Loading Process",
				 Function:function(){
				    
				 }
			 });
				 OptionBox.Show({Title:"Select Faculty",
				 Options:Optionsarr
				 });
			 }
		 }else{//paytypeitem
			   //get the payment item infos
			   var facs = JSON.parse(_('payitemdata').textContent);
			   var Optionsarr = [];
			   if(facs.length > 0){
				   for(var s=0; s<facs.length; s++){
					   var fac = facs[s];
					   Optionsarr.push({
						   Logo:"list-alt",
						   Title:fac.ItemName.toUpperCase(),
						   Info:"Select to load Report",
						   Function:function(datastr){
							   //alert(datastr);
							Payment.PaymentReport.PerformLoad(datastr)
						   },
						   Parameter:datastr+"&itemID="+fac.ID
					   })
				   }
				   Optionsarr.push({Logo:"times",
				   Title:"Cancel Operation",
				   Info:"Abort Report Loading Process",
				   Function:function(){
					  
				   }
			   });
				   OptionBox.Show({Title:"Select Payment Item",
				   Options:Optionsarr
				   });
			   }
 
			 }*/
			//alert(datastr);
		},
		PTyper: function (obj) {
			var cst = obj.GetStatus();
			var oelems = [];
			oelems['payrptonline'] = 'payrptoffline';
			oelems['payrptoffline'] = 'payrptonline';
			if (cst == 0) {
				//check if second is off, the on it
				var altobj = _(oelems[obj.id]);
				if (altobj.GetStatus() == 0) altobj.SwitchOn();
			}
		},
		Back: function () {
			//console.log(Payment.PaymentReport.LastDataStr.length);
			if (Payment.PaymentReport.LastDataStr.length > 0) {
				var lststr = Payment.PaymentReport.LastDataStr.pop();

				Payment.PaymentReport.PerformLoad(lststr, true);
			} else {
				MessageBox.Show("No More History data Found");
			}
			//console.log(Student.RegReport.LastDataStr);
		},
		SearchPress: function (e) {
			if (window.event) { // IE                 
				keynum = e.keyCode;
			} else if (e.which) {
				// Netscape/Firefox/Opera                   
				keynum = e.which;
			}
			if (keynum == 13) {
				//alert(keynum);
				//get the kept data
				var kdata = _('payrpt_curdatastr');
				if (kdata != null) {
					Payment.PaymentReport.Search(kdata.textContent)
				}
				//_('payrptsearchbtn').click();
			}
		},
		LastDataStr: [],
		Search: function (datastr) {
			var str = _('payrptsearch').TextContent().Trim();
			if (str != "") {
				//alert(str);
				Payment.PaymentReport.PerformLoad(datastr + "&str=" + escape(str));
			} else {
				Payment.PaymentReport.PerformLoad(datastr);
			}
		},
		PerformLoad: function (datastr, back) {

			back = back || false;
			//get current display text
			var curdis = _('rptdistxt');
			if (curdis == null) {
				curdis = "REPORT";
			} else {
				curdis = curdis.textContent;
			}
			datastr += "&LastDis=" + escape(curdis);
			var currdatastr = _('payrpt_curdatastr');
			if (currdatastr != null) {
				//keep the loaded as last before loading new
				if (currdatastr.textContent.Trim() != "" && back == false) {
					Payment.PaymentReport.LastDataStr.push(currdatastr.textContent);
				}
			}
			//alert(datastr);
			Payment.PaymentReport.Ajax.Post({
				PostData: datastr + "&hist=" + Payment.PaymentReport.LastDataStr.length + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Payment/loadReport.php",
				OnProgress: function (delta) {
					var perc = Math.floor(delta * 95);
					_("Paymenttab").ProgressGet(3).ProgressTo(perc);
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					_("Paymenttab").ProgressGet(3).ProgressTo(100);
					//console.log(Payment.PaymentReport.LastDataStr.length);
					//check if error messge sent
					//alert(res);
					/* if(res.Trim().substr(0,1) == "#"){
						MessageBox.Show(res); return;
					} */
					_('reportbx').innerHTML = res;

					if (typeof param['displaytext'] != _UND) {
						_('payrptgrpbx_title').innerHTML = Icon('list-alt') + " <span id=\"rptdistxt\">" + param['displaytext'] + "</span>";
					} else {
						_('payrptgrpbx_title').innerHTML = Icon('list-alt') + " <span id=\"rptdistxt\">REPORT</span>";
					}

					var sbx = _('payrptsearch_inp');
					if (sbx != null) {
						sbx.focus();
					}
					_('payrporthome').Hide();
					_('payrptgrpbx').Show();
					Tabs.HideSideBar('Payment', 3);
					//_('payrptsearch').TextFocus();
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');
					_("Paymenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("#Internal Error: ' + res + '")');

				},
				OnAbort: function (res) {
					_("Paymenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');

				}
			})
		},
		PrintOption: (itemNum, regNo)=>{
			let opt = [];
			if(itemNum.trim() != "")opt.push({
				Title: "PAYMENT DETAILS", Logo: "user", Info: "View payment slip",
				Function: function (ref) {
					Payment.PaymentReport.PrintRc(itemNum);
				}});
				opt.push({
					Title: "WALLET HISTORY", Logo: "user-plus", Info: "View payer wallet history",
					Function: function (ref) {
					 Payment.PaymentReport.PrintWallet(regNo)
					}
				});
			OptionBox.Show({
				Title: "View Payment History (regNo)",
				Logo: "credit-card",
				Options: opt
			});
		},
		PrintRc: function (itemNum) {
			res = "ItemNo=" + itemNum;
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Payment&" + res + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
		},
		PrintWallet: function (regNo) {
			res = "RegNo=" + regNo;
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Wallet&" + res + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
		},
		Print: function () {
			//get current user det
			var cuserdet = Cookie.Get("UserDet");
			if (cuserdet != "") {
				var resarr = cuserdet.split("~");
				var userID = resarr[0]
			} else {
				var userID = 0;
			}

			var rptprintdata = _('rptprintdata');
			if (rptprintdata == null) {
				MessageBox.Show("Load Report and Click Print");
				return;
			}

			rptprintdataobj = JSON.parse(rptprintdata.textContent);
			var reportfile = "payreport.php";
			var dorientation = "P";
			if (rptprintdataobj['reportType'] == "paytypeclass" || rptprintdataobj['reportType'] == "paytypeclassp" || rptprintdataobj['reportType'] == "paytypeclassup" || rptprintdataobj['reportType'] == "paytypeclassdet" || rptprintdataobj['reportType'] == "paytypeclassdetp" || rptprintdataobj['reportType'] == "paytypeclassdetdual") {
				reportfile = "classlistfee.php";
				dorientation = "L";
			} else if (rptprintdataobj['reportType'] == "payitems") {
				reportfile = "payitems.php";
				dorientation = "L";
			} else if (rptprintdataobj['reportType'] == "payitemdet") {
				reportfile = "payitemdet.php";
				dorientation = "L";
			}
			//return;

			rptprintdataobj['UID'] = userID;
			var datastr = JSON.stringify(rptprintdataobj);
			PDFPrinter.Print(configdata.Core + "cportal/Reports/Payment/" + reportfile, "data=" + escape(datastr) + "&paper=A4&orientation=" + dorientation + "&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir));

		},

		Export: function () {
			MessageBox.Show("Note: Export will export all records to Excel format");
			//get current user det
			var cuserdet = Cookie.Get("UserDet");
			if (cuserdet != "") {
				var resarr = cuserdet.split("~");
				var userID = resarr[0]
			} else {
				var userID = 0;
			}

			var rptprintdata = _('rptprintdata');
			if (rptprintdata == null) {
				MessageBox.Show("Load Report before Exporting");
				return;
			}
			//alert(rptprintdata.textContent);
			rptprintdataobj = JSON.parse(rptprintdata.textContent);

			rptprintdataobj['UID'] = userID;
			rptprintdataobj['export'] = "true";
			var datastr = JSON.stringify(rptprintdataobj);
			Payment.PaymentReport.Ajax.Post({
				Action: configdata['Core'] + "cportal/Reports/Payment/payreport.php",
				PostData: "data=" + escape(datastr) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_("Paymenttab").ProgressGet(3).ProgressTo(100);
					if (res.Trim().substr(0, 6).toLowerCase() == "<table") {
						tableToExcel(res, 'Payment Report');
					} else {
						MessageBox.Show(res);
					}

				},
				OnProgress: function (delta) {
					var perc = Math.floor(delta * 95);
					_("Paymenttab").ProgressGet(3).ProgressTo(perc);
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');
					_("Paymenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("#Error :' + res + '");');
				},
				OnAbort: function (res) {

					_("Paymenttab").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("Report Export Aborted");');
				}
			})
		}
	},// Payment Report End
	PayNow: { //Pay Now
		GenLoader: new GenLoading({ StudyID: "pnstudstudy", FacID: "pnstudfac", DeptID: "pnstuddept", ProgID: "pnstudprog" }),
		AutoAmount: function (st) {
			var state = st.GetStatus();
			if (state == 0) {
				_('pmanualamt').Show();
				_('pautoamt').Hide();
				var manualamttb = _('pmanualamttb');
				manualamttb.SetText(_('psysamt').value.Replace(",", "").ToNumber().toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
				manualamttb.TextFocus();
			} else {
				_('pautoamt').Show();
				_('pmanualamt').Hide();
				var paidamt = _('ppaidamt');
				var namt = _('psysamt').value.Replace(",", "").ToNumber().toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
				if (paidamt != null) paidamt.textContent = namt;
				var paidamtbtn = _('ppaidamtbtn');
				if (paidamtbtn != null) paidamtbtn.textContent = namt;
			}
		},
		Reset: function () {
			_("payntypetb").ClearText();
			_('mpnleveltb').ClearTextAll();
			_('mpnpaypolicytb').ClearTextAll();

			Payment.PayNow.ClosePayDetBox();
		},
		NewPayee: function (swi) {
			var state = swi.GetStatus();
			Payment.PayNow.Reset();
			if (state == 0) { //if not new payee
				//clear and enable regno textbox
				var tb = _('payeeID');
				//tb.TextEnable();
				tb.ClearText();
				//clear and disable name textbox
				var tnnme = _('payeeName');
				tnnme.ClearText();
				tnnme.TextDisable();
				_('pnotherdet').Hide();
				tb.TextFocus();
			} else {
				var tb = _('payeeID');
				//tb.TextDisable();
				tb.SetText(_('NewPayeeID').value);
				var tnnme = _('payeeName');
				tnnme.ClearText();
				tnnme.TextEnable();
				_('pnotherdet').Show();
				_("Payee_det").value = "#";
				tnnme.TextFocus();
			}
			_('paynowhome').Hide();
			_('paynowbx').Show();
			_('paynidtb').SetText("");
			_('paynnametb').SetText("");
		},
		Done: () => {
			var state = _('newpayee').GetStatus();
			if (state == 1) {
				_('paynidtb').SetText(_('payeeID').TextContent());
				_('paynnametb').SetText(_('payeeName').TextContent());
			}
			Tabs.HideSideBar('Payment', 5);
		},
		PayTypeChange: function () {
			var tb = _('payeeID');
			if (tb.TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee ID/Student Registration Number or Select New Payee to Create New"); return; }
			//var RegNo = _("payeeName").SelectedStudent();
			if (_("payeeName").TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee Name"); return; }
			//var RegNo =_(selectedrw.id + "_1").Text().Trim();
			//_("mpleveltb").ClearText();
			var PayId = _("payntypetb").ValueContent();
			RegNo = tb.TextContent();
			//alert(PayId);
			TextBox.Load("mpnleveltb", configdata.Core + "cportal/Pages/Scripts/Gen/loadlevel.php?RegNo=" + escape(RegNo) + "&PayID=" + escape(PayId) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
			Payment.PayNow.ClosePayDetBox();
		},
		ClosePayDetBox: function () {
			_("disanalysbxn").Animate({ CSSRule: "opacity:0", Time: 500, DoAt: 1, EndAction: "_('disanalysbxn').innerHTML = ''" });
		},
		LoadPayPol: function (obj) { //load payment policy when levelchange
			var tb = _('payeeID');
			if (tb.TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee ID/Student Registration Number or Select New Payee to Create New"); return; }
			//var RegNo = _("payeeName").SelectedStudent();
			if (_("payeeName").TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee Name"); return; }
			//var RegNo =_(selectedrw.id + "_1").Text().Trim();
			var Lvl = obj.ValueContent();
			var PayId = _("payntypetb").ValueContent();
			if (PayId.Trim() == "") { MessageBox.Show("Select the Payment Type"); return; }
			selectrw = typeof selectrw == _UND ? "" : selectrw;
			//alert(PayId); return;
			TextBox.Load("mpnpaypolicytb", configdata.Core + "cportal/Pages/Scripts/Gen/loadPayPol.php?RegNo=" + encodeURIComponent(RegNo) + "&Lvl=" + encodeURIComponent(Lvl) + "&PayID=" + encodeURIComponent(PayId) + "&Sel=" + encodeURIComponent(selectrw) + "&SubDir=" + encodeURIComponent(configdata.SubDir), function (obj) {
				//var sss = obj.innerHTML;
				//_("txtbxxx").innerHTML = obj.innerHTML;
				var tbid = obj.id.split("_")[0]; //get the textbox id from the drop down box id
				//alert(tbid);
				/*var sss = obj.innerHTML.Replace(tbid,"textin");
					_("txtbxxx").innerHTML = sss;*/

				var tb = _(tbid);
				if (_('selectseen') == null) {
					tb.ClearText();
				}

				var drpdwn = _(tbid + "_drpd");
				var inner = drpdwn.innerHTML.Trim();
				if (inner == "#") {
					drpdwn.innerHTML = "";
					MessageBox.Show("Complete Payment Already Made");
				}
				tb.HideLoading();
				//Payment.ManualPay.ClosePayDetBox();
			});

		},
		LoadPayDetails: function (obj) {
			var tb = _('payeeID');
			if (tb.TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee ID/Student Registration Number or Select New Payee to Create New"); return; }
			//var RegNo = _("payeeName").SelectedStudent();
			if (_("payeeName").TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee Name"); return; }
			var studtypenum = _("Payee_det").value; //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
			var studtype = studtypenum;
			//var loadcriteria = _("mpss").Data("type");

			var RegNo = tb.TextContent();


			var PayPol = obj.ValueContent().Replace("-", "_");
			var PayId = _("payntypetb").ValueContent();
			var Lvl = _("mpnleveltb").ValueContent();
			if (PayId.Trim() == "") { MessageBox.Show("Select the Payment Type"); return; }
			if (Lvl.Trim() == "") { MessageBox.Show("Select the Student Payment Level"); return; }
			var datastr = "";
			if (_('studpayee').GetStatus() == 1) {
				//check if user select fac,dept, study and prog
				//pnstudstudy:;pnstudfac:;pnstuddept:;pnstudprog
				var pnstudstudy = _('pnstudstudy').ValueContent().ToNumber();
				var pnstudfac = _('pnstudfac').ValueContent().ToNumber();
				var pnstuddept = _('pnstuddept').ValueContent().ToNumber();
				var pnstudprog = _('pnstudprog').ValueContent().ToNumber();
				if (pnstudstudy == 0 || pnstudfac == 0 || pnstuddept == 0 || pnstudprog == 0) {
					MessageBox.Show("Select Student School Details");
					obj.ClearText();
					return;
				}
				datastr = "StudyID=" + pnstudstudy + "&FacID=" + pnstudfac + "&DeptID=" + pnstuddept + "&ProgID=" + pnstudprog + "&";
			}
			var op = _("disanalysbxn").style.opacity.ToNumber();
			datastr += "RegNo=" + encodeURIComponent(RegNo) + "&PayID=" + PayId + "&Lvl=" + Lvl + "&PayPol=" + PayPol + "&studType=" + escape(studtype) + "&idpref=p&PayeeName=" + escape(_("payeeName").TextContent()) + "&paynow=1";
			//alert(datastr);
			//"Display Loading".__();
			_('pnanalyLoading').Animate({ CSSRule: "opacity:1;visibility:visible", Time: 200 });
			if (op > 0) {
				_("disanalysbxn").Animate({ CSSRule: "opacity:0", Time: 500, DoAt: 1, EndAction: "Payment.PayNow.LoadPayDetailsReal('" + datastr + "')" });
			} else {
				Payment.PayNow.LoadPayDetailsReal(datastr);
			}
		},
		LoadPayDetailsReal: function (datastr) {
			_("disanalysbxn").HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadPayDet.php?" + datastr + "&SubDir=" + encodeURIComponent(configdata.SubDir), function (obj) {
				obj.Animate({ CSSRule: "opacity:1", Time: 500 });
				//var receipt = _("preceipt");
				//Tracer.Tag(receipt.value);
				/*var setimg = false;
				if(receipt != null){
					if(receipt.value.Trim() != ""){
						_("imgpd").SetPadImage(receipt.value);
						setimg = true;
					}  
				}
			    
				if(!setimg)_("imgpd").ClearImagePad();*/
				//"Hide Loading".__();
				var inserted = _('pninserted');
				if (inserted != null) {
					insertreg = inserted.value;
					//if auto reg used
					var NewPayID = _('NewPayeeID');
					if (insertreg == NewPayID.value) {
						var payeeidnwarr = NewPayID.value.split("/");
						var Num = payeeidnwarr[2].ToNumber() + 1;
						Num = Num + "";
						var pad = 3 - Num.length;
						var rst = (pad > 0) ? "0".repeat(pad) + Num : Num;
						payeeidnwarr[2] = rst
						NewPayID.value = payeeidnwarr.join("/");
					}
				}
				_('pnanalyLoading').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 });
			}, function () { MessageBox.Show("#Error Loading Payment Details"); _('pnanalyLoading').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 }); });
		},
		StudPayee: function (obj) {
			var stat = obj.GetStatus();
			if (stat == 0) {
				//hide the other details
				_('studpayeedet').Hide();
			} else {
				_('studpayeedet').Show();
			}
		},
		SearchAjax: new Ajax(),
		SearchPayee: function (obj) {
			var stxt = _('payeeID').TextContent();
			var PayeeNameLogo = _('payeeName_icon');
			if (_("payntypetb").ValueContent().ToNumber() != 0) {
				Payment.PayNow.Reset();
			}
			Payment.PayNow.SearchAjax.abort();
			PayeeNameLogo.className = PayeeNameLogo.className.replace("user", "cog fa-spin");
			Payment.PayNow.SearchAjax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/searchpayee.php",
				PostData: "str=" + escape(stxt) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: res => {
					if (!Login.Authenticate(res)) return;
					PayeeNameLogo.className = PayeeNameLogo.className.replace("cog fa-spin", "user");
					if (res.Trim() != "") {
						var arr = JSON.parse(res);
						//alert(res);
						if (arr) {
							if (typeof arr['Name'] != _UND) { //if froom payee_tb
								_('payeeName').SetText(arr['Name']);
							} else {
								//alert(arr['SurName']);
								_('payeeName').SetText(arr['SurName'] + " " + arr['FirstName'] + " " + arr['OtherNames']);
								_('paynidtb').SetText(stxt);
								_('paynnametb').SetText(arr['SurName'] + " " + arr['FirstName'] + " " + arr['OtherNames']);
							}
							if (typeof arr['Pre'] != _UND) {
								_("Payee_det").value = arr['Pre'];
							}
							_('paynowhome').Hide();
							_('paynowbx').Show();
							return;
						}
					}
					_('payeeName').SetText("");
					_('paynidtb').SetText("");
					_('paynnametb').SetText("");



					//
				},
				OnAbort: function () {
					//PayeeNameLogo.className = PayeeNameLogo.className.replace("cog fa-spin","user");
				},
				OnError: function () {
					PayeeNameLogo.className = PayeeNameLogo.className.replace("cog fa-spin", "user");
				},

			});
		}, Pay: function () {
			var tb = _('payeeID');
			if (tb.TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee ID/Student Registration Number or Select New Payee to Create New"); return; }
			//var RegNo = _("payeeName").SelectedStudent();
			if (_("payeeName").TextContent().Trim() == "") { MessageBox.Show("Enter a valid Payee Name"); return; }
			var studtypenum = _("Payee_det").value; //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
			var studType = studtypenum;
			//var loadcriteria = _("mpss").Data("type");

			var RegNo = tb.TextContent();





			//var studtypenum = _(selected.id+"_det").value.ToNumber(); //get the student type by the load number set (0-pstudentinfo; 1>studentinfo)
			//var studType = studtypenum < 1?"p":"";
			var regid = 1;
			var paytype = _('payntypetb').ValueContent().ToNumber();
			var paylvl = _('mpnleveltb').ValueContent().ToNumber();
			var paypol = _('mpnpaypolicytb').ValueContent().Replace("-", "_");
			if (paytype == 0 || paylvl == 0 || paypol.ToNumber() == 0) {
				MessageBox.Show("Select all Payment Details to Load Analysis");
				return;
			}
			var paypolsplit = paypol.split("_");
			var sempart = 3
			if (paypolsplit.length == 2) {
				paypol = paypolsplit[0];
				sempart = paypolsplit[1];
			}
			//var datastr = "RegNo=" + RegNo + "&RegID=" + regid + "&PayId=" + paytype + "&Sem=" + paypol + "&pre=" + studType + "&lvl=" + paylvl + "&sempart=" + sempart + "&from=1";
			var datastr = "RegNo=" + RegNo + "&RegID=" + regid + "&PayID=" + paytype + "&Sem=" + paypol + "&pre=" + studType + "&Lvl=" + paylvl + "&SemPart=" + sempart + "&from=1&BrkDwn=";
			//var paydata = "RegNo="+escape(param.RegNo)+"&Lvl="+escape(param.Lvl)+"&Sem="+escape(param.Sem)+"&SemPart="+escape(param.SemPart)+"&Amt="+escape(param.Amt)+"&PayID="+escape(param.PayID)+"&BrkDwn="+brkdwn;
			//console.log(datastr);
			var disanalysis = _('pdisanalysis');
			if (disanalysis != null) {
				if (disanalysis.GetStatus() == 0) {
					datastr = datastr + "&Amt=" + _('pmanualamttb').TextContent().Replace(",", "").ToNumber();
				}
			}

			Payment.ManualPay.Ajax.Post({
				//Action: "../portal/Admin/Payment/mesPayOption.php",
				Action: configdata['Core'] + "general/Payment/init.php",
				PostData: datastr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					try {
						var resobj = JSON.parse(res);//console.log(resobj.Error);
						if (typeof resobj.Error != _UND) { _("Paymenttab").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#ERR: ' + resobj.Error + '")'); return }
						if (typeof resobj.Ref == _UND) { _("Paymenttab").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: No Payment Reference Found")'); return }
						var amt = resobj.Amt.ToNumber().toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
						OptionBox.Show({
							Title: "Select Payment Options",
							TitleHTML: 'AMOUNT PAYABLE: <b>' + amt + "</b>",
							Logo: "money",
							Options: [
								{
									Title: "BANK", Logo: "university", Info: "Pay at Bank Option",
									Function: function (ref) {
										PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Payment&ItemNo=" + escape(ref) + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
									},
									Parameter: resobj.Ref
								},
								{
									Title: "ONLINE", Logo: "laptop", Info: "Pay online via Card",
									Function: function (ref) {
										//alert('aaa');
										var win = window.open(configdata['Core'] + "general/Payment/post.php?Ref=" + escape(ref) + "&SubDir=" + encodeURIComponent(configdata.SubDir), "newwin", "width=800,menubar=no,status=no,scrollbars=yes");
										win.focus();
									},
									Parameter: resobj.Ref
								}
							]
						});
						/* var obj = JSON.parse(res);
						roption = [];
						if (obj.length > 1) {
							for (var d = 0; d < obj.length; d++) {
								var cur = obj[d];
								roption.push({
									Logo: cur.Logo,
									Title: cur.Name,
									Info: cur.Title,
									Function: function (param) {
									//	alert(param);
										eval(param);
										//alert(param);
									},
									Parameter: cur.Action
								});
							}
							roption.push({
								Logo: "times",
								Title: "Cancel Operation",
								Info: "Terminate Payment",
								Function: function () {

								}
							});
							OptionBox.Show({
								Title: "Make Payment",
								Options: roption
							}); 
						} else {
							MessageBox.Show("#Error Cannot Load Payment Types");
						}*/

						//alert(obj.length);
					} catch (e) {
						MessageBox.Show("#" + res);
					}
					_('mpnpaypolicytb').ClearText();
					_("Paymenttab").ProgressGet(5).ProgressTo(100);
				},
				OnProgress: function (delta) {
					var perc = Math.floor(delta * 95);
					_("Paymenttab").ProgressGet(5).ProgressTo(perc);
				},
				OnError: function (res) {
					_("Paymenttab").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#Error : ' + res.Replace('"', '\"') + '");');
				},
				OnAbort: function (res) {
					_("Paymenttab").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("Payment process Aborted");');
				}

			});

		},
		ChangeAmount: function () {
			var num = _('pmanualamttb').TextContent().Replace(",", "").ToNumber().toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
			//obj.textContent.Replace(",","").ToNumber();
			//var paidamt = _('paidamt');
			//if(paidamt != null)paidamt.textContent = num;
			var paidamtbtn = _('ppaidamtbtn');
			if (paidamtbtn != null) paidamtbtn.textContent = num;
		},
		Save: function () {
			if (_("Paymenttab").ProgressGet(5).ProgressState() == 0) {
				var paidamtbtn = _('ppaidamtbtn');
				if (paidamtbtn != null) {
					paidamtbtn.click();
				} else {
					var paymade = _('ppaymade');
					if (paymade != null && paymade.value.ToNumber() == 1) {
						MessageBox.Show('Payment Already Made');
					} else {
						MessageBox.Show('No Payment Details Loaded');
					}
				}
			} else {
				MessageBox.Show("Busy, Try Again Later");
			}
		},
		Print: function () {
			if (_("Paymenttab").ProgressGet(5).ProgressState() == 0) {
				var tn = _('pCurTransNum');
				if (tn == null) {
					MessageBox.Show("No Payment Object Found");
				} else {
					if (tn.value.Trim() == "") {
						MessageBox.Show("No Payment Found");
					} else {
						var transno = tn.value;
						/*var PrinterObj = new Printer();
						PrinterObj.Preview("Payment Slip","../portal/Admin/Slip.php?ItemNo="+transno+"&folder=Payment",function(){});*/
						PDFPrinter.Print(configdata.Core + "general/Slip.php", "ItemNo=" + transno + "&folder=Payment&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
					}
				}


			} else {
				MessageBox.Show("Busy, Try Again Later");
			}
		},
		Clear: function () {
			Payment.PayNow.Reset();
			//_('pnstudstudy').ClearTextAll();
			//_('pnstudfac').ClearTextAll();
			//_('pnstuddept').ClearTextAll();
			//_('pnstudprog').ClearTextAll();
			//_('payeeName').ClearText();
		}
	},//Pay Now End

	//Payment Type
	PaymentType: {
		GetPartFields: function () {
			var maxsem = Number(_('maxsem').value);
			var partshare = _('partshare').value;
			var FArr = { HALF: [], QUATER: [] };
			for (var d = 1; d <= maxsem; d++) {
				FArr.HALF.push("F" + d + "F3");
				for (var p = 1; p <= 3; p++) {
					FArr.QUATER.push("F" + d + "F" + p);
				}
			}
			return FArr[partshare]
		},
		CheckItem: function (obj, selectval) {
			var cid = obj.id;
			var idarr = cid.split("_");
			var cellID = idarr[3];
			var delvalnum = selectval.ToNumber();
			if (cellID == "PItems") { //if Payment item cell, check if more condition is selected
				/* 	if(delvalnum == -2){
						var tr = obj.parentElement;
						console.log(tr);
						tr.classList.add('isbanner');tr.title="testing banner System";
						return;
					} */
				//diabbled no required cells
				// var reqcell = ["PLevel","PPeriod","Fpay","Spay","FpayComplete","SpayComplete","FpayFull","SpayFull","PTot","PStatus"];
				var reqcell = ["PLevel", "PPeriod", "PTot", "PStatus"];

				reqcell = reqcell.concat(Payment.PaymentType.GetPartFields());

				//alert(reqcell.length);
				for (var r = 0; r < reqcell.length; r++) {
					reqcellid = reqcell[r];

					idarr[3] = reqcellid;
					var reqcellobj = _(idarr.join("_"));
					//alert(_('paytypeanal_rw_2_FPay'));//paytypeanal_rw_2_Fpay
					if (reqcellobj != null) {
						var swobj = reqcellobj.firstElementChild;

						if (delvalnum < 0) { //if more condition is selected


							if (reqcellid != "PStatus") {

								reqcellobj.classList.add("head");
								swobj.contentEditable = false;


							} else {
								//rswitch = swobj.firstElementChild.firstElementChild;
								rswitch = swobj.firstElementChild;
								//console.log(rswitch);
								rswitch.SwitchOn();
								rswitch.Disable();
							}

						} else {
							if (!reqcellobj.classList.contains("head")) break;
							reqcellobj.classList.remove("head");
							if (reqcellid != "PStatus") {
								swobj.contentEditable = true;
							} else {
								rswitch = swobj.firstElementChild.firstElementChild;
								rswitch.SwitchOff();
								rswitch.Enable();
							}
						}

					}
				}

			}
		},
		UpdateAmt: function (totcell, totamt2) {
			var amt = totamt2 < 1 ? "" : totamt2.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
			totcell.textContent = amt;
			totcell.Data("value", amt);
			SpreadSheet.UpdateDataString(totcell);
		},
		TotalAmt: function (obj) {
			//console.log(obj.id);
			if (!obj.classList.contains('amtfield')) return;

			//if part payment is disabled, there is no need for calculating totals
			var partshare = _('partstatus').value;
			if (partshare == "FALSE") return;
			if (typeof obj != _UND && typeof obj.textContent != _UND) {
				var cid = obj.id;
				var idarr = cid.split("_");
				var cellID = idarr[3];
				var totcell = _(cid.replace(cellID, "PTot"));

				if (totcell == null) return;
				var totamt2 = 0;
				var maxsem = Number(_('maxsem').value);
				var partshare = _('partshare').value;
				//var FArr = {HALF:[],QUATER:[]};
				for (var d = 1; d <= maxsem; d++) {
					if (partshare == "HALF") { // if half
						var curobj = _(cid.replace(cellID, "F" + d + "F3"));
						if (curobj != null) {
							totamt2 += curobj.textContent.Replace(",", "").ToNumber();
						}

					} else { //if qauter
						var semsum = 0;
						for (var p = 1; p <= 2; p++) {
							var curobj = cellID == "F" + d + "F" + p ? obj : _(cid.replace(cellID, "F" + d + "F" + p));
							if (curobj != null) {
								semsum += curobj.textContent.Replace(",", "").ToNumber();
							}
						}
						var totobj = _(cid.replace(cellID, "F" + d + "F3"));
						Payment.PaymentType.UpdateAmt(totobj, semsum);
						totamt2 += semsum;
					}

				}
				Payment.PaymentType.UpdateAmt(totcell, totamt2);
				return;


				//if(cellID == "Fpay" || cellID == "Spay" || cellID == "FpayComplete" || cellID == "SpayComplete"){
				if (cellID == "Fpay" || cellID == "Spay" || cellID == "FpayComplete" || cellID == "SpayComplete") {
					//calculate total
					var cells = ["Fpay", "Spay", "FpayComplete", "SpayComplete"];
					var totamt = 0;
					var totfamt = null;
					var totsamt = null;
					for (var s = 0; s < 4; s++) {
						var indcell = cells[s];
						var curobj = _(cid.replace(cellID, indcell));

						if (curobj != null) {
							var camt = curobj.textContent.Replace(",", "").ToNumber();
							if ((cellID == "Fpay" || cellID == "FpayComplete") && (indcell == "Fpay" || indcell == "FpayComplete")) {
								totfamt = totfamt == null ? camt : totfamt + camt;
							}
							if ((cellID == "Spay" || cellID == "SpayComplete") && (indcell == "Spay" || indcell == "SpayComplete")) {
								totsamt = totsamt == null ? camt : totsamt + camt;
							}
							totamt += camt;
						}
					}


					var ftotcell = _(cid.replace(cellID, "FpayFull"));
					if (ftotcell != null && totfamt != null) {
						var famt = totfamt < 1 ? "" : totfamt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
						ftotcell.textContent = famt;
						ftotcell.Data("value", famt);
						SpreadSheet.UpdateDataString(ftotcell);
					}
					var stotcell = _(cid.replace(cellID, "SpayFull"));
					if (stotcell != null && totsamt != null) {
						var samt = totsamt < 1 ? "" : totsamt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
						stotcell.textContent = samt;
						stotcell.Data("value", samt);
						SpreadSheet.UpdateDataString(stotcell);
					}
					//console.log(totcell);
					var amt = totamt < 1 ? "" : totamt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
					totcell.textContent = amt;
					totcell.Data("value", amt);
					SpreadSheet.UpdateDataString(totcell);
				}

			}
		},
		MoreCond: function (obj) {
			alert(obj.parentElement)
		},
		//format amt to numeric - run when onblur
		FormatAmt: function (obj) {
			if (typeof obj != _UND && typeof obj.textContent != _UND) {
				var idarr = obj.id.split("_");
				var cellID = idarr[3];
				var Fields = Payment.PaymentType.GetPartFields();
				Fields.push('PTot'); //include the overall total field for formating
				var exist = false;
				for (a = 0; a < Fields.length; a++) {
					if (cellID == Fields[a]) {
						exist = true;
						break;
					}
				}
				//if(cellID == "Fpay" || cellID == "Spay" || cellID == "FpayFull" || cellID == "SpayFull" || cellID == "FpayComplete" || cellID == "SpayComplete" || cellID == "PTot"){
				if (exist) {

					var amt = obj.textContent.Replace(",", "").ToNumber();

					obj.textContent = amt < 1 ? "" : amt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
					obj.Data("value", amt);
					SpreadSheet.UpdateDataString(obj);
				}

				//for more condition selection
				if (cellID == "PItems" && obj.Data("value") == "0") {
					alert("More Condition");
				}
			}

		},
		//PayType Ajax
		Ajax: new Ajax(),
		//load the module controls
		LoadModuleCntr: function (obj) {
			var selval = obj.ValueContent();
			var modulecntrbx = _('modulescntrs');
			var selcell = _('paytbpaym').Selected();
			var selcelval = selcell != null ? _("inp_" + selcell.id).value.split("_")[0] : 0;
			//console.log(selcelval);
			modulecntrbx.innerHTML = '<div style="text-align:center;margin-top:30px"><i class="fa fa-cog fa-spin"></i></div>';
			modulecntrbx.HTML(configdata.Core + "cportal/Pages/Scripts/Payment/modules.php?DB=" + selval + "&PayID=" + selcelval + "&SubDir=" + encodeURIComponent(configdata.SubDir), function () { }, function () { });
		},
		//Load the PayRules when Module Type Change
		LoadPayTypeByModule: function (obj) {
			//get the selected paytype
			var selcontID = _("inp_" + obj.id).value;
			//alert(selcontID);
			var selcell = _('paytbpaym').Selected();
			// if(selcell != null){
			var selval = _('paymoduletb').ValueContent();
			Payment.PaymentType.LoadPayType(selcell, selval, selcontID);
			//}
			//console.log("LoadPayTypeByModule: "+seltype.id);
		},
		LoadingDet: false,
		//Load Payment Type Details
		LoadPayType: function (cell, cntrmodule, contmodID) {
			if (Payment.PaymentType.LoadingDet) return;
			//console.log("LoadPayType: "+cell.id);
			all = cntrmodule || 0; //represent loading of analyses using the supplied module type id
			//if not supplied will use the Pay item module type
			//console.log(cell.parentElement.parentElement.parentElement)
			contmodID = contmodID || 0;
			var rcellval = 0;
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj == null) return;
				var cellval = cellvalobj.value;
				rcellval = cellval.split("_")[0];
			}




			//use the ajax object to load the payment type details
			Payment.PaymentType.LoadingDet = true; //loading started
			Payment.PaymentType.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/loadpaytype.php",
				PostData: "PayID=" + rcellval + "&Type=" + all + "&MID=" + contmodID + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(Math.floor(delta * 60));
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					var fchar = res.substr(0, 1);
					if (fchar == "#") { MessageBox.Show(res) } else {

						var sp = res.split('~~!!');
						//console.log(res);
						var paydet = JSON.parse(sp[0]);
						if (param['Type'] == 0) { //if module type not supplied meaning not loaded from moduletype text change
							_('paytypenametb').SetText(paydet['ItemName']);
							_('paycurrencytb').SelectText(paydet['Currency']);
							_('payscopetb').SelectText(paydet['studType']);
							_('payitemreftb').SetText(paydet['PaymentID']);
							_('paymoduletb').SelectText(paydet['OwnerModule']);
							_('paytypegatewaytb').SelectText(paydet['PayGatewayID']);
							_('paytypedecrtb').SetText(paydet['ItemDescr']);
							_('payitemrecbnktb').SetText(paydet['CollectBank']);
							if (paydet['MultiOrder'] == "TRUE") {
								_('paytmultiorder').SwitchOn();
							} else {
								_('paytmultiorder').SwitchOff();
							}
						}

						/* console.log(sp[1]);
									Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
									return; */
						_('paytypeanabx').innerHTML = sp[1];
						_('paytypehomescreen').Hide();
						_('paymenttypebx').Show();
					}
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
					Payment.PaymentType.LoadingDet = false; //loading ended
					Tabs.HideSideBar("Payment", 0);
				},
				OnAbort: function (res) {

					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					Payment.PaymentType.LoadingDet = false; //loading ended  
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res + '");');
					Payment.PaymentType.LoadingDet = false; //loading ended 
				}
			});

		},
		Save: function () {
			_('grppayTypefrm').submit();
		},
		PerformSave: function () {
			//get the selected payment type
			var cell = _('paytbpaym').Selected();
			var rcellval = 0;
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj == null) return;
				var cellval = cellvalobj.value;
				rcellval = cellval.split("_")[0];
			}
			//get the type name
			var typename = _('paytypenametb').TextContent();
			if (typename.Trim() == "") { MessageBox.Show("Invalid Payment Type Name"); return; }
			var currency = _('paycurrencytb').ValueContent();
			var itemref = _('payitemreftb').TextContent();
			var decr = _('paytypedecrtb').TextContent();
			var payscope = _('payscopetb').ValueContent();
			var paygateway = _('paytypegatewaytb').ValueContent();
			var collectbnk = _('payitemrecbnktb').TextContent();

			var multiorder = _('paytmultiorder').GetStatus();
			if (payscope == "w" && multiorder == 1) {
				_('paytmultiorder').SwitchOff(); multiorder = 0;
			}
			if (paygateway.Trim().ToNumber() < 1) { MessageBox.Show("Select a Valid Payment Gateway Platform"); return; }
			if (payscope.Trim() == "") { MessageBox.Show("Select a Valid Payment Scope"); return; }
			var moduletb = _('paymoduletb').ValueContent();
			//get selected module id
			var modulecontroltb = _('modulecntrtb');
			if (modulecontroltb == null) { MessageBox.Show("Select a Valid Module Control"); return; }
			var modulecell = modulecontroltb.Selected();
			if (modulecell == null) { MessageBox.Show("Select a Valid Module Control"); return; }
			var cellmvalobj = _("inp_" + modulecell.id);
			if (cellmvalobj == null) { MessageBox.Show("#Invalid Module Control Selected"); return; }
			var cellmval = cellmvalobj.value;
			mcellval = cellmval.split("_")[0];
			//get the structure
			var RuleSheet = _('paytypeanal');
			if (RuleSheet == null) { MessageBox.Show("#Rule Sheet Not Found"); return; }
			if (!SpreadSheet.ColumnDataExist("paytypeanal", "PItems") || !SpreadSheet.ColumnDataExist("paytypeanal", "PTot")) {
				//MessageBox.Show("Invalid Rule Set");
				//return;
			}
			var rulesets = _('paytypeanal_datastring').value;
			var discolumns = RuleSheet.GetDisplayColumns();
			var partstatus = _('partstatus').value;
			var partshare = _('partshare').value;
			var maxsem = _('maxsem').value;
			//console.log(partshare);

			var data = "maxsem=" + rawescape(maxsem) + "&partshare=" + rawescape(partshare) + "&partstatus=" + rawescape(partstatus) + "&SelType=" + rcellval + "&Name=" + escape(typename) + "&descr=" + escape(decr) + "&Currency=" + currency + "&multiorder=" + multiorder + "&Ref=" + escape(itemref) + "&GID=" + escape(paygateway) + "&PayScope=" + escape(payscope) + "&CollectBank=" + escape(collectbnk) + "&ModuleTB=" + moduletb + "&ModuleTBID=" + mcellval + "&discolumns=" + rawescape(discolumns) + "&ruleset=" + rawescape(rulesets);
			//collectbnk
			if (rcellval == 0) {
				OptionBox.Show({
					Title: "Add New Payment Type",
					Options: [{
						Logo: "plus",
						Title: "Add New",
						Info: "Add " + typename,
						Function: function (data) {
							Payment.PaymentType.FinishSave(data);
						},
						Parameter: data
					}/* ,
		{
			Logo: "times",
			Title: "Cancel",
			Info: "Cancel Add Payment Type Operation",
			Function: function () {
				MessageBox.Show("Adding New Payment Type Canceled");
			},
			//Parameter:selectedRegNo
		} */]

				});
			} else {
				OptionBox.Show({
					Title: "Update Payment Type",
					Options: [{
						Logo: "tasks",
						Title: "Update",
						Info: "Update " + typename,
						Function: function (data) {
							Payment.PaymentType.FinishSave(data);
						},
						Parameter: data
					}/* ,
		{
			Logo: "times",
			Title: "Cancel",
			Info: "Cancel Payment Type Update",
			Function: function () {
				MessageBox.Show("Payment Type Update Canceled");
			},
			//Parameter:selectedRegNo
		} */]

				});
			}



			//console.log(data);
		},
		FinishSave: function (data) {
			Payment.PaymentType.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/savepaytype.php",
				PostData: data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(Math.floor(delta * 60));
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var fchar = res.Trim().substr(0, 1);
					if (fchar == "~") { //if successful
						var idp = res.Trim().substr(1);
						//reload the items
						_('paytypes').HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadpaytypetb.php?sel=" + idp + "&SubDir=" + encodeURIComponent(configdata.SubDir));
						res = "*Payment Type Saved Successfully";
					}
					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {

					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Error: ' + res + '");');
				}

			});
		},
		New: function () {
			_('paytypehomescreen').Hide();
			_('paymenttypebx').Show();

			//alert('gdggd');
			var selectedobj = _('paytbpaym').Selected();
			//console.log(selectedobj);
			if (selectedobj != null) {
				Table.Deselect(selectedobj)
			}
			_('paytypenametb_inp').focus();
			Tabs.HideSideBar("Payment", 0);
			//_('paytbpaym').Deselect();
		},
		GenLoader: new GenLoading({ StudyID: "simstudy", FacID: "simfac", DeptID: "simdept", ProgID: "simprog", LevelID: "simlvl", SemID: "simsemest", ClassID: "simclass" }),
		Test: function () {
			var cell = _('paytbpaym').Selected();
			var rcellval = 0;
			if (cell == null) { MessageBox.Show("No Payment Type Selected"); return }
			var cellvalobj = _("inp_" + cell.id);
			if (cellvalobj == null) { MessageBox.Show("Invalid Payment Type Selected"); return };
			var cellval = cellvalobj.value;
			rcellval = cellval.split("_")[0];
			if (rcellval == 0) {
				MessageBox.Show("Invalid Payment Type Selected"); return
			}
			/*  Payment.PaymentType.Ajax.Post({
			  Action:configdata['Core']+"cportal/Pages/Scripts/Payment/simulate.php",
			  PostData:"PayID="+rcellval+"&SubDir="+encodeURIComponent(configdata['SubDir']),
			  OnProgress:function(delta){
	  
			  },
			  OnComplete:function(res){
				  if(!Login.Authenticate(res))return;
				  if(res == "#"){MessageBox.Show("#Internal Error: Payment Type Not Found");return;}
				   */
			/* TitleHTMLb4:res, */
			OptionBox.Show({
				Title: "Simulate Payment Type",

				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/simulate.php", Data: "PayID=" + rcellval + "&SubDir=" + encodeURIComponent(configdata['SubDir']) },
				Options: [{
					Logo: "tasks",
					Title: "Simulate Now",
					Info: "Run a payment simulation, using the selected parameter",
					Function: function (selPayType) {
						var reqired = _("textBx & SimulataParamGrp & req err");
						if (reqired != null) { MessageBox.Show("Invalid Entering: All Fields are Required"); return }
						//get all data
						var data = Page.DataString("SimulataParamGrp") + "&PayID=" + selPayType;
						//console.log(data);
						Payment.PaymentType.SimulateNow(data);
					},
					Parameter: rcellval
				}/* ,
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Cancel Add Payment Type Operation",
					Function: function () {
						MessageBox.Show("Simulation Canceled");
					}
					//,Parameter:selectedRegNo
				} */]

			});
			/* }
		   }); */
			//console.log(rcellval);return;

		},
		SimulateNow: function (data) {
			//get the structure
			/* var RuleSheet = _('paytypeanal');
			if(RuleSheet == null){MessageBox.Show("#Rule Sheet Not Found");return;}
			if (!SpreadSheet.ColumnDataExist("paytypeanal", "PItems") || !SpreadSheet.ColumnDataExist("paytypeanal", "PTot")) {
			 MessageBox.Show("Invalid Rule Set");
			 return;
		 }
		 var rulesets = _('paytypeanal_datastring').value;
		 var discolumns = RuleSheet.GetDisplayColumns(); */

			//var data = "PayID="+rawescape(selPayType);
			//MessageBox.Show(data);
			PDFPrinter.Print(configdata['Core'] + "general/Slip.php", data + "&folder=Payment&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata['SubDir']), "pay_simulate.pdf");
			/* Payment.PaymentType.Ajax.Post({
			  Action:"Pages/Scripts/Payment/proccessruleset.php",
			  PostData:data,
			  OnProgress:function(delta){
				Tabs.Tab("Payment").ProgressGet(0).ProgressTo(Math.floor(delta * 60));
			  },
			  OnComplete:function(res,url,param){
				  console.log(res);
		  	
			   //MessageBox.Show(res);
			   Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
			  },
			  OnAbort:function(res){
				  MessageBox.Show("Operation Aborted");
				  Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
			  },
			  OnError:function(res){
				  MessageBox.Show("Error: "+res);
				  Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
			  }
		  
			}); */

		}, Delete: function () {
			var cell = _('paytbpaym').Selected();
			selectedid = 0;
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj != null) {
					var cellval = cellvalobj.value;
					selectedid = cellval.split("_")[0].ToNumber();
				}

			}
			if (selectedid < 1) { MessageBox.Show("No Payment Type Selected"); return; }
			OptionBox.Show({
				Title: "Delete Payment Type",
				Logo: "trash",
				Options: [{
					Logo: "thumbs-up",
					Title: "Continue",
					Info: cell.textContent + " Payment Type, will be DELETED",
					Function: function (ptyid) {
						Payment.PaymentType.DeletePayType(ptyid);
					},
					Parameter: selectedid
				}
				]
			});
		},
		DeletePayType: function (ptyids) {

			Payment.PaymentType.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/delpaytype.php",
				PostData: "ptypeid=" + ptyids + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					//convert to json
					var resobj = JSON.parse(res);
					if (typeof resobj.GID != _UND) {
						//reload the gateways names
						//_('paygates').HTML("pages/Scripts/Payment/loadgatewaydet.php?gatewaytb=1&gid="+resobj.GID);
						_('paytypes').HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadpaytypetb.php?sel=0" + "&SubDir=" + encodeURIComponent(configdata.SubDir));
						// Payment.PaymentType.New();
						Payment.PaymentType.Clear();
					}
					resdis = resobj.Message.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + resdis + '");');
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');

					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("#Internal Error ' + res + '");');
				},
				OnError: function (res) {

					Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				}
			})
		}, Clear: function () {

			CoverScreen.Show("paytypeclerstud", 'Please wait for a few seconds ...<div style="font-size:0.6em">while we clear all data on Page</div>', function () {
				Payment.PaymentType.ClearText();
				//Student.BioData.GroupCurrent = new Array();//reset the current display datastr of group array
			});


		},//function to clear text
		ClearText: function () {

			_("textBx & objgrpelempayType").ClearText(); //clear all textbox
			_('modulescntrs').innerHTML = "";

			var selectedobj = _('paytbpaym').Selected();
			//console.log(selectedobj);
			if (selectedobj != null) {
				Table.Deselect(selectedobj)
			}
			_('paytypenametb_inp').focus();
			_('paytypeanal').ClearSpreadSheet();
			CoverScreen.Close(_('paytypeclerstud'));
			//Tabs.Tab("Payment").ProgressGet(0).ProgressTo(100);
		}
	},//Payment Type End

	Troubleshoot: {
		//ptrobstudstudy:;ptrobstudfac:;ptrobstuddept:;ptrobstudprog:;ptrobstudlvl:;
		GenLoader: new GenLoading({ StudyID: "ptrobstudstudy", FacID: "ptrobstudfac", DeptID: "ptrobstuddept", ProgID: "ptrobstudprog", LevelID: "ptrobstudlvl" }),
		ChangeType: function (swi) {

			var state = swi.GetStatus();
			if (state == 1) {
				_('paytroregno').Show();
				_('paytrorange').Hide();
				_('paytrospec').focus();
			} else {
				_('paytroregno').Hide();
				_('paytrorange').Show();
			}

		},
		TRegNos: [],
		TIndex: 0,
		Ajax: new Ajax(),
		GetAllStudent: function () {
			var ptrobtn = _('ptrobtn');
			if (ptrobtn.IsLoading()) {
				MessageBox.Show("A process is on-going, wait until completion or Stop Process");
				return;
			}
			//check fixer type
			var state = _('paytrotype').GetStatus();
			if (state == 1) { //if specific student 
				//get the regNos
				var RegNotbx = _('paytrospec');
				var RegNos = RegNotbx.TextContent();
				if (RegNos.Trim() == "") {
					MessageBox.Show("Enter Student Registration Number or Payment Reference <br/> <i>(Seperate multiple Entering with space or comma)</i>");
					RegNotbx.TextFocus();
					return;
				} else {
					//get total regno
					studet = RegNos.Trim().Replace(" ", ",").split(",");
					//$data = "RegNos="+escape(RegNos);
				}
			} else {
				var studet = {};
				//fsestb
				// studet['SesID'] = _('fsestb').ValueContent().ToNumber();
				studet['StudyID'] = _('ptrobstudstudy').ValueContent().ToNumber();
				var pfac = _('ptrobstudfac');
				if (pfac != null) {
					studet['FacID'] = pfac.ValueContent().ToNumber();
					studet['DeptID'] = _('ptrobstuddept').ValueContent().ToNumber();
					studet['ProgID'] = _('ptrobstudprog').ValueContent().ToNumber();
				}


				studet['LvlID'] = _('ptrobstudlvl').ValueContent().ToNumber();

			}
			//alert(JSON.stringify(studet));
			//return;'<strong>348</strong> - Troubleshooting <span>AKS/NAS/MTH/019</span> Results ...'
			_('verpayhome').Hide();
			_('ptrobtrem').Show();

			ptrobtn.StartLoading();
			_('ptrobtitle').innerHTML = 'Reading and Processing Students ....';
			_('ptrobcontdiv').innerHTML = '';
			//load valid students
			Payment.Troubleshoot.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/verify.php",
				PostData: "GetRegNos=" + escape(JSON.stringify(studet)) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(Math.floor(delta * 19));
					//Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta*95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					Payment.Troubleshoot.TRegNos = []; Payment.Troubleshoot.TIndex = 0;
					var titbx = _('ptrobtitle');
					titbx.innerHTML = '';
					_('ptrobcontdiv').innerHTML = '';
					_('ptobcntrbtn').Hide();
					_('ptrobtn').StopLoading();
					//_('').Hide();
					if (res == "#") {

						Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("#No Valid Student/Payment Found");');

						return;
					}
					if (res == "##") {

						Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("#Error Loading Students");');

						return;
					}

					if (res == "###") {//access denied

						Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("#Access Denied <br /> Browser-Reload the system and Try Again");');

						return;
					}
					//_('rstfixcontdiv').innerHTML = res;
					//alert(res);
					//return;

					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(20);
					var studDet = JSON.parse(res);
					var totstud = studDet.Total;
					if (totstud < 1) {

						Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("No Valid Student/Payment Found");');
						return;
					}
					var studs = studDet.RegNos;
					var totbad = studDet.TotalBad;
					var studsbad = studDet.BadRegNos;
					// console.log(studDet.Q)
					Payment.Troubleshoot.TRegNos = studDet.RegNos;
					titbx.innerHTML = '<strong class="ok">' + totstud + '</strong> Valid Student/Payment Found';
					//alert(totstud + " => " +JSON.stringify(studDet.RegNos)+" ; " + totbad+ " => " +JSON.stringify(studDet.BadRegNos));
					OptionBox.Show({
						Title: "Verify & Fix Student Payment Issues",
						TitleHTML: '<table class="tbl rwb greyShadow" style="width:95%;font-size:0.8em;margin:auto" bordercolor="#CCCCCC" border="1"><tr class=""  ><th style="text-align:left">Valid Student/Payment</th><td>' + totstud + '</td></tr><tr><th style="text-align:left">Invalid Student/Payment</th><td>' + totbad + '</td></tr></table><div style="font-size:0.7em;padding:10px" class="altColor"><i>(All Invalid Student will be Ignored)</i></div>',
						ShowClose: false,
						Options: [{
							Title: "Verify Now",
							Info: "Verify all Student Payments",
							Logo: "cogs",
							Function: function () {
								Payment.Troubleshoot.TState = "Play";
								Payment.Troubleshoot.Verify(0);
								_('ptrobtitle').innerHTML = '<strong>Initializing Verification ....</strong>';

								Tabs.Tab("Payment").ProgressGet(2).ProgressTo(100);
								Tabs.HideSideBar("Payment", 2);
							}
						},
						{
							Title: "CANCEL",
							Info: "Cancel Operation",
							Logo: "times",
							Function: function () {


								_('ptrobtitle').innerHTML = '';
								Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');
							}
						}]
					})

				},
				OnAbort: function () {
					Payment.Troubleshoot.TRegNos = []; Payment.Troubleshoot.TIndex = 0;
					_('ptrobtitle').innerHTML = '';
					_('ptrobcontdiv').innerHTML = '';
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1);
					_('ptrobtn').StopLoading();
				},
				OnError: function (res) {
					Payment.Troubleshoot.TRegNos = []; Payment.Troubleshoot.TIndex = 0;
					_('ptrobtitle').innerHTML = '';
					_('ptrobcontdiv').innerHTML = '';
					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res + '");');

					_('ptrobtn').StopLoading();
				}
			});


		},
		TState: "Stop",
		Play: function () {
			//Exams.ResultFixer.FixerState = "Play";
			if (Payment.Troubleshoot.TState == 'Pause') {
				Payment.Troubleshoot.TState = "Play";
				Payment.Troubleshoot.Verify(0);
				_('ptrobplaybtn').style.display = 'none';
				_('ptrobpausebtn').style.display = 'inline-block';
				_('ptrobtitle').innerHTML = '<strong>Resuming ...</strong>';
			} else if (Payment.Troubleshoot.TState == 'Stop') {
				Payment.Troubleshoot.TState = "Play";
				Payment.Troubleshoot.GetAllStudent();
			}


		},
		Pause: function () {
			if (Payment.Troubleshoot.TState == 'Play') {
				_('ptrobtitle').innerHTML = '<strong>Pausing ...</strong>';
				Payment.Troubleshoot.TState = "Pause";
				_('ptrobpausebtn').style.display = 'none';
				_('ptrobplaybtn').style.display = 'inline-block';
			}

		},
		Stop: function () {
			if (Payment.Troubleshoot.TState == 'Play') {
				_('ptrobtitle').innerHTML = '<strong>Stoping ...</strong>';
				Payment.Troubleshoot.TState = "Stop";
			} else if (Payment.Troubleshoot.TState == 'Pause') {
				_('ptrobtitle').innerHTML = '<strong>' + (Payment.Troubleshoot.TIndex + 1) + ' of ' + Payment.Troubleshoot.TRegNos.length + '</strong> -<span class="err"> Verification Process Stoped</span>';
				Payment.Troubleshoot.TRegNos = [];
				Payment.Troubleshoot.TIndex = 0;
				Payment.Troubleshoot.TState = "Stop";
				_('ptrobtn').StopLoading();
				_('ptobcntrbtn').Hide();
				//_('fixallbtn').Show();
				_('ptrobplaybtn').style.display = 'none';
				_('ptrobpausebtn').style.display = 'inline-block';
			}

		},
		CType: 0,
		Verify: function (Type) {
			Type = Type || 0;
			CType = Type;
			var ptit = _('ptrobtitle');
			var trobtn = _('ptrobtn');
			var ptobcntrbtn = _('ptobcntrbtn');
			var ptrobcontdiv = _('ptrobcontdiv');
			//$typetxt = Type == 0 ? "" : " & Fixing";
			if (Payment.Troubleshoot.TState == 'Stop') {
				ptit.innerHTML = '<strong>' + (Payment.Troubleshoot.TIndex) + ' of ' + Payment.Troubleshoot.TRegNos.length + '</strong> -<span class="err"> Verification Process Stoped</span>';
				Payment.Troubleshoot.TRegNos = [];
				Payment.Troubleshoot.TIndex = 0;
				trobtn.StopLoading();
				ptobcntrbtn.Hide();
				//_('fixallbtn').Show();
				return;
			}

			if (Payment.Troubleshoot.TState == 'Pause') {
				ptit.innerHTML = '<strong>' + (Payment.Troubleshoot.TIndex) + ' of ' + Payment.Troubleshoot.TRegNos.length + '</strong> -<span class="altColor2"> Verification Process Paused</span>';
				//Exams.ResultFixer.FixRegNos = [];
				//Exams.ResultFixer.FixerIndex = 0;
				return;
			}

			if (Payment.Troubleshoot.TRegNos.length < 1) {
				MessageBox.Show("No Valid Student Loaded");
				ptit.innerHTML = '';
				ptrobcontdiv.innerHTML = '';
				Tabs.Tab("Payment").ProgressGet(2).ProgressTo(100);
				ptobcntrbtn.Hide();
				//_('fixallbtn').Hide();
				return;
			}
			trobtn.StartLoading();
			//start individual troubleshoting
			//$startInd = 0;

			//perform trouble shoting

			//get the regno
			$RegNo = Payment.Troubleshoot.TRegNos[Payment.Troubleshoot.TIndex];
			ptobcntrbtn.Show();
			//_('fixallbtn + cntrbtnfixall').Hide();
			//alert(JSON.stringify(Exams.ResultFixer.FixRegNos))
			//Exams.ResultFixer.FixerIndex++;
			if ($RegNo.Trim() == "") {
				Payment.Troubleshoot.TIndex++;
				if (Payment.Troubleshoot.TIndex < Payment.Troubleshoot.TRegNos.length) {
					Payment.Troubleshoot.Verify(0);
				} else {
					trobtn.StopLoading();
					ptit.innerHTML = '<strong class="ok">' + Payment.Troubleshoot.TRegNos.length + ' Student<small>(s)</small> Payments Processed Successfully</strong>';
					ptobcntrbtn.Hide();
					//_('fixallbtn').Show();
					//_('rstfixcontdiv').innerHTML = '';
				}

			} else {
				ptit.innerHTML = '<strong>' + Payment.Troubleshoot.TIndex + ' of ' + Payment.Troubleshoot.TRegNos.length + '</strong> - Verifying ' + " (" + $RegNo + ") Payment<small>(s)</small> ....";
				var FixerAj = new Ajax();
				FixerAj.Post({
					PostData: "RegNo=" + escape($RegNo) + "&Tot=" + Payment.Troubleshoot.TRegNos.length + "&Num=" + (Payment.Troubleshoot.TIndex + 1) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/verify.php",
					OnProgress: function (delta) {

					},
					OnComplete: function (res, url, param) {
						if (!Login.Authenticate(res)) return;
						//alert(res);
						//rstfixcontdiv
						_('ptrobcontdiv').insertAdjacentHTML('beforeend', res);
						Payment.Troubleshoot.TIndex++;
						if (Payment.Troubleshoot.TIndex < Payment.Troubleshoot.TRegNos.length) {
							Payment.Troubleshoot.Verify(0);
						} else {
							_('ptrobtn').StopLoading();
							_('ptrobtitle').innerHTML = '<strong class="ok">' + Payment.Troubleshoot.TRegNos.length + ' Student<small>(s)</small> / Payment<small>(s)</small> Processed Successfully</strong>';
							_('ptobcntrbtn').Hide();
							//_('fixallbtn').Show();
						}
						var rind = _(param['RegNo'] + '_scroll');
						if (rind != null) {
							//rind.scrollIntoView();
						}

					},
					OnAbort: function () {
						Payment.Troubleshoot.TRegNos = [];
						Payment.Troubleshoot.TIndex = 0;
						_('ptrobtitle').innerHTML = '<strong class="err">Process Aborted by User</strong>';
						_('ptrobtn').StopLoading();
						_('ptobcntrbtn').Hide();
						//_('fixallbtn').Show();
					},
					OnError: function () {
						Payment.Troubleshoot.TRegNos = [];
						Payment.Troubleshoot.TIndex = 0;
						//_('resultfixtitle').innerHTML = '';
						_('ptrobtitle').innerHTML = '<strong class="err">Process Aborted due to Internal error</strong>';
						_('ptrobtn').StopLoading();
						_('ptobcntrbtn').Hide();
						//_('fixallbtn').Hide();
					}
				})
			}
		},
		UpdateProg: Ref => {
			OptionBox.Show({
				Title: 'UPDATE PAYMENT',
				Logo: "edit",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/loadpayprogupdate.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Ref=" + Ref },
				Options: [{
					Logo: "edit",
					Title: "Update Payment",
					Info: "Update Student Payment to Current Academic Details",
					Function: function (Ref) {
						Payment.Troubleshoot.UpdatePayProg(Ref);
					},
					Parameter: Ref
				}, {
					Logo: "times",
					Title: "Cancel",
					Info: "Cancel Update"
				}
				]
			});
		},
		PayUpdateAjax: new Ajax,
		UpdatePayProg: Ref => {
			Payment.Troubleshoot.PayUpdateAjax.Post({
				Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Ref=" + Ref,
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/payprogupdate.php",
				OnProgress: delta => {
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(Math.round(delta) * 30);
				},
				OnError: res => {
					MessageBox.Show(res);
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(-1);
				},
				OnComplete: res => {
					var msg = res;
					try {
						resobj = JSON.parse(res);
						if (resobj.Success) {
							//get display item
							var ordbtn = _('ord_' + resobj.Ref);
							if (ordbtn != null) {
								ordbtn.parentElement.innerHTML = resobj.ProgName;
							}
						}
						msg = resobj.Message;
					} catch (error) {
						msg = "#" + error.toString();
					}


					MessageBox.Show(msg);
					Tabs.Tab("Payment").ProgressGet(2).ProgressTo(100);
				}
			});
		}
	},

	//Payment settings start
	PaySetting: {
		//format amt to numeric
		FormatAmt: function (obj) {
			if (typeof obj != _UND && typeof obj.textContent != _UND) {
				//check if the amt field payitems_rw_3_PItemAmt_edit
				if (obj.id.split("_")[3] == "PItemAmt") {

					var amt = obj.textContent.Replace(",", "").ToNumber().toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
					obj.textContent = amt;

				}
			}
		},
		Ajax: new Ajax(),
		//Add Predefined Method
		Save: function () {
			//Save code
			var settingds = _('payitems').GetDataString();
			var partpaylvlrst = _('partpaylvlrst').GetDataString();
			//var pGateway = _('paygatewtb').ValueContent();
			//var pGatewaytxt = _('paygatewtb_inp').value;
			var PayOrderValidty = _('payorderexpiretb').TextContent();
			var autosem = _('schautosem').GetStatus();
			var autolvl = _('schautolvl').GetStatus();
			var allowprogressivePay = _('allowprogressivePay').GetStatus();
			var uniquetranid = _('uniquetranid').GetStatus();
			var schbulkupdate = _('schbulkupdate').GetStatus();
			//alert(autosem);
			//var data = "PayItems="+escape(settingds)+"&PayGateWay="+escape(pGatewaytxt)+"&PayGateWayID="+escape(pGateway);
			var data = "PayItems=" + escape(settingds) + "&OrderValidity=" + escape(PayOrderValidty) + "&AutoSem=" + autosem +"&AutoLvl=" + autolvl+"&AllowProgressivePay=" + allowprogressivePay + "&uniquetranid=" + uniquetranid + "&partpaylvlrst=" + escape(partpaylvlrst) + "&schbulkupdate=" + schbulkupdate;
			Payment.PaySetting.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/setsave.php",
				PostData: data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(7).ProgressTo(Math.floor(delta * 80));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					var fchar = res.Trim().substr(0, 1);
					if (fchar == "~") { //if course group reload exist
						_('payitemsbx').innerHTML = res.Trim().substr(1);
						res = "*Payment Settings Saved";
					}
					res = res.Replace('"', '\"');

					Tabs.Tab("Payment").ProgressGet(7).ProgressTo(100, 'MessageBox.Show("' + res + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Payment").ProgressGet(7).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {

					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(7).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res + '");');
				}
			});
			//alert(settingds);
		}
	},
	//Payment settings Ends

	//Payment Gateway
	PayGateway: {
		Ajax: new Ajax(),
		LoadPayGateway: function (cell) {
			var cellvalobj = _("inp_" + cell.id);
			if (cellvalobj == null) return;
			var cellval = cellvalobj.value;
			rcellval = cellval.split("_")[0];
			OptionBox.Show({
				Title: "Payment Gateway",
				TitleHTML: OptionBox.TextBox({ id: 'techcodetb', logo: 'unlock', title: 'Technical Personel ID (TPID)', type: 'password' }),
				Logo: "money",
				Options: [{
					Logo: "thumbs-up",
					Title: "Continue",
					Info: "View Payment Gateway",
					Function: function (rcellvals) {
						var tpid = _('techcodetb');
						if (tpid == null || tpid.TextContent().Trim() == "") {
							MessageBox.Show("#INVALID TECHNICAL PERSONEL ID (TPID) SUPPLIED");
							return;
						}
						Payment.PayGateway.LoadPayGatewayReal(rcellvals, tpid.TextContent());
					},
					Parameter: rcellval
				}]
			});
		},
		LoadPayGatewayReal: function (rcellval, tpid) {
			//get all gateway details
			Payment.PayGateway.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/loadgatewaydet.php",
				PostData: "gid=" + rcellval + "&tpid=" + tpid + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//split response
					var resarr = res.split('~#split_gateway#~');
					//console.log(resarr[0])
					var resobj = JSON.parse(resarr[0]);
					if (typeof resobj.Error != _UND) {
						MessageBox.Show("#" + resobj.Error);
						var selectedobj = _('paytbpaygate').Selected();
						//console.log(selectedobj);
						if (selectedobj != null) {
							Table.Deselect(selectedobj)
						}
					} else {
						//set fields
						var tbs = resobj.Textbox;
						for (var tbd = 0; tbd < tbs.length; tbd++) {
							//individual data
							var tbdata = tbs[tbd];
							var textb = _(tbdata[0]);
							if (textb != null) {
								textb.SetText(tbdata[1]);
							}
						}
						//SwitchOn
						if (resobj.USE == 1) {
							_('paygatestatus').SwitchOn();
						} else {
							_('paygatestatus').SwitchOff();
						}

						if (resobj.FooterImage != null && resobj.FooterImage.Trim() != "") {
							//console.log(resobj.FooterImage);
							_('payGatefoot').SetPadImage(configdata['Core'] + "general/Payment/Gateways/" + resobj.FooterImage);
						} else {
							_('payGatefoot').ClearImagePad();
						}

						//if params spreaad sheet exist
						if (typeof resarr[1] != _UND) {
							_('paygateparambx').innerHTML = resarr[1];
						}
						_('paygatewayhome').Hide();
						_('paygatewaydetbx').Show();
					}
					//console.log(res);
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(100);
					Tabs.HideSideBar("Payment", 6);
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');

					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("#Server Error: ' + res + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("Opeartion Aborted");');
				}
			})
		},
		LoadScript: function (obj) {
			obj.BrowseFile(function () { }, function (s) { s.SetText("LOADED"); }, 600000000, ".php");
		},
		CopyURL: function (obj) {
			var inpel = _(obj + '_inp');
			if (inpel.value.Trim() == "") return;
			inpel.select();
			document.execCommand('copy');
			MessageBox.Show("*URL Copied to Clipboard");
		},
		Save: function () {
			_('grppaygatefrm').submit();
			//alert(_('paygatescripttb').FileDataString());
		},
		PerformSave: function () {
			//get the selected payment gatway
			var cell = _('paytbpaygate').Selected();
			selectedid = 0;
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj != null) {
					var cellval = cellvalobj.value;
					selectedid = cellval.split("_")[0].ToNumber();
				}

			}
			var reqired = _("textBx & objgrpelempaygate & req err");
			if (reqired != null) {
				reqired = IsArray(reqired) ? reqired : [reqired];
				var reqstr = "";
				for (var r = 0; r < reqired.length; r++) {
					var reqelem = reqired[r];
					reqstr += reqelem.title;
					if (r < reqired.length - 1) { //if not the last one
						if (r < reqired.length - 2) { //if second to the last
							reqstr += ", ";
						} else {
							reqstr += " and ";
						}
					}
				}
				MessageBox.Show("INVALID ENTERING (" + reqstr + ")");
				return;
			}
			$str = selectedid < 1 ? "Add New" : "Update";
			OptionBox.Show({
				Title: $str + " Payment Gateway",
				TitleHTML: OptionBox.TextBox({ id: 'techcodetb', logo: 'unlock', title: 'Technical Personel ID (TPID)', type: 'password' }),
				Logo: "money",
				Options: [{
					Logo: "plus",
					Title: "Continue",
					Info: $str + " Payment Gateway, Name must be unique",
					Function: function (gid) {
						Payment.PayGateway.SavePayGateway(gid);
					},
					Parameter: selectedid
				}]
			});

		},
		SavePayGateway: function (gid) {
			//get all user supplied data
			var tpid = _('techcodetb');
			if (tpid == null || tpid.TextContent().Trim() == "") {
				MessageBox.Show("#INVALID TECHNICAL PERSONEL ID (TPID) SUPPLIED");
				return;
			}
			//get file uploded
			gatescript = "";
			var floaded = _('paygatescripttb paygaterequesturltb paygateresponsetb payGatefoot_image');
			for (var fl = 0; fl < floaded.length; fl++) {
				var scrtb = floaded[fl];
				var gatescriptind = scrtb.FileDataString();
				//var txt = scrtb.TextContent();
				if (gatescriptind.Trim() != "") {
					gatescript += "&" + gatescriptind;
				}
			}
			//alert(gatescript);
			//get the payment parameters
			var payparam = _('paygateparamspreadsheet').GetDataString();




			data = Page.DataString('objgrpelempaygate') + "&tpid=" + escape(tpid.TextContent()) + gatescript + "&gid=" + gid + "&param=" + escape(payparam);
			//alert(data);
			Payment.PayGateway.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/savegateway.php",
				PostData: data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					//convert to json
					var resobj = JSON.parse(res);
					if (typeof resobj.GID != _UND) {
						//reload the gateways names
						_('paygates').HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadgatewaydet.php?gatewaytb=1&gid=" + resobj.GID + "&SubDir=" + encodeURIComponent(configdata.SubDir));
					}

					resdis = resobj.Message.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("' + resdis + '");');
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');

					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res + '");');
				},
				OnError: function (res) {

					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				}
			})
		},
		//Clear/Deselect for new entering
		New: function () {
			var selectedobj = _('paytbpaygate').Selected();
			//console.log(selectedobj);
			if (selectedobj != null) {
				Table.Deselect(selectedobj)
			}
			_('grppaygatefrm').reset();
			_('paygateparamspreadsheet').ClearSpreadSheet();
			_('paygatenametb_inp').focus();
			_('paygatewayhome').Hide();
			_('paygatewaydetbx').Show();
			Tabs.HideSideBar("Payment", 6);
		},
		Clear: function () {
			Payment.PayGateway.New();

		}, Delete: function () {
			var cell = _('paytbpaygate').Selected();
			selectedid = 0;
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj != null) {
					var cellval = cellvalobj.value;
					selectedid = cellval.split("_")[0].ToNumber();
				}

			}
			if (selectedid < 1) { MessageBox.Show("No Payment Gateway Selected"); return; }
			OptionBox.Show({
				Title: "Delete Payment Gateway",
				TitleHTML: OptionBox.TextBox({ id: 'techcodetb', logo: 'unlock', title: 'Technical Personel ID (TPID)', type: 'password' }),
				Logo: "trash",
				Options: [{
					Logo: "thumbs-up",
					Title: "Continue",
					Info: cell.textContent + " Payment Gateway, will be DELETED",
					Function: function (gid) {
						Payment.PayGateway.DeletePayGateway(gid);
					},
					Parameter: selectedid
				}
				]
			});
		},
		DeletePayGateway: function (gids) {
			var tpid = _('techcodetb');
			if (tpid == null || tpid.TextContent().Trim() == "") {
				MessageBox.Show("#INVALID TECHNICAL PERSONEL ID (TPID) SUPPLIED");
				return;
			}
			Payment.PayGateway.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/delgateway.php",
				PostData: "gid=" + gids + "&tpid=" + escape(tpid.TextContent()) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					console.log(res);
					//convert to json
					var resobj = JSON.parse(res);
					if (typeof resobj.GID != _UND) {
						//reload the gateways names
						_('paygates').HTML(configdata.Core + "cportal/Pages/Scripts/Payment/loadgatewaydet.php?gatewaytb=1&gid=" + resobj.GID + "&SubDir=" + encodeURIComponent(configdata.SubDir));
						Payment.PayGateway.New();
					}

					resdis = resobj.Message.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("' + resdis + '");');
				},
				OnError: function (res) {
					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res + '");');
				},
				OnError: function (res) {

					Tabs.Tab("Payment").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				}
			})
		}
	}
	//Payment Gateway Ends
	,
	PayApproval: {//Offline Payment Approval
		Ajax: new Ajax(),
		View: function (orderid, det, rwnum) {
			OptionBox.Show({
				Title: "Offline Payment Request",
				TitleHTML: det,
				Logo: "tasks",
				Options: [{
					Logo: "file",
					Title: "View Payment Request",
					Info: "View Offline Payment Request Details",
					Function: function (oid) {
						// alert("print "+oid);
						PDFPrinter.Print(configdata.Core + "cportal/Reports/Payment/offlinereceipt.php", "OrderID=" + oid + "&paper=A4&orientation=P&MT=4&MB=40" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "offlinereceipt.pdf");
					},
					Parameter: orderid
				},
				{
					Logo: "trash",
					Title: "Delete Request",
					Info: "Delete Offline Payment Request",
					Function: function (param) {
						var oid = param[0];
						var rwnum = param[1];
						Payment.PayApproval.Ajax.Post({
							Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/delpayrequest.php",
							PostData: "OrderID=" + oid + "&rwnum=" + rwnum + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
							OnProgress: function (delta) {
								Tabs.Tab("Payment").ProgressGet(8).ProgressTo(Math.floor(delta * 50));
							},
							OnComplete: function (res, url, params) {
								if (res != "#") {
									//
								} else {
									res = "*OFFLINE PAYMENT DELETED SUCCESSFULLY";
									SpreadSheet.DeleteRow(params['rwnum'], "payapprssb", true);
								}

								res = res.Replace('"', '\"');
								Tabs.Tab("Payment").ProgressGet(8).ProgressTo(100, 'MessageBox.Show("' + res + '");');
							},
							OnAbort: function (res) {

								Tabs.Tab("Payment").ProgressGet(8).ProgressTo(-1, 'MessageBox.Show("Delete Operation Aborted");');
							},
							OnError: function (res) {
								res = res.Replace('"', '\"');

								Tabs.Tab("Payment").ProgressGet(8).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res + '");');
							}
						});
						//delete request
					},
					Parameter: [orderid, rwnum]
				}
				]
			});
			//	alert(datasrt);

			/*var RestPrint = new Printer();
					  RestPrint.Preview("Result Sheet","Reports/Exams/resultsheet.php?"+datasrt,function(){});*/
			//PDFPrinter.Print("Reports/Exams/resultsheet.php", datasrt + "&paper=A4&orientation=P&MT=4&MB=40", "resultsheet.pdf");
		},
		SearchAjax: new Ajax(),
		SearchDelayTimer: null,
		Search: function () {
			//alert(obj);
			if (Payment.PayApproval.SearchDelayTimer != null) {
				clearTimeout(Payment.PayApproval.SearchDelayTimer);
				Payment.PayApproval.SearchDelayTimer = null;
				Payment.PayApproval.SearchAjax.abort();
			}
			Payment.PayApproval.SearchDelayTimer = setTimeout(function () {

				_('rstpayapprbx').FadeOut(300);
				_('payapprrstsloadin').Animate({ CSSRule: "opacity:1;visibility:visible", Time: 300 });
				var UID = Login.User();
				UID = UID[0]
				var limit = _('payapprmaxrec').RangeValue();
				var val = _("payappsearch").TextContent();
				var filter = _("payapprfilter").TextContent();
				Payment.PayApproval.SearchAjax.Post(
					{
						Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/payapprsearch.php",
						PostData: "UID=" + UID + "&limit=" + limit + "&val=" + escape(val) + "&filter=" + filter + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							_('rstpayapprbx').innerHTML = res;
							_('rstpayapprbx').FadeIn(300);
							_('payapprrstsloadin').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 300 });
							Payment.PayApproval.SearchDelayTimer = null;
							// alert(res);
						},
						OnError: function (res) {
							MessageBox.Show("#Internal Error: " + res);
							Payment.PayApproval.SearchDelayTimer = null;
						}
					}
				)
			}, 300);
			//alert(UID + ";" + limit + ";" + val);
			//var val = _("rstappsearch").Text
		},
		Save: function () {
			var ssbobj = _('payapprssb');
			if (ssbobj == null) {
				return;
			}
			OptionBox.Show({
				Title: "Save Offline Payment Approval Status",
				Options: [
					{
						Title: "Continue",
						Logo: "save",
						Info: "Save all displayed Offline Payment Approval Status",
						Function: function () {
							var UID = Login.User();
							UID = UID[0];
							var datas = _('payapprssb').GetDataString();
							datas = datas + "&UID=" + UID;
							Payment.PayApproval.SaveAjax = new Ajax();
							Payment.PayApproval.SaveAjax.Post({
								Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/savepayappr.php",
								PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
								OnProgress: function (delta) {
									Tabs.Tab("Payment").ProgressGet(8).ProgressTo(Math.floor(delta * 90));
								},
								OnComplete: function (res) {
									if (!Login.Authenticate(res)) return;
									Tabs.Tab("Payment").ProgressGet(8).ProgressTo(100, 'MessageBox.Show("' + res + '");');

								},
								OnAbort: function (res) {
									Tabs.Tab("Payment").ProgressGet(8).ProgressTo(-1, 'MessageBox.Show("#Operation Aborted");');

								},
								OnError: function (res) {

									res = res.Replace('"', '\"');
									Tabs.Tab("Payment").ProgressGet(8).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res + '");');
								}
							});
						}
					},
					{
						Title: "Cancel",
						Logo: "times",
						Info: "Terminate Save Operation",
						Function: function () {
							MessageBox.Show("Save Operation Aborted");
						}
					}
				]
			});
		},
		Clear: function () {
			_('removeRw_payapprssb').click();
		}, Print: function () {
			//check spreadsheet 
			var sprsh = _('parampayapp');
			if (sprsh != null) {
				//get the datastr 
				var datastr = sprsh.value + "&paper=A4&orientation=P&MT=4&MB=32";

				//get the user id
				//var UID = Login.User();
				//UID = UID[0];
				//get the search val 
				//var txtval = _('rstappsearch').TextContent();
				//datastr += "&UID="+UID+"&val="+escape(txtval);
				//alert(datastr);
				PDFPrinter.Print(configdata.Core + "cportal/Reports/Payment/payapprsheet.php", datastr + "&SubDir=" + encodeURIComponent(configdata.SubDir), "payapprs.pdf");
				//PDFPrinter.Print("root://cportal/Reports/Exams/broadsheet.epr", "", "apprs.pdf");
			} else {
				MessageBox.Show("No Record Found");
			}
		}
	},
	Wallet: {
		FormatAmt: function (obj) {
			if(obj.Data('column') == "1"){
				var amt = obj.textContent.Replace(",", "").ToNumber();

			obj.textContent = amt < 1 ? "" : amt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
			obj.Data("value", amt);
			SpreadSheet.UpdateDataString(obj);
			}
			
		},
		Ajax: new Ajax(),
		Save: function () {
			var cell = _('wpaytbll').Selected();
			var rcellval = '0';
			if (cell != null) {
				var cellvalobj = _("inp_" + cell.id);
				if (cellvalobj == null) return;
				var cellval = cellvalobj.value;
				rcellval = cellval.split("_")[0];
			}
			if (rcellval == 0) {
				MessageBox.Show("#No Payment Type Assign to Wallet System"); return;
			}

			var pamtsheet = _('pwalletamtsheet_datastring').value;
			var minbal = _('wallmimbaltb').TextContent();
			var menuid = _('wallportmenu').ValueContent();
			var dyamtstatus = _('dynamicwalamt').GetStatus();
			//alert(minbal);return;
			var data = "Amts=" + encodeURIComponent(pamtsheet) + "&PayID=" + rcellval + "&MinBal=" + minbal + "&MenuID=" + menuid+ "&DynamicAmt=" + dyamtstatus;
			//alert(rcellval + " == " +pamtsheet);
			Payment.Wallet.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Payment/savewalletset.php",
				PostData: data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Payment").ProgressGet(9).ProgressTo(Math.floor(delta * 60));
				},
				OnComplete: function (res, url, param) {
					//alert(res);
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					Tabs.Tab("Payment").ProgressGet(9).ProgressTo(100, 'MessageBox.Show("' + res + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Payment").ProgressGet(9).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {

					res = res.Replace('"', '\"');
					Tabs.Tab("Payment").ProgressGet(9).ProgressTo(100, 'MessageBox.Show("Error: ' + res + '");');
				}

			});
		}
	}
} //Payment Object


/************************************************************************************************** */
//Users Object
/************************************************************************************************** */
var Users = {
	//*Users.Manage
	Manage: {
		StaffChange: function (obj) { //method to handle the staff switch change
			var st = obj.GetStatus();
			if (st == 1) { //if on
				//make box visible
				// _("ustaffdet").FadeIn(200);
				//set textbox to be writeable
				//_("ustaffname_inp").readOnly = "";
				// _("ustaffid_inp").readOnly = "";
				// _("ustaffunit_inp").readOnly = "";
			} else {
				//_("ustaffdet").Animate({CSSRule:"opacity:0.6",Time:200});
				//_("ustaffname_inp").readOnly = "readonly";
				//_("ustaffid_inp").readOnly = "readonly";
				//_("ustaffunit_inp").readOnly = "readonly"; 
			}
		},
		Ajax: new Ajax(), //ajax object fro manage module
		//Users.Manage.Load - load the selected user details (Login Name, Username and Passport)
		Load: function (selobj) {
			if (Tabs.Tab("Users").ProgressGet(0).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user and validate it
			// var selobj = _('usermag').SelectedObject(true);
			if (selobj == null) { MessageBox.Show("#Selected User Identification Failed"); return }
			var selUserID = selobj.Data("id").Trim();
			if (selUserID != "") {
				Users.Manage.Ajax.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Users/loaduser.php",
					PostData: "UID=" + escape(selUserID) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Users").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						// MessageBox.Show(res);
						res = res.Trim();
						if (res == "") {
							MessageBox.Show("#Invalid User Record Found");
						} else {
							resarr = res.split("~~@##~~");
							//check if valid 
							if (resarr.length == 4) {
								var UID = resarr[0];
								var ULogName = resarr[1];
								var UName = resarr[2];
								var staffst = resarr[3].ToNumber();
								//alert(staffst);
								//set the textboxes
								_('userLognametb').SetText(ULogName);
								_('usernametb').SetText(UName);
								var ststobj = _("ustaffst");
								//set the hidden staff st element which holds the staff state of the loaded user
								if (staffst > 0) { ststobj.SwitchOn(); _('CurrStaffSt').value = "1" } else { ststobj.SwitchOff(); _('CurrStaffSt').value = "0" }
								_('userpasspd').SetPadImage("Files/UserImages/" + UID + ".jpg");
								_('manageuserhome').Hide();
								_('userManageFrm').Show();
							} else {
								//alert(res);
								MessageBox.Show(res);
							}
						}
						Tabs.Tab("Users").ProgressGet(0).ProgressTo(100);
						Tabs.HideSideBar("Users", 0);
					},
					OnAbort: function () {

						Tabs.Tab("Users").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					},
					OnError: function (res) {
						//MessageBox.Show("Server Error: " + res);
						Tabs.Tab("Users").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res.Replace('"', '\"') + '");');
					}
				})
			} else {
				MessageBox.Show("#Selected User Identification Failed");
			}
		}//Users.Manage.Load
		//Users.Manage.Clear
		, Clear: function () {
			// alert("Clear");
			_('userLognametb usernametb').ClearText();
			_('userpasspd').ClearImagePad();
			_('ustaffst').SwitchOff();
			_('CurrStaffSt').value = "0";
			var usersearch = _('usermag');
			if (usersearch) {
				obj_usermag.ReSearch();
			}
			_('manageuserhome').Hide();
			_('userManageFrm').Show();
			Tabs.HideSideBar("Users", 0);
			_('userLognametb_inp').focus();
		}//Users.Manage.Clear
		//Users.Manage.Save
		, Save: function () {
			_('userManageFrm').submit();
		}//Users.Manage.Save
		//Users.Manage.SaveReal
		, SaveReal: function () {
			if (Tabs.Tab("Users").ProgressGet(0).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user
			var usersearch = _('usermag');
			var selobj = null;
			if (usersearch) {
				var selobj = usersearch.SelectedObject(true);
			}

			var selUserID = "";
			if (selobj != null) {
				selUserID = selobj.Data("id");
			}
			var reqired = _("textBx & usermanageGrp & req err");
			if (reqired != null) { MessageBox.Show("Invalid Entering"); return }
			//if()
			//alert(_('userpasspd').IsSet());
			if (!_('userpasspd').IsSet()) { MessageBox.Show("Invalid User Passport"); return; }

			if (selUserID == "") {
				//popup
				OptionBox.Show({
					Title: "Add New User",
					Options: [{
						Logo: "plus",
						Title: "Add User",
						Info: "Add a New User",
						Function: function () {
							Users.Manage.PerformSave(0);
						},
						//Parameter:selectedRegNo
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Cancel Add New User Operation",
						Function: function () {
							MessageBox.Show("Add New User Operation Canceled");
						},
						//Parameter:selectedRegNo
					}]

				});
			} else {
				if (_("ustaffst").GetStatus() == 0 && _('CurrStaffSt').value == "1") { //if user is a staff and want to un staff
					OptionBox.Show({
						Title: "Un-Staff User",
						Options: [
							{
								Logo: "user-times",
								Title: "Continue",
								Info: "Update User Details and Un-Staff User",
								Function: function (selUserID) {
									Users.Manage.PerformSave(selUserID);
								},
								Parameter: selUserID
							},
							{
								Logo: "times",
								Title: "Cancel",
								Info: "Terminate Operation",
								Function: function () {
									MessageBox.Show("Operation Canceled");
								}
							}
						]
					})
				} else {
					Users.Manage.PerformSave(selUserID);
				}

			}
		}//Users.manage.SaveReal
		//Users.Manage.PerformSave
		, PerformSave: function (selid) {
			var ULogName = _('userLognametb').TextContent();
			var UName = _('usernametb').TextContent();
			/*var UStaffID = _('ustaffid').TextContent();
			var UStaffUnit = _('ustaffunit').TextContent();*/
			var UStaffSt = _("ustaffst").GetStatus();
			var Upassp = _('userpasspd').GetPadFile();
			//if a new user and new selected passport not found
			if (selid == 0 && Upassp == null) { MessageBox.Show("#Invalid Passport: Select a Valid Passport"); return }
			var UpassPstr = "";
			if (Upassp) {
				UpassPstr = "&" + Upassp.PostData;
			}
			var Data = "ULogName=" + rawescape(ULogName) + "&UName=" + rawescape(UName) + "&UID=" + selid + "&UStaffSt=" + UStaffSt + UpassPstr;
			Users.Manage.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Users/upduser.php",
				PostData: Data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Users").ProgressGet(0).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					var resarr = res.split("_");
					if (resarr.length == 3) {
						res = resarr[0];
						var UID = resarr[1].ToNumber();
						var newStaffSt = resarr[2];
						_('CurrStaffSt').value = newStaffSt;
						//check if updated user is current user
						var userdet = Login.User();
						if (userdet) {
							//s	alert(userdet);
							var curUserID = userdet[0].ToNumber();
							if (UID == curUserID) {
								//set the user Images

								var newimgsrc = _("userpasspd_image").src
								_("All_userloginboximg").src = newimgsrc;
								_('userloginimgsm').src = newimgsrc;
							}
						}

					}
					var userlist = _('usermag');
					if (userlist != null) {
						userlist.ReLoad();
					}

					Tabs.Tab("Users").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
				},
				OnAbort: function () {
					Tabs.Tab("Users").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');

				},
				OnError: function (res) {
					//Tabs.Tab("Users").ProgressGet(0).ProgressTo(100);
					Tabs.Tab("Users").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("Server Error: " + res);
				}
			});
		}//Users.Manage.performSave
		//Users.Manage.Delete
		, Delete: function () {
			if (Tabs.Tab("Users").ProgressGet(0).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user and validate it
			var selobj = _('usermag').SelectedObject(true);
			if (selobj == null) { MessageBox.Show("#Selected User Identification Failed"); return; }
			var selUserID = selobj.Data("id").Trim();
			if (selUserID == "") { MessageBox.Show("#Selected User Identification Failed"); return; }
			if (Login.User()[0] == selUserID) { MessageBox.Show("#Invalid Operation, Main User cannot be Deleted"); return; }

			OptionBox.Show({
				Title: "Delete User",
				Options: [{
					Logo: "trash",
					Title: "Delete User",
					Info: "Delete the Selected User Completely",
					Function: function (selUserID) {
						Users.Manage.PerformDelete(selUserID);
					},
					Parameter: selUserID
				},
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Abort the Delete Operation",
					Function: function () {
						MessageBox.Show("Delete Operation Canceled");
					},
					//Parameter:selectedRegNo
				}]

			});
		}//Users.Manage.delete
		//Users.manage.PerformDelete
		, PerformDelete: function (UserID) {
			//package data and send to server script 
			Users.Manage.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Users/deluser.php",
				PostData: "UID=" + escape(UserID) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Users").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					var fstr = res.Trim().substr(0, 1);
					if (fstr == "*") {
						Users.Manage.Clear();
						_('usermag').ReLoad();
						Tabs.Tab("Users").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					} else {
						Tabs.Tab("Users").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					}
					//	MessageBox.Show(res);
				},
				OnAbort: function (res) {

					Tabs.Tab("Users").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					Tabs.Tab("Users").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Server Error: ' + res.Replace('"', '\"') + '");');
				}
			})
		}//Users.Manage.PerformDelete
		//Users.Manage.Print
		, Print: function () {
			if (Tabs.Tab("Users").ProgressGet(0).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user and validate it
			var selUserID = "";
			var sbobj = _('usermag');
			if (sbobj != null) {
				var selobj = sbobj.SelectedObject(true);

				if (selobj != null) {
					selUserID = selobj.Data("id").Trim();
				}
			}


			if (selUserID == "") { //if no user selected
				OptionBox.Show({
					Title: "Print All Users",
					Options: [{
						Logo: "print",
						Title: "Print All Users",
						Info: "Print all Users Details and Privileges",
						Function: function () {
							Users.Manage.PerformPrint(0);
						},
						// Parameter:selUserID
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort the Print Operation",
						Function: function () {
							MessageBox.Show("Print Operation Canceled");
						},
						//Parameter:selectedRegNo
					}]

				});
			} else {
				//user selected
				Users.Manage.PerformPrint(selUserID.ToNumber());
			}

		}//Users.Manage.Print
		, Printer: new Printer() //printer object
		//Users.Manage.PerformPrint
		, PerformPrint: function (selUserID) {
			// Users.Manage.Printer.Preview("CPortal Users","../portal/Admin/Slip.php?UID="+selUserID+"&folder=Users",function(){})
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "UID=" + selUserID + "&folder=Users&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "cportal_user.pdf");
		}//Users.Manage.PerformPrint
		//Users.Manage.Copy
		, Copy: function () {
			var selUserID = "";
			var sbobj = _('usermag');
			if (sbobj != null) {
				var selobj = _('usermag').SelectedObject(true);
				if (selobj != null) {
					selUserID = selobj.Data("id").Trim();
				}
			}
			if (selUserID != "") {
				ClipBoard.Copy(selUserID, "User");
				MessageBox.Show("*User Copied");
			} else {
				MessageBox.Show("No User Selected");
			}
		}//Users.Manage.Copy
		, Paste: function () {
			var copiedUser = ClipBoard.Paste("User");
			//alert(document.cookie);

			if (copiedUser.Trim() != "") {
				var txt = _("usermagsearchtxt").SetText(copiedUser);
				var obj = window["obj_usermag"];
				//alert(obj);
				if (obj) {
					obj.ReSearch(function () {
						var items = _("class_usermag");
						var items = IsArray(items) ? items[0] : items;
						if (items) {
							items.click();
						}
					});
				}

			} else {
				MessageBox.Show("No Copied User Found")
			}
		}//Users.mange.Paste
	}//Users.Manage
	//Users.Priv
	, Priv: {
		//Priv Ajax
		Ajax: new Ajax(),
		//Users.Priv.Load
		Load: function (obj) {
			var userid = "";
			if (obj) {
				userid = obj.Data("id"); //get the user id from the data-id attribute set in the SearchBox load script
			}
			if (userid == "") { MessageBox.Show("Selected User Valiadtion Failed"); return; }
			//send data to server
			Users.Priv.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Users/loadpriv.php",
				PostData: "UID=" + escape(userid) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//clear
					res = res.Trim();
					var cc = Users.Priv.Clear(true);
					var us = res.substr(0, 1);
					if (us == "_") { //if priv found
						var privs = res.substr(1);
						//alert(privs);
						var privarr = privs.split(":");
						if (privarr.length > 0) {
							//var priv = privarr[]
							for (var s = 0; s < privarr.length; s++) {
								var priv = privarr[s];
								var swobj = _("sw_" + priv);
								if (swobj) {
									swobj.SwitchOn();
								}
							}
						}
						_("selprivs").value = privs; //set hidden element
						Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("*User Privileges Loaded");');
						_('userprivhome').Hide();
						_('userPrivFrm').Show();
						Tabs.HideSideBar("Users", 1);
						//MessageBox.Show("");
					} else {
						Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
						//MessageBox.Show(res);
					}
				},
				OnAbort: function () {

					Tabs.Tab("Users").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res.Replace('"', '\"') + '");');
				}
			})
			// alert(userid);
		}//Users.Priv.Load
		//Users.Priv.Clear
		, Clear: function (obj) {

			var selprivsobj = _('selprivs');
			if (selprivsobj != null) {
				if (selprivsobj.value.Trim() == "") {
					//MessageBox.Show("No Selected Privilege Found");
					return;
				}
				var privarr = selprivsobj.value.split(":");
				if (privarr.length > 0) {
					for (var d = 0; d < privarr.length; d++) {
						selpriv = privarr[d];
						//get the switch object
						var swobj = _("sw_" + selpriv);
						if (swobj) {
							swobj.SwitchOff();
						}
					}
				}
				selprivsobj.value = "";
				if (typeof obj == _UND) {
					_("userpriv").Deselect();
				}
				Tabs.HideSideBar("Users", 1);
				return true;
			} else {
				MessageBox.Show("#Selected Privileges Identification Failed");
			}
		}//Users.Priv.Clear
		//Users.Priv.SwitchChange
		, SwitchChange: function (obj, st) {

			if (st == 0) { //if off
				Users.Priv.RemovePriv(obj.id);
			} else {
				Users.Priv.AddPriv(obj.id);
			}
			//alert(_('selprivs').value);
		},
		RemovePriv: function (privid) {
			prividr = privid.split("_")[1];
			var selobj = _('selprivs');
			if (selobj) {
				if (selobj.value.Trim() == "") {
					return;
				} else {
					var selvalarr = selobj.value.split(":");
					var nwselarr = new Array();
					if (selvalarr.length > 0) {
						for (var s = 0; s < selvalarr.length; s++) {
							var cpriv = selvalarr[s];
							if (prividr != cpriv) {
								nwselarr[nwselarr.length] = cpriv;
							}
						}
					}
					selobj.value = nwselarr.join(":");
				}

			} else {
				MessageBox.Show("Page error: Operation Aborted");
				_(privid).Undo();
			}
		},
		AddPriv: function (privid) {
			var selprivs = "";
			prividr = privid.split("_")[1];
			var selobj = _('selprivs');
			// alert(selobj);
			if (selobj) {
				if (selobj.value.Trim() == "") {
					selobj.value = prividr;
				} else {
					selobj.value += ":" + prividr;
				}

			} else {
				MessageBox.Show("Page error: Operation Aborted");
				_(privid).Undo();
			}

		}
		//Users.Priv.Save
		, Save: function () {
			_('userPrivFrm').submit();
		}
		//Users.Priv.SaveReal
		, SaveReal: function () {
			var selUserID = "";
			var sbobj = _('userpriv');
			if (sbobj != null) {
				var selobj = _('userpriv').SelectedObject(true);
				if (selobj != null) {
					selUserID = selobj.Data("id").Trim();
				}
			}
			if (selUserID.Trim() == "") { MessageBox.Show("Invalid User selected"); return; }
			var selprivs = _("selprivs").value;
			//package data, UserID and Privs to server script
			Users.Priv.Ajax.Post({
				Action: configdata['Core'] + "cportal/Pages/Scripts/Users/savepriv.php",
				PostData: "UID=" + selUserID + "&Priv=" + selprivs + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					MessageBox.Show(res);
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
				},
				OnAbort: function () {

					Tabs.Tab("Users").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res.Replace('"', '\"') + '");');
				}
			})
		}
		//Users.Priv.Print
		, Print: function () {
			if (Tabs.Tab("Users").ProgressGet(1).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user and validate it
			var selUserID = "";
			var sbobj = _('userpriv');
			if (sbobj != null) {
				var selobj = _('userpriv').SelectedObject(true);

				if (selobj != null) {
					selUserID = selobj.Data("id").Trim();
				}
			}


			if (selUserID == "") { //if no user selected
				OptionBox.Show({
					Title: "Print All Users",
					Options: [{
						Logo: "print",
						Title: "Print All Users",
						Info: "Print all Users Details and Privileges",
						Function: function () {
							Users.Priv.PerformPrint(0);
						},
						// Parameter:selUserID
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort the Print Operation",
						Function: function () {
							MessageBox.Show("Print Operation Canceled");
						},
						//Parameter:selectedRegNo
					}]

				});
			} else {
				//user selected
				Users.Priv.PerformPrint(selUserID.ToNumber());
			}

		}//Users.Manage.Print
		, Printer: new Printer() //printer object
		//Users.Manage.PerformPrint
		, PerformPrint: function (selUserID) {
			// Users.Priv.Printer.Preview("CPortal Users","../portal/Admin/Slip.php?UID="+selUserID+"&folder=Users",function(){})
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "UID=" + selUserID + "&folder=Users&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "cportal_user.pdf");
		}//Users.Manage.PerformPrint
		//Users.Priv.Delete
		, Delete: function () {
			if (Tabs.Tab("Users").ProgressGet(1).ProgressState() != 0) { MessageBox.Show("System Busy, Try Again Later"); return }
			//get selected user and validate it
			var selobj = _('userpriv').SelectedObject(true);
			if (selobj == null) { MessageBox.Show("#Selected User Identification Failed"); return; }
			var selUserID = selobj.Data("id").Trim();
			if (selUserID == "") { MessageBox.Show("#Selected User Identification Failed"); return; }
			OptionBox.Show({
				Title: "Delete User",
				Options: [{
					Logo: "trash",
					Title: "Delete User",
					Info: "Delete the Selected User Completely",
					Function: function (selUserID) {
						Users.Priv.PerformDelete(selUserID);
					},
					Parameter: selUserID
				},
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Abort the Delete Operation",
					Function: function () {
						MessageBox.Show("Delete Operation Canceled");
					},
					//Parameter:selectedRegNo
				}]

			});
		},
		//Users.Priv.PerformDelete
		PerformDelete: function (UserID) {
			//package data and send to server script 
			Users.Priv.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Users/deluser.php",
				PostData: "UID=" + escape(UserID)
					+ "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					var fstr = res.Trim().substr(0, 1);
					if (fstr == "*") {
						Users.Priv.Clear();
						_('userpriv').ReLoad();
						Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					} else {
						Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					}
					//MessageBox.Show(res);
				},
				OnAbort: function (res) {

					Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//	MessageBox.Show("" + res);
					Tabs.Tab("Users").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("#Server Error: ' + res.Replace('"', '\"') + '");');
				}
			})
		}
		//Users.Priv.Copy
		, Copy: function () {
			var selUserID = "";
			var sbobj = _('userpriv');
			if (sbobj != null) {
				var selobj = _('userpriv').SelectedObject(true);
				if (selobj != null) {
					selUserID = selobj.Data("id").Trim();
				}
			}
			if (selUserID != "") {
				ClipBoard.Copy(selUserID, "User");
				MessageBox.Show("*User Copied");
			} else {
				MessageBox.Show("No User Selected");
			}
		}//Users.Priv.Copy
		, Paste: function () {
			var copiedUser = ClipBoard.Paste("User");
			//alert(document.cookie);

			if (copiedUser.Trim() != "") {
				var txt = _("userprivsearchtxt").SetText(copiedUser);
				var obj = window["obj_userpriv"];
				//alert(obj);
				if (obj) {
					obj.ReSearch(function () {
						var items = _("class_userpriv");
						var items = IsArray(items) ? items[0] : items;
						if (items) {
							items.click();
						}
					});
				}

			} else {
				MessageBox.Show("No Copied User Found")
			}
		}//Users.Priv.Paste
	}//Users.Priv
}//Users Object

//Exams Object
var Exams = {

	//Exams.ResultUpload
	ResultUpload: {
		GenLoader: new GenLoading({ StudyID: "rstudstudy", FacID: "rstudfac", DeptID: "rstuddept", ProgID: "rstudprog", LevelID: "rstudlvl", SemID: "semest", ClassID: "rstclassid" }),
		SaveAjax: new Ajax(),
		IsLoaded: () => {
			var loadedparamobj = _('dispdetid');
			if (loadedparamobj == null) { //if loaded params found
				return false;
			}
			return true;
		},
		Export: function () {
			/* var coursesdet = _('lcoursesdet');
		  if(coursesdet == null || coursesdet.Text().Trim() == ""){
			MessageBox.Show("#No Semester Courses Details Found");
			return;
		  }
		  if(!SpreadSheet.ColumnDataExist("sprstcourses","CCode") && !SpreadSheet.ColumnDataExist("sprstcourses","CTitle") && !SpreadSheet.ColumnDataExist("sprstcourses","CH")){
			MessageBox.Show("#Empty Result Set");
			return;
		 }
			//export code sprstcourses */
			//tableToExcel(_('sprstupload').outerHTML,'Result Sheet');
			/* var copy = _('sprstupload').cloneNode(true);
			copy.rows[0].cells[0].innerHTML = "S/N";
			copy.rows[0].cells[copy.rows[0].cells.length - 1].innerHTML = "";
			//copy.rows[0].cells[copy.rows[0].cells.length - 1].rowSpan = 2;
			//get the ast column
			copy.deleteRow(-1);

			tableToExcel(copy.outerHTML, 'Result Sheet'); */
			//alert(copy.outerHTML);
			//var loadedparamobj = _('dispdetid');
			/* if (!Exams.ResultUpload.IsLoaded()) { //if loaded params found
	   MessageBox.Show("#No Result Loaded"); return;
			} */
			var loadedparamobj = _('dispdetid');
			if (loadedparamobj == null) { //if loaded params found
				MessageBox.Show("#No Result Loaded"); return;
			}



			OptionBox.Show({
				Title: 'EXPORT RESULT',
				Logo: "files-o",
				TitleHTML: OptionBox.TextBox({ id: 'exportpassw', logo: 'lock', title: 'Lock-File Password (*.xlsx, *.xls)', type: 'password' }),
				Options: [
					{
						Logo: "file-excel-o",
						Title: "Excel Workbook",
						Info: "Microsoft Office Excel Workbook (*.xlsx)",
						Function: function (param) {
							var pasw = _('exportpassw').TextContent();
							Exams.ResultUpload.ExportReal(param, 0, pasw);
						},
						Parameter: loadedparamobj.value
					},
					{
						Logo: "file-text-o",
						Title: "Excel 97-2003 Workbook",
						Info: "Microsoft Office Excel 97-2003 Workbook (*.xls)",
						Function: function (param) {
							var pasw = _('exportpassw').TextContent();
							Exams.ResultUpload.ExportReal(param, 1, pasw);
						},
						Parameter: loadedparamobj.value
					},
					{
						Logo: "file-o",
						Title: "CSV",
						Info: "Comma Seperated Value (*.csv)",
						Function: function (param) {
							var pasw = _('exportpassw').TextContent();
							Exams.ResultUpload.ExportReal(param, 2, pasw);
						},
						Parameter: loadedparamobj.value
					},
					{
						Logo: "file-code-o",
						Title: "JSON",
						Info: "JSON File (*.json)",
						Function: function (param) {
							Exams.ResultUpload.ExportReal(param, 3, "");
						},
						Parameter: loadedparamobj.value
					},
					{
						Logo: "window-restore",
						Title: "Web Page",
						Info: "HTML Web Page (*.html)",
						Function: function (param) {
							Exams.ResultUpload.ExportReal(param, 4, '');
						},
						Parameter: loadedparamobj.value
					}/* ,
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Terminate Result Upload / Update Operation",
						Function: function () {
							MessageBox.Show("#Operation Terminated");
						} 
					}*/
				]
			});
		},
		AddElem: function (name, value) {
			var inputelem = document.createElement('input');
			inputelem.type = "hidden";
			inputelem.value = value;
			inputelem.name = name;
			return inputelem;
		},
		ExportReal: function (param, type, pasw) {
			var rstScoreStruc = _('rstScoreStruc');
			var rstScoreStrucMax = _('rstScoreStrucMax');
			if (rstScoreStruc == null) {
				MessageBox.Show("#SCORING STRUCTURE NOT FOUND");
				return;
			}

			rstScoreStruc = rstScoreStruc.textContent;
			var form = document.createElement('form');
			form.action = configdata.Core + "cportal/Pages/Scripts/Exams/Exportrst.php";
			form.name = "newform";

			form.method = "post";
			//display display columns 
			var discol = _('sprstupload').GetDisplayColumns();
			//alert(discol);
			//console.log(param);
			//sheet data string 
			var shdatastr = _('sprstupload_datastring').value;
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('updatetype', type));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('discol', discol));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('sdatastr', shdatastr));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('rstparam', param));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('pasw', pasw));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('rstScoreStruc', encodeURIComponent(rstScoreStruc)));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('rstScoreStrucMax', encodeURIComponent(rstScoreStrucMax)));
			form.insertAdjacentElement('afterbegin', Exams.ResultUpload.AddElem('SubDir', encodeURIComponent(configdata.SubDir)));
			// form.target = "_blank";
			document.body.insertAdjacentElement('beforeend', form);
			form.submit();

			/* Exams.ResultUpload.SaveAjax.Post(
				{
					Action: "Pages/Scripts/Exams/Exportrst.php",
					PostData: "",
					OnProgress: function (delta) {
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if(!Login.Authenticate(res))return;
						//alert(res);
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100);
						//console.log(res);
						MessageBox.Show(res);
						//alert(res);
					},
					OnAbort: function (res) {
						MessageBox.Show("#Operation Aborted");
					},
					OnError: function (res) {
						MessageBox.Show("#Server Error: " + res);
					}
				}
			); */
		},
		lastStrictLevel: 1,
		Save: function () {
			//console.log('Save');
			//get the loaded params
			var loadedparamobj = _('dispdetid');
			if (loadedparamobj != null) { //if loaded params found
				// alert(loadedparamobj.value);
				//check if data exist var shdatastr = _('sprstupload_datastring').value;
				var rstScoreStrucID = Exams.ResultUpload.GetScoreStructureID();
				if (rstScoreStrucID.length < 1) {
					MessageBox.Show("#INVALID RESULT SHEET");
					return;
				}
				var empty = true;
				for (var df = 0; df < rstScoreStrucID.length; df++) {
					if (SpreadSheet.ColumnDataExist("sprstupload", rstScoreStrucID[df])) {
						empty = false;
						break;
					}
				}
				//if (!SpreadSheet.ColumnDataExist("sprstupload", "CA") && !SpreadSheet.ColumnDataExist("sprstupload", "Exm")) {
				if (empty) {
					MessageBox.Show("#Empty Result Set");
				} else {
					//check if result already approved
					var approbj = _("dispdetappr");
					if (approbj != null) {
						if (approbj.value == "1") {
							MessageBox.Show("INVALID OPERATION: RESULT ALREADY APPROVED");
							return;
						}
					}
					var selectRstInfo = DropDownLine.Selected('ruppreset');
					var RstInfoID = selectRstInfo.Value;
					var RstInfoTxt = selectRstInfo.Text;
					//var fields = ["sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest"];
					var detarr = _('dispdet').value.ToDataArray();
					var titlehtml = '<table class="tbl rwb greyShadow" style="width:95%;font-size:0.8em;margin:auto;margin-bottom:15px" bordercolor="#CCCCCC" border="1"><tr class=""  ><th style="text-align:left">Session</th><td>' + detarr['sestb'] + '</td></tr><tr><th style="text-align:left">Programme</th><td>' + detarr['rstudprog'] + '</td></tr><tr><th style="text-align:left">Level</th><td>' + detarr['rstudlvl'] + ' (' + detarr['classid'] + ') ' + '</td></tr><tr><th style="text-align:left">' + detarr['semlabel'] + '</th><td>' + detarr['semest'] + '</td></tr><tr><th style="text-align:left">Course</th><td>' + detarr['rcourse'] + '</td></tr><tr><th style="text-align:left">Use Setting</th><td>' + RstInfoTxt + '</td></tr></table>' + OptionBox.Switcher({ id: 'strictlvl', title: 'STRICT LEVEL MODE', info: 'Save Result with the selected level for all Student', state: Exams.ResultUpload.lastStrictLevel });
					// var tit = "Save Result <hr /> Session: <strong>"+detarr['sestb']+"</strong><br />Programme: <strong>"+detarr['rstudprog']+"</strong><br />Level: <strong>"+detarr['rstudlvl']+"</strong><br />Semester: <strong>"+detarr['semest']+"</strong><br />Course: <strong>"+detarr['rcourse']+"</strong>";
					OptionBox.Show({
						Title: 'SAVE RESULT',
						TitleHTML: titlehtml,
						Options: [
							{
								Logo: "history",
								Title: "Normal Save",
								Info: "Save Result, using Course, Result and School Settings assign to the Result (IF Exist)",
								Function: function (param) {
									var lvlstrictmode = _('strictlvl').GetStatus();
									Exams.ResultUpload.SaveResultReal(param[0], 0, lvlstrictmode, param[1]);
								},
								Parameter: [loadedparamobj.value, RstInfoID]
							},
							{
								Logo: "calendar",
								Title: "Update Save",
								Info: "Save Result, using the current Course, Result and School Settings <b>(" + RstInfoTxt + ")</b>",
								Function: function (param) {
									var lvlstrictmode = _('strictlvl').GetStatus();
									Exams.ResultUpload.SaveResultReal(param[0], 1, lvlstrictmode, param[1]);
								},
								Parameter: [loadedparamobj.value, RstInfoID]
							},
							{
								Logo: "times",
								Title: "Cancel",
								Info: "Terminate Result Upload / Update Operation",
								Function: function () {
									MessageBox.Show("#Operation Terminated");
								}
							}
						]
					});
				}
			} else {
				MessageBox.Show("#No Result Loaded");
			}
		},
		SaveResultReal: function (param, updatetype, strictmode, RstInfoID) {
			updatetype = typeof updatetype == _UND ? 0 : updatetype; //1 - will update using current course, result and school settings, 0 - update using the setting as at when result first uploaded
			strictmode = typeof strictmode == _UND ? 1 : strictmode;
			//perform the save operation
			//display display columns 
			var discol = _('sprstupload').GetDisplayColumns();
			//sheet data string 
			var shdatastr = _('sprstupload_datastring').value;
			var rstScoreStruc = Exams.ResultUpload.GetScoreStructure();
			var rstScoreStrucID = Exams.ResultUpload.GetScoreStructureID();
			var rstScoreStrucMax = Exams.ResultUpload.GetScoreStructureMax();
			if (typeof RstInfoID == _UND) {
				var selectRstInfo = DropDownLine.Selected('ruppreset');
				var RstInfoID = selectRstInfo.Value;
				//var RstInfoTxt = selectRstInfo.Text; 
			}

			//console.log(shdatastr);
			//compile  

			var pstdata = "discol=" + rawescape(discol) + "&sdatastr=" + rawescape(shdatastr) + "&rstparam=" + rawescape(param) + "&updatetype=" + updatetype + "&strictlvlmode=" + strictmode + "&rstScoreStruc=" + encodeURIComponent(JSON.stringify(rstScoreStruc)) + "&rstScoreStrucID=" + encodeURIComponent(JSON.stringify(rstScoreStrucID)) + "&rstScoreStrucMax=" + encodeURIComponent(JSON.stringify(rstScoreStrucMax)) + "&RstInfoID=" + RstInfoID;
			Exams.ResultUpload.SaveAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/RstSave.php",
					PostData: pstdata
						+ "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//alert(res);Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100);
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
						//console.log(res);
						//MessageBox.Show(res);
						//alert(res);
					},
					OnAbort: function (res) {
						//'MessageBox.Show("'+res.Replace('"','\"')+'");'
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Operation Aborted")');
					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Exams").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Server Error: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		},
		Ajax: new Ajax(),

		CellKeyPress: function (cel) {
			var cellidarr = cel.id.split("_");
			var rstScoreStruc = Exams.ResultUpload.GetScoreStructureID();
			var rstScoreStrucMax = Exams.ResultUpload.GetScoreStructureMax();

			if (rstScoreStruc.length < 1) return;
			var columID = cellidarr[3];
			//if (columID == "CA" || columID == "Exm") {
			//console.log(rstScoreStruc.indexOf(columID));
			if (rstScoreStruc.indexOf(columID) > -1) {
				var scrobj = [];
				var rownum = cellidarr[2].ToNumber();
				/* var caobj = _(cellidarr[0] + "_rw_" + rownum + "_CA_edit");
				var exmobj = _(cellidarr[0] + "_rw_" + rownum + "_Exm_edit"); */
				//get all the score
				var tot = 0;
				for (var sc = 0; sc < rstScoreStruc.length; sc++) {
					scrobj[sc] = _(cellidarr[0] + "_rw_" + rownum + "_" + rstScoreStruc[sc] + "_edit");
					var uscr = scrobj[sc].textContent.ToNumber();
					if (uscr > rstScoreStrucMax[sc]) {
						uscr = rstScoreStrucMax[sc].ToNumber();
						scrobj[sc].style.color = "red";
						scrobj[sc].setAttribute('data-tooltip', "Maximum: " + rstScoreStrucMax[sc]);
						scrobj[sc].classList.add('tooltip');
						//data-tooltip
					} else {
						scrobj[sc].style.color = "";
						scrobj[sc].classList.remove('tooltip');
					}
					tot += uscr;
				}
				var totobj = _(cellidarr[0] + "_rw_" + rownum + "_Tot_edit");
				var grdobj = _(cellidarr[0] + "_rw_" + rownum + "_Grd_edit");
				/* if(caobj.textContent.length > 2 || exmobj.textContent.length > 2){
						 if(columID == "CA"){
						   curobjc = caobj;
						   nextobj = exmobj;
						 }else{
							curobjc = exmobj;
						   nextobj = _(cellidarr[0]+"_rw_"+(rownum+1)+"_CA_edit");
						 }
						 var keychar = curobjc.textContent.substr(curobjc.textContent.length - 1,1);
						curobjc.textContent = curobjc.textContent.substr(0,curobjc.textContent.length - 1);
						var dd = SpreadSheet.UpdateDataString(curobjc);
						//exmobj.focus();
						if(nextobj != null){
						nextobj.textContent = keychar;
						nextobj.PlaceCursorAt();
						var ss = SpreadSheet.UpdateDataString(nextobj);
						}
						 
						//setTimeout(exmobj.setSelectionRange(2,2),1);
						//return; 
					 }*/
				//alert(exmobj.textContent);
				//var tot = caobj.textContent.ToNumber() + exmobj.textContent.ToNumber();
				totobj.textContent = tot;
				totobj.Data("value", tot);
				var struc = _('gradeStruc')
				if (struc != null) {
					var stucval = _('gradeStruc').textContent;
					var grd = DataString.RangeGet(stucval, tot);
					//grd = grd.split("|");
					grd = JSON.parse(grd);
					// console.log(grd);
					grdobj.textContent = grd['Grade'];
				} else {
					grdobj.textContent = "-";
				}
				grdobj.Data("value", grdobj.textContent);
				//Update DataString

			}
		},
		OnBlur: function (cell) {
			var cellidarr = cell.id.split("_");
			var rstScoreStruc = Exams.ResultUpload.GetScoreStructureID();
			var rstScoreStrucMax = Exams.ResultUpload.GetScoreStructureMax();
			var columID = cellidarr[3];
			var colind = rstScoreStruc.indexOf(columID);
			if (colind > -1) {
				var rownum = cellidarr[2];
				scrobj = _(cellidarr[0] + "_rw_" + rownum + "_" + rstScoreStruc[colind] + "_edit");
				var uscr = scrobj.textContent.ToNumber();
				if (uscr > rstScoreStrucMax[colind]) {
					scrobj.textContent = rstScoreStrucMax[colind];
					scrobj.style.color = "";
					scrobj.classList.remove('tooltip');
				}
				SpreadSheet.UpdateDataString(_(cellidarr[0] + "_rw_" + rownum + "_Grd_edit"));
				SpreadSheet.UpdateDataString(_(cellidarr[0] + "_rw_" + rownum + "_Tot_edit"));
			}
			//alert(cell.id);
			/*
			 //spdatastrObj.value = DataString.Set(datastr,rownum +"_"+ colnum,newval);
						 SpreadSheet.UpdateDataString(_(cellidarr[0]+"_rw_"+rownum+"_Grd_edit"));
						  SpreadSheet.UpdateDataString(_(cellidarr[0]+"_rw_"+rownum+"_CA_edit"));
			*/
		},
		LoadedScoreStructure: [],
		LoadedScoreStructureID: [],
		LoadedScoreStructureMax: [],
		GetScoreStructure: function (update) {
			update = update || false;
			//check if exist in cache
			if (Exams.ResultUpload.LoadedScoreStructure.length > 0 && update == false) {
				return Exams.ResultUpload.LoadedScoreStructure;
			}
			var rstScoreStruc = _('rstScoreStruc');
			if (rstScoreStruc == null) {
				Exams.ResultUpload.LoadedScoreStructure = [];
				return [];
			}

			rstScoreStruc = rstScoreStruc.textContent;
			//alert(rstScoreStruc);
			Exams.ResultUpload.LoadedScoreStructure = JSON.parse(rstScoreStruc);
			Exams.ResultUpload.LoadedScoreStructure = Exams.ResultUpload.LoadedScoreStructure == null ? [] : Exams.ResultUpload.LoadedScoreStructure;
			return Exams.ResultUpload.LoadedScoreStructure;

		},
		GetScoreStructureID: function (update) {
			update = update || false;
			//check if exist in cache
			if (Exams.ResultUpload.LoadedScoreStructureID.length > 0 && update == false) {
				return Exams.ResultUpload.LoadedScoreStructureID;
			}
			var rstScoreStrucID = _('rstScoreStrucID');
			if (rstScoreStrucID == null) {
				Exams.ResultUpload.LoadedScoreStructureID = [];
				return [];
			}

			rstScoreStrucID = rstScoreStrucID.textContent;
			//alert(rstScoreStruc);
			Exams.ResultUpload.LoadedScoreStructureID = JSON.parse(rstScoreStrucID);
			Exams.ResultUpload.LoadedScoreStructureID = Exams.ResultUpload.LoadedScoreStructureID == null ? [] : Exams.ResultUpload.LoadedScoreStructureID;
			return Exams.ResultUpload.LoadedScoreStructureID;

		},
		GetScoreStructureMax: function (update) {
			update = update || false;
			//check if exist in cache
			if (Exams.ResultUpload.LoadedScoreStructureMax.length > 0 && update == false) {
				return Exams.ResultUpload.LoadedScoreStructureMax;
			}
			var rstScoreStrucMax = _('rstScoreStrucMax');
			if (rstScoreStrucMax == null) {
				Exams.ResultUpload.LoadedScoreStructureMax = [];
				return [];
			}

			rstScoreStrucMax = rstScoreStrucMax.textContent;
			//alert(rstScoreStruc);
			Exams.ResultUpload.LoadedScoreStructureMax = JSON.parse(rstScoreStrucMax);
			Exams.ResultUpload.LoadedScoreStructureMax = Exams.ResultUpload.LoadedScoreStructureMax == null ? [] : Exams.ResultUpload.LoadedScoreStructureMax;
			return Exams.ResultUpload.LoadedScoreStructureMax;

		},
		ChangeRstInfo: RstInfoID => {
			if (RstInfoID == '0') {
				//get the current selected RstInfoID - SaveResultReal
				var selectRstInfo = DropDownLine.Selected('ruppreset');
				var RstInfoID = selectRstInfo.Value;
				var RstInfoTxt = selectRstInfo.Text;
				//load the details
				OptionBox.Show({
					Title: RstInfoTxt,
					Logo: "cogs",
					TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Exams/resultupload_rstinfo.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&RstInfoID=" + RstInfoID },
					Options: [
						{
							Logo: "thumbs-up",
							Title: "Continue",
							Info: "",
							Function: function () {
								//Exams.ResultReport.SaveResultAttr(rstID);
							}
						}
					]

				});
			} else {
				Exams.ResultUpload.Reload(RstInfoID);
			}
		},
		Reload: RstInfoID => {
			//get the selected course
			var cid = _('courseids');

			if (cid == null) {
				return;
			}
			var cidv = cid.value;
			if (cidv.Trim() == "") return;
			var tbobj = _('coursetb_' + cidv + '_2');
			if (tbobj == null) return;
			var tdid = tbobj.value;
			tdidarr = tdid.split("_");
			trid = tdidarr[0] + "_" + tdidarr[1] + "_" + tdidarr[2];
			var trobj = _(trid);
			if (trobj == null) return;
			Exams.ResultUpload.Load(trobj, RstInfoID);
			/*  OptionBox.Show({
				 Title:"Reload Result Sheet",
				 TitleHTML:OptionBox.Note("Result Sheet Reload: Make sure all new entry are Saved"),
				 Logo:"list-alt",
				 Options:[
					 {
						 Title:"Continue",
						 Logo:"thumbs-up",
						 Info:"Continue Result Sheet Reload Operation",
						 Function:param=>{
					   	
						   Exams.ResultUpload.Load(param[0],param[1]);
						 },
						 Parameter:[trobj,RstInfoID]
					 }
				 ]
			 }); */

		},
		Load: function (obj, RstInfoID, loadType) {
			if (typeof loadType == "undefined") {
				OptionBox.Show({
					Title: "Load Result",
					TitleHTML: OptionBox.Note("Filter Result by Main or Carryover Student"),
					Logo: "filter",
					Options: [
						{
							Title: "Main and Carryover Student",
							Logo: "thumbs-up",
							Info: "Load Result of Both Main and Carryover Student",
							Function: param => {

								Exams.ResultUpload.Load(param[0], param[1], param[2]);
							},
							Parameter: [obj, RstInfoID, 1]
						},
						{
							Title: "Main Student Only",
							Logo: "thumbs-up",
							Info: "Load result of Main Student Only",
							Function: param => {

								Exams.ResultUpload.Load(param[0], param[1], param[2]);
							},
							Parameter: [obj, RstInfoID, 2]
						},
						{
							Title: "Carryover Student Only",
							Logo: "thumbs-up",
							Info: "Load result of Carryover Student Only",
							Function: param => {

								Exams.ResultUpload.Load(param[0], param[1], param[2]);
							},
							Parameter: [obj, RstInfoID, 3]
						}
					]
				});
				return
			}
			//alert('loading');
			//console.log(obj);
			//return;
			var RstInfoText = "";
			//check if there is a result setting
			if (typeof RstInfoID == "undefined") {
				var RstInfo = DropDownLine.Selected('ruppreset');
				RstInfoID = RstInfo.Value;
				RstInfoText = RstInfo.Text;

				//DropDownLine.SetTheme('ruppreset','ok');
				//alert(RstInfoID);
				if (RstInfoID == '-1') {
					MessageBox.Show("#No Result Settings Found"); return
				}
			}




			var sest = _('sestb');

			if (_('rstudstudy') != null) {
				var reqired = _("textBx & objgrpelemrstup & req err");
				if (reqired != null) {
					MessageBox.Show("#All field are Required");
					return false;
				}
			} else {
				var reqired = _("sestb & req err");
				if (reqired != null) {
					MessageBox.Show("#Select Result Session");
					return false;
				}
			}



			//get all selected input
			/*
			  var fields = ["sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest"];
			 var datstr = "";
			 for(var dd=0; dd<fields.length; dd++){
				 var fobj = _(fields[dd]);
				 datstr += fields[dd] + "=" + fobj.ValueContent() + ":" + rawescape(fobj.TextDisplay()) +  "&"
			 }*/
			// alert(_(obj.id + "_1").textContent);
			//var filt = _('filtertb').ValueContent();
			var trid = typeof obj == "string" ? obj : obj.Data("id");
			//alert(trid);
			var coursedetobj = _(trid + "_det");

			var classid = _('rstclassid');
			var classidr = "";
			if (classid != null) {
				classidr = "&classid=" + classid.ValueContent() + ":" + rawescape(classid.TextDisplay());
			} else {
				if (typeof obj == "string") {
					MessageBox.Show("#ERROR: CLASS IDENTIFICATION FAILED"); return;
				}
				var clid = Number(obj.Data("class-id"));
				if (clid < 1) { MessageBox.Show("#ERROR: CLASS IDENTIFICATION FAILED"); return; }
				classidr = "&classid=" + clid + ":" + rawescape(obj.Data("class-name"));
			}
			if (coursedetobj == null) { MessageBox.Show("#ERROR: NO COURSE DETAILS FOUND"); return; }
			//check if it is a reload operation

			//	_("rstcontdiv").FadeOut(300);

			datstr = coursedetobj.value + classidr + "&sestb=" + sest.ValueContent() + ":" + rawescape(sest.TextDisplay()) + "&RstInfoID=" + RstInfoID + ":" + rawescape(RstInfoText);//+ "&filtertb=" + filt.ValueContent() + ":" + rawescape(filt.TextDisplay());// added the filter data to post string 22-5-17 #1

			var totcol = obj.cells.length;
			datstr += "&rcourse=" + trid + ":" + rawescape(_(obj.id + "_" + (totcol - 1)).textContent + " (" + _(obj.id + "_" + (totcol - 2)).textContent + ")");
			var cid = _('courseids');

			if (cid != null && cid.value == trid) {
				//alert('Reload');
				var shdatastr = _('sprstupload_datastring').value;
				var discol = _('sprstupload').GetDisplayColumns();
				var rstScoreStruc = Exams.ResultUpload.GetScoreStructure();
				var rstScoreStrucID = Exams.ResultUpload.GetScoreStructureID();
				var rstScoreStrucMax = Exams.ResultUpload.GetScoreStructureMax();
				datstr += "&sdatastr=" + rawescape(shdatastr) + "&scl=" + rstScoreStruc.length + "&rstScoreStruc=" + encodeURIComponent(JSON.stringify(rstScoreStruc)) + "&rstScoreStrucID=" + encodeURIComponent(JSON.stringify(rstScoreStrucID)) + "&rstScoreStrucMax=" + encodeURIComponent(JSON.stringify(rstScoreStrucMax)) + "&discol=" + rawescape(discol);


				/* if(rstScoreStruc.length < 1){
				   MessageBox.Show("#SCORING STRUCTURE NOT FOUND");
					return;
				} */
			}
			_('rstuplhome').Hide();
			_('rstbxdiv').Show();
			_("rstcontdiv").innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load and Proccess Results</small>");
			_('rstrpagrp_title').innerHTML = Icon("check-square-o") + " Result Sheet";

			console.log(datstr);
			// Tabs.Tab("Exams").ProgressGet(0).ProgressTo(90);
			// return;
			Exams.ResultUpload.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadstudregrst.php",
				PostData: datstr + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&LoadType=" + loadType,
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_("rstcontdiv").innerHTML = res;
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100);
					var det = _("dispdet");
					if (det != null) {
						totrw = "";
						if (_('sprstupload') != null) {
							var totrw = _('sprstupload').rows.length - 2;
						}
						// alert(det.value);
						var dtarr = det.value.ToDataArray();
						// alert(dtarr['rcourse']);
						var loadtype = _('rstType').textContent.ToNumber();
						var loadTypeTxt = "";

						loadTypeTxt = (loadtype == 1) ? "" : ((loadtype == 2) ? " (Main)" : " (Carryover)");


						_('rstrpagrp_title').innerHTML = Icon("check-square-o") + " Result Sheet - " + dtarr['rcourse'] + " - #" + totrw + loadTypeTxt;
					}
					//keep the loaded field in a global cache for optimzation purpose
					Exams.ResultUpload.GetScoreStructure(true);
					Exams.ResultUpload.GetScoreStructureID(true);
					Exams.ResultUpload.GetScoreStructureMax(true);
					Tabs.HideSideBar("Exams", 0);
					//_("loadcourses").Animate({CSSRule:"visibility:hidden;opacity:0",Time:200});
					//_("rstcontdiv").FadeIn(300);
				},
				OnAbort: function (res) {
					_("rstcontdiv").innerHTML = Markups.GroupBoxPlaceholder("ban", "Hoops !!! </br> <small>Operation Aborted</small>");
					//'MessageBox.Show("'+res.Replace('"','\"')+'");'

					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Operation Aborted","altColor");');
				},
				OnError: function (res) {
					_("rstcontdiv").innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!! </br> <small>" + res + "</small>", "danger-text");
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Server Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("#Error: " + res);
				}
			})

			//alert(datstr.TrimRight("&"));
		},
		LoadFac: function () { //function to load department textbox based on selected faculty
			//var facID = _("studfac").ValueContent();
			//if(facID == null)return;select * from fac_tb order by FacName
			//alert(facID);

			//alert(window.sessionStorage)
			//Tracer.Start("Chain Loading");

			var studstudy = _("rstudstudy").ValueContent();
			//Tracer.Tag("Study: "+studstudy);
			studstudy = (studstudy == null || studstudy.Trim() == "") ? 1 : studstudy;
			//Tracer.Tag("Onload of fac due to change of studyid = " + studstudy);
			TextBox.Load("rstudfac", "FacID", "FacName", "StudyID=" + studstudy, "fac_tb"); //Load:function(tb,key, val, cond, dbtb)
			//Exams.ResultUpload.LoadLevel(); //load level if a programe id is set
			//Tracer.End();
		},
		//*Student.BioData.LoadDepartment *BioData.LoadDepartment *Student.BioData.LoadDept *BioData.LoadDept
		LoadDept: function () { //function to load department textbox based on selected faculty
			//Tracer.Start();
			var facID = _("rstudfac").ValueContent();
			//Tracer.Tag("Faculty: "+facID);
			if (facID == null || facID.Trim() == "") facID = 0;
			//alert(facID);
			//alert(facID);
			//Tracer.Tag("Onload of dept due to change of fac = "+facID);
			TextBox.Load("rstuddept", "DeptID", "DeptName", "FacID = " + facID, "dept_tb"); //Load:function(tb,key, val, cond, dbtb)
			//Tracer.End();
			//_('rstudprog')
		},
		//*Student.BioData.LoadProgramme *BioData.LoadProgramme
		LoadProg: function () { //function to load program textbox based on selected department
			//Tracer.Start();
			var deptID = _("rstuddept").ValueContent();
			if (deptID == null || deptID.Trim() == "") deptID = 0;
			//Tracer.Tag("Onload of prog due to change of dept = " +deptID);
			//Tracer.Tag("Department: "+deptID);
			TextBox.Load("rstudprog", "ProgID", "ProgName", "DeptID = " + deptID, "programme_tb"); //Load:function(tb,key, val, cond, dbtb)
			//Tracer.End();
		}, LoadLevel: function () { //function to load level based on programme and 
			//Tracer.Start();
			var progID = _("rstudprog").ValueContent();
			var studyobj = _("rstudstudy");
			var studstudy = studyobj == null ? 0 : studyobj.ValueContent();
			if (progID == "") return;
			if (studstudy == null || studstudy.Trim() == "") studstudy = 0;
			//alert(facID);
			//Tracer.Tag("Onload of level due to change of prog = "+progID+" or studyid = " + studstudy);
			//Tracer.Tag("Level: StudyID is "+studstudy);
			TextBox.Load("rstudlvl", configdata.Core + "cportal/Pages/Scripts/Gen/loadlevel.php?StudyID=" + escape(studstudy) + "&progID=" + escape(progID) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
			_("semest").ClearText();
			//MessageBox.Show("Note: Level-Set Changed, confirm Student level before Save");
			//Load:function(tb,key, val, cond, dbtb)
			//Tracer.End();
		},
		LoadStudy: function () {
			TextBox.Load("rstudstudy", configdata.Core + "cportal/Pages/Scripts/Gen/loadStudy.php?a=1" + "&SubDir=" + encodeURIComponent(configdata.SubDir));

		},
		CourseAj: null,
		LoadCourse: function () {
			_('lcourses').FadeOut(300);
			//_("loadcourses").FadeIn(200);
			_("loadcourses").Animate({ CSSRule: "visibility:visible;opacity:1", Time: 200 });
			var progobj = _('rstudprog');
			var progID = progobj.classList.contains("textBx") ? progobj.ValueContent() : progobj.value;
			//var progID = _("rstudprog").ValueContent();
			var lvlID = _("rstudlvl").ValueContent();
			var studyobj = _("rstudstudy");
			var studstudy = studyobj == null ? 5 : studyobj.ValueContent();
			var sesid = _("sestb").ValueContent();
			//semest
			var semest = _("semest").ValueContent();
			if (Exams.ResultUpload.CourseAj != null) {
				Exams.ResultUpload.CourseAj.abort();
				Exams.ResultUpload.CourseAj = null;
			}
			Exams.ResultUpload.CourseAj = _('lcourses').HTML(configdata.Core + "cportal/Pages/Scripts/Exams/loadcourses.php?dept=" + progID + "&lvl=" + lvlID + "&stid=" + studstudy + "&sem=" + semest + "&ses=" + sesid + "&SubDir=" + encodeURIComponent(configdata.SubDir), function () { _('lcourses').FadeIn(300); _("loadcourses").Animate({ CSSRule: "visibility:hidden;opacity:0", Time: 200 }); Exams.ResultUpload.CourseAj = null; }, function () { });
			//TextBox.Load("rcourse","CourseID","CONCAT('<b>',CourseCode,'</b> - ',Title)","Lvl = " +lvlID+" AND Sem = "+semest+" AND DeptID = "+progID+" AND StudyID = "+studstudy,"course_tb");

		}, LoadSemester: function () {

			TextBox.Load("semest", "Num", "Sem", "Enable=1", "semester_tb");

		}, LoadEmptySheet: function () {
			_("rstcontdiv").FadeOut(300);
			_("rstcontdiv").HTML(configdata.Core + "cportal/Pages/Scripts/Exams/loadstudregrst.php?empty=1" + "&SubDir=" + encodeURIComponent(configdata.SubDir), function () {
				_("rstcontdiv").FadeIn(300);
				_('rstrpagrp_title').innerHTML = "Result Sheet";
			});
			// Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100);

			//_("loadcourses").Animate({CSSRule:"visibility:hidden;opacity:0",Time:200});

		}, CourseReload: function () {
			if (_('semest') != null) {
				Exams.ResultUpload.LoadCourse();
			} else {
				Page.Open('Pages/Page/exams.php', 0, 'Exams', 'RUpload', 'Result Upload', true)
			}

		}, Clear: function () {
			CoverScreen.Show("rstclear", "Working ...", function () {
				var obj = _('coursetb');
				if (obj != null) {
					obj.Deselect();
				}
				Exams.ResultUpload.LoadEmptySheet();
				CoverScreen.Close(_('rstclear'));
			});
		}, Print: function () {
			//get the display rst det 
			var disdet = _('dispdetid');
			if (disdet == null) { MessageBox.Show("#No Result Found/Loaded"); return; }
			if (disdet.value.Trim() == "") { MessageBox.Show("#No Result Found/Loaded"); return; }
			console.log(disdet.value);
			var loadedsprsh = _('sprstupload');
			if (loadedsprsh == null) { MessageBox.Show("No Result Sheet Found"); return; }
			var totrow = loadedsprsh.rows.length - 2;
			/* var RestPrint = new Printer();
			  RestPrint.Preview("Result Sheet","Reports/Exams/resultsheet.php?"+disdet.value+"&TotRow="+totrow,function(){});*/
			// var RestPrint = new PDFPrinter();
			PDFPrinter.Print(configdata.Core + "cportal/Reports/Exams/resultsheet.php", disdet.value + "&TotRow=" + totrow + "&paper=A4&orientation=P&MT=4&MB=40&SubDir=" + encodeURIComponent(configdata.SubDir), "resultsheet.pdf");
			//alert();
		},
		ImportData: "",
		Import: function () {
			if (_('sprstupload_file') == null) {
				MessageBox.Show("Load the result sheet to import into");
				return;
			}
			var loadedparamobj = _('dispdetid');
			if (loadedparamobj == null) {
				MessageBox.Show("#No Result Loaded");
				return;
			}
			//check if result already approved
			var approbj = _("dispdetappr");
			if (approbj != null) {
				if (approbj.value == "1") {
					MessageBox.Show("INVALID OPERATION: RESULT ALREADY APPROVED");
					return;
				}
			}

			/* var rstScoreStruc = _('rstScoreStruc');
			if(rstScoreStruc == null){
				MessageBox.Show("#SCORING STRUCTURE NOT FOUND");
				return;
			}

			rstScoreStruc = rstScoreStruc.textContent;
			//alert(rstScoreStruc);
			rstScoreStruc = JSON.parse(rstScoreStruc); */
			var rstScoreStruc = Exams.ResultUpload.GetScoreStructure();
			if (rstScoreStruc.length < 1) {
				MessageBox.Show("#SCORING STRUCTURE NOT FOUND");
				return;
			}
			var headermk = '<tr><th style="border:#ddd solid thin;text-transform:uppercase">Column</th><th style="border:#ddd solid thin;text-transform:uppercase">Label</th></tr><tr><th style="border:#ddd solid thin;text-align:left;text-transform:uppercase">Registration Number:</th><td style="border:#ddd solid thin;"><input style="width:50px;border:none;height:100%" type="text" id="regcol" value="B" /></td></tr>';
			//var wt = 250/(rstScoreStruc.length + 1);
			//var inputmk = '<td style="border:#ddd solid thin;"><input style="width:'+wt+'px;border:none;height:100%" type="text" id="regcol" value="B" /></td>';
			var col = ["D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S"];
			//var scorf = [];
			for (var dd = 0; dd < rstScoreStruc.length; dd++) {
				var colletter = typeof col[dd] == _UND ? "X" : col[dd];
				headermk += '<tr><th style="border:#ddd solid thin;text-align:left;text-transform:uppercase">' + rstScoreStruc[dd] + ':</th><td style="border:#ddd solid thin;"><input style="width:50px;border:none;height:100%" type="text" class="scorerstinp" id="SCE' + (dd + 1) + '" value="' + colletter + '" /></td></tr>';
				//inputmk += '<td style="border:#ddd solid thin;"><input style="width:'+wt+'px;border:none;height:100%" type="text" id="SCE'+(dd+1)+'" value="'+colletter+'" /></td>';
			}

			OptionBox.Show({
				Title: "Import Result From Excel",
				TitleHTML: '<table cellspacing="0" cellpadding="0" style="border-collapse: collapse;width:250px;font-size:0.9em" class="tbl rw greyShadow" border="1">' + headermk + '</table>',
				Options: [
					{
						Title: "Import",
						Logo: "download",
						Info: "Import a result from a valid excel file (.xls, .xlsx)",
						Function: function (rss) {

							//if(coursedetobj == null){MessageBox.Show("#ERROR: NO COURSE DETAILS FOUND"); return;}
							//alert()
							//Exams.ResultUpload.ImportData = "colregno=" + _('regcol').value + "&colca=" + _('cacol').value + "&colexam=" + _('examcol').value;
							Exams.ResultUpload.ImportData = "colregno=" + _('regcol').value + "&TotSC=" + rss.length;
							for (var dds = 0; dds < rss.length; dds++) {
								Exams.ResultUpload.ImportData += '&SCE' + (dds + 1) + '=' + encodeURIComponent(_('SCE' + (dds + 1)).value) + '&SC' + (dds + 1) + '=' + encodeURIComponent(rss[dds]);
							}
							//alert(Exams.ResultUpload.ImportData);
							_('sprstupload_file').click();

						},
						Parameter: rstScoreStruc
					},
					{
						Title: "Cancel",
						Logo: "times",
						Info: "Terminate Import Operation",
						Function: function () {
							MessageBox.Show("Import Operation Aborted");
						}
					}
				]
			});


		},
		ImportAjax: new Ajax(),
		PerformImport: function (fileobj) {
			var loadedparamobj = _('dispdetid');
			var coursedetobj = _("dispdet");
			if (loadedparamobj == null) {
				MessageBox.Show("#No Result Loaded");
				return;
			}
			//convert dets to array
			var detidarray = loadedparamobj.value.ToDataArray();
			var detstrarray = coursedetobj.value.ToDataArray();
			var newdatastr = "";
			for (var key in detidarray) {
				if (detidarray.hasOwnProperty(key)) {
					var id = detidarray[key];
					var txt = detstrarray[key];
					newdatastr += "&" + key + "=" + id + ":" + rawescape(txt);
				}
			}

			//_("rstcontdiv").FadeOut(300);
			_('rstshinner').Hide();
			_("rstcontdiv").insertAdjacentHTML('beforeend', Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load and Proccess Results from Excel</small>"))
			//_("rstcontdiv").innerHTML += Markups.GroupBoxPlaceholder("download ep-animate-fading","Please Wait !!!! </br><small>While we Load and Proccess Results from Excel</small>");
			var data = fileobj.id + "=?" + "&" + Exams.ResultUpload.ImportData + newdatastr + "&import=1";
			//alert(data);return;
			Exams.ResultUpload.ImportAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadstudregrst.php",
				PostData: data + "&SubDir=" + encodeURIComponent(configdata.SubDir) + "&Require=" + encodeURIComponent(configdata.Require),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_("rstcontdiv").innerHTML = res;
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100);
					var det = _("dispdet");
					if (det != null) {
						totrw = "";
						if (_('sprstupload') != null) {
							var totrw = _('sprstupload').rows.length - 2;
						}
						// alert(det.value);
						var dtarr = det.value.ToDataArray();
						// alert(dtarr['rcourse']);
						_('rstrpagrp_title').innerHTML = Icon("check-square-o") + " Result Sheet - " + dtarr['rcourse'] + " - #" + totrw;
					}
					//_("loadcourses").Animate({CSSRule:"visibility:hidden;opacity:0",Time:200});
					//_("rstcontdiv").FadeIn(300);
					// alert(res);
				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
					_("rstcontdiv").innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>" + res + "</small>", 'danger-text');
					//	MessageBox.Show("" + res);
				}
			})
		}
		, Deselect: function () {

			var obj = _('coursetb');
			if (obj != null) {
				obj.Deselect();
			}
		}
	},

	//Result Approval 
	Approval: {
		View: function (datasrt) {
			/*var RestPrint = new Printer();
					  RestPrint.Preview("Result Sheet","Reports/Exams/resultsheet.php?"+datasrt,function(){});*/
			PDFPrinter.Print(configdata.Core + "cportal/Reports/Exams/resultsheet.php", datasrt + "&paper=A4&orientation=P&MT=4&MB=40&SubDir=" + encodeURIComponent(configdata.SubDir), "resultsheet.pdf");
		},
		SearchAjax: new Ajax(),
		SearchDelayTimer: null,
		Search: function () {
			//alert(obj);
			if (Exams.Approval.SearchDelayTimer != null) {

				clearTimeout(Exams.Approval.SearchDelayTimer);
				Exams.Approval.SearchDelayTimer = null;
				Exams.Approval.SearchAjax.abort();
				//console.log('Aborted');
			}
			//console.log(Exams.Approval.SearchAjax);
			Exams.Approval.SearchDelayTimer = setTimeout(function () {

				_('rstapprbx').FadeOut(300);
				_('rstsloadin').Animate({ CSSRule: "opacity:1;visibility:visible", Time: 300 });
				var UID = Login.User();
				UID = UID[0]
				var limit = _('maxrec').RangeValue();
				var val = _("rstappsearch").TextContent();
				var filter = _("apprfilter").TextContent();
				Exams.Approval.SearchAjax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/rstapprsearch.php",
						PostData: "UID=" + UID + "&limit=" + limit + "&val=" + escape(val) + "&filter=" + filter + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							_('rstapprbx').innerHTML = res;
							_('rstapprbx').FadeIn(300);
							_('rstsloadin').Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 300 });
							Exams.Approval.SearchDelayTimer = null;
							// alert(res);
						},
						OnError: function (res) {
							MessageBox.Show("#Internal Error: " + res);
							Exams.Approval.SearchDelayTimer = null;
						}
					}
				)
			}, 300);
			//alert(UID + ";" + limit + ";" + val);
			//var val = _("rstappsearch").Text
		},
		Save: function () {
			var ssbobj = _('rstapprssb');
			if (ssbobj == null) {
				return;
			}
			OptionBox.Show({
				Title: "Save Result Approval Status",
				Options: [
					{
						Title: "Continue",
						Logo: "save",
						Info: "Save all displayed Result Approval Status",
						Function: function () {
							var datas = _('rstapprssb').GetDataString();
							//console.log(datas+"&SubDir="+encodeURIComponent(configdata['SubDir']));
							Exams.Approval.SaveAjax = new Ajax();
							Exams.Approval.SaveAjax.Post({
								Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/saveappr.php",
								PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
								OnProgress: function (delta) {
									Tabs.Tab("Exams").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
								},
								OnComplete: function (res) {
									if (!Login.Authenticate(res)) return;
									MessageBox.Show(res);
									Tabs.Tab("Exams").ProgressGet(1).ProgressTo(100);
									//MessageBox.Show(res);
								},
								OnAbort: function (res) {
									Tabs.Tab("Exams").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("#Operation Aborted");');

								},
								OnError: function (res) {
									MessageBox.Show("" + res);
									Tabs.Tab("Exams").ProgressGet(1).ProgressTo(-1);
								}
							});
						}
					},
					{
						Title: "Cancel",
						Logo: "times",
						Info: "Terminate Save Operation",
						Function: function () {
							MessageBox.Show("Save Operation Aborted");
						}
					}
				]
			});
		},
		Clear: function () {
			_('removeRw_rstapprssb').click();
		}, Print: function () {
			//check spreadsheet 
			var sprsh = _('paramrstapp');
			if (sprsh != null) {
				//get the datastr 
				var datastr = sprsh.value + "&paper=A4&orientation=P&MT=4&MB=32&SubDir=" + encodeURIComponent(configdata.SubDir);

				//get the user id
				//var UID = Login.User();
				//UID = UID[0];
				//get the search val 
				//var txtval = _('rstappsearch').TextContent();
				//datastr += "&UID="+UID+"&val="+escape(txtval);
				//alert(datastr);

				PDFPrinter.Print(configdata.Core + "cportal/Reports/Exams/resultapprsheet.php", datastr, "apprs.pdf");
				//PDFPrinter.Print("root://cportal/Reports/Exams/broadsheet.epr", "", "apprs.pdf");
			} else {
				MessageBox.Show("No Record Found");
			}
		}
	},
	//Exams.ResultReport
	ResultReport: {
		GenLoader: new GenLoading({ StudyID: "tstudstudy", FacID: "tstudfac", DeptID: "tstuddept", ProgID: "tstudprog", LevelID: "tstudlvl", SemID: "tsemest", ClassID: "tstudclass" }),
		LoadRstAjax: new Ajax(),
		LoadOptions: (rstID, studname) => {
			OptionBox.Show({
				Title: '<b style="font-size:1.2em">' + studname + '</b>',
				Logo: "user",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Exams/loadattr.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&RstID=" + rstID },
				Options: [{
					Logo: "save",
					Title: "Save Result",
					Info: "Save other Result Details",
					Function: function (rstID) {
						Exams.ResultReport.SaveResultAttr(rstID);
					},
					Parameter: rstID
				}, {
					Logo: "print",
					Title: "Print Result",
					Info: "Print Student Result",
					Function: function (rstID) {
						/* var action = [{"Action":'Exams.ResultReport.Sign(\''+escape(JSON.stringify(signparam))+'\')',"Logo":"pencil","Title":"Append Signature","DisplayText":"Sign"}]; */
						/* scriptarr = script.split("/");
						if(scriptarr[0] == "Reports"){ //for old script url
							script = configdata.Core+"cportal/"+script;
						} */
						script = configdata.Core + "general/Slip.php";
						datastr = "RID=" + rstID + "&folder=Result&file=Slipi.php&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&PayperType=A4&Orientation=P&MarginTop=4&MarginBottom=4";
						PDFPrinter.Print(script, datastr, "Result_" + rstID + ".pdf");
					},
					Parameter: rstID
				}]

			});
		},
		SaveResultAttr: rstID => {
			var otherResultsIDs = _('otherResults');
			if (otherResults == null) {
				MessageBox.Show("#INVALID PARAMETER"); return;
			}
			//console.log(otherResultsIDs);
			var otherResultsIDarr = JSON.parse(otherResultsIDs.textContent);
			var data = {};
			//get the ids of the Group Sheets
			for (var d = 0, dlen = otherResultsIDarr.length; d < dlen; d++) {
				//get the individual spreadsheet
				var otherRdet = otherResultsIDarr[d];
				var GN = otherRdet[1];
				var Remarks = otherRdet[2];
				//var sheetiddata = _(otherRdet[0]).GetDataString();
				data[otherRdet[0]] = _(otherRdet[0]).GetDataString();
				data[otherRdet[0] + "_GN"] = GN;
			}
			data["TComment"] = _('rstclassteachercoment').TextContent();
			data["HTComment"] = _('rstheadteachercoment').TextContent();
			data["otherRst"] = otherResultsIDs.textContent;
			data["SubDir"] = configdata['SubDir'];
			data["RID"] = rstID;
			Exams.ResultReport.LoadRstAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/saveotherrst.php",
				PostData: data,
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//_('rstrptcontdiv').innerHTML = res;

					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(100);
					/* var infobx = _('rstinfobs');
					if(infobx != null){
						_('rstrptsht_title').innerHTML = Icon('check-square-o') + " " + infobx.value;
					} */
					MessageBox.Show(res);

					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res.Replace('"', '\"') + '");');
				}
			})

			//console.log(data);
			//alert(JSON.stringify(data));
		},
		LoadResult: function () {
			var reqired = _("textBx & objgrpelemrstrpt & req err");
			if (reqired != null) {
				MessageBox.Show("Invalid Selection: All Fields are Required");
				return;
			}
			//_('rstrptcontdiv').FadeOut(200);
			_('rstrptsht_title').innerHTML = Icon('check-square-o') + " RESULT SHEET"
			_('rstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load and Proccess Results</small>");
			var progobj = _('tstudprog');
			var progid = progobj.classList.contains("textBx") ? progobj.TextContent() : progobj.value;
			var studobj = _('tstudstudy');
			var studyID = studobj == null ? 0 : studobj.TextContent()
			var datastr = "StudyID=" + studyID + "&ProgID=" + progid + "&LevelID=" + _('tstudlvl').TextContent() + "&SemID=" + _('tsemest').TextContent() + "&SesID=" + _('tsestb').TextContent() + "&ClassID=" + _('tstudclass').TextContent();
			//alert(datastr);
			Exams.ResultReport.LoadRstAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadrst.php",
				PostData: datastr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_('rstrptcontdiv').innerHTML = res;

					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(100);
					var infobx = _('rstinfobs');
					if (infobx != null) {
						_('rstrptsht_title').innerHTML = Icon('check-square-o') + " " + infobx.value;
					}
					_('rsheethome').Hide();
					_('rstrptsht').Show();
					Tabs.HideSideBar("Exams", 2);
					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					_('rstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>Operation Aborted</small>", 'altColor');
				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
					_('rstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>" + "Internal Error: " + res + "</small>", 'danger-text');
				}
			})
			// alert(datastr);
		},
		PrintAjax: new Ajax(),
		Print: function () {
			var reqired = _("textBx & objgrpelemrstrpt & req err");
			if (reqired != null) {
				MessageBox.Show("Invalid Selection: All Fields are Required");
				return;
			}/* OptionBox.TextBox({id:'techcodetb',logo:'unlock',title:'Technical Personel ID (TPID)',type:'password'}) */
			Exams.ResultReport.PrintAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadreports.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var reports = JSON.parse(res);
					//console.log(reports);
					var Options = [];
					if (reports) {
						for (var d = 0; d < reports.length; d++) {
							var indrp = reports[d];
							Options.push(
								{
									Title: indrp.Title,
									Info: indrp.Descr,
									Logo: indrp.Logo,
									Function: function (param) {
										param[0] += "&utitle=" + escape(_('sheettit').TextContent());
										Exams.ResultReport.PrintReal(param[0], param[1], param[2]);
									},
									Parameter: [indrp.Param, indrp.Script, indrp.ID]
								}
							);
						}
						//console.log(Options);
						OptionBox.Show({
							Title: "Select Result Sheet Type",
							//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
							TitleHTML: OptionBox.TextBox({ id: 'sheettit', logo: 'font', title: 'Result Sheet Title (Main Only)', type: 'text' }),
							Options: Options
						});
					} else {
						MessageBox.Show("No Report Set");
					}
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(100);
					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);

				}
			})

			// _('rstrptcontdiv').FadeOut(200);

			// MessageBox.Show(datastr);
		},
		PrintReal: function (param, script, ReportID) {
			//typee = (typeof typee == _UND) ? "main" : typee;
			progobj = _('tstudprog');
			var progid = progobj.classList.contains("textBx") ? progobj.TextContent() : progobj.value;
			var studobj = _('tstudstudy');
			var studyID = studobj == null ? 0 : studobj.TextContent();
			var lvl = _('tstudlvl').TextContent(), sem = _('tsemest').TextContent(), ses = _('tsestb').TextContent(), classid = _('tstudclass').TextContent();
			var datastr = "StudyID=" + studyID + "&ProgID=" + progid + "&LevelID=" + lvl + "&SemID=" + sem + "&SesID=" + ses + "&ClassID=" + classid + "&" + param + "&ReportID=" + ReportID;
			var fname = datastr.Replace("=", "");
			fname = fname.Replace("&", "");
			var signparam = { "StudyID": studyID, "ProgID": progid, "LevelID": lvl, "SemID": sem, "SesID": ses, "ReportID": ReportID };
			datastr += "&sigparam=" + escape(JSON.stringify(signparam));
			//var signparam = studyID+"~"+progid+"~"+lvl+"~"+sem+"~"+ses+"~"+ReportID; //ReportID Must be the last
			//console.log(datastr);
			//PDFPrinter.Print("Reports/Exams/resultBroadSheet.php", datastr, "BroadSheet_" + fname + ".pdf");
			//"root://cportal/Reports/Exams/broadsheet.epr"
			var action = [{ "Action": 'Exams.ResultReport.Sign(\'' + escape(JSON.stringify(signparam)) + '\')', "Logo": "pencil", "Title": "Append Signature", "DisplayText": "Sign" }];
			scriptarr = script.split("/");
			if (scriptarr[0] == "Reports") { //for old script url
				script = configdata.Core + "cportal/" + script;
			}
			PDFPrinter.Print(script, datastr, "BroadSheet_" + fname + ".pdf", action);
		},
		SignAjax: new Ajax(),
		Sign: function (signparam) {
			//alert(signparam);
			//get the report signatures
			Exams.ResultReport.SignAjax.Post({
				OnComplete: function (res, url, para) {
					if (res.Trim() != "") {
						//alert(res);
						var resobj = JSON.parse(res);
						if (typeof resobj.Error != _UND) {
							MessageBox.Show("#" + resobj.Error); return;
						}

						if (typeof resobj.Signatories != _UND) {
							//signatories found
							//form Signatory Options
							var Options = [];
							for (var dd = 0; dd < resobj.Signatories.length; dd++) {
								var sig = resobj.Signatories[dd];
								Options.push({
									Title: sig.Title,
									Info: "Sign Report as " + sig.Title,
									Logo: "pencil",
									Function: function (param) {
										var sigdet = escape(JSON.stringify(param[0]));
										var reportparam = param[1];
										/* var userdet = Login.User();
											if (userdet == null) { MessageBox.Show("User Identification Failed"); return; }
											var userID = userdet[0]; */
										var usertb = _('SigUserName');
										if (usertb == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Username Field"); return; }
										usernm = usertb.TextContent();
										if (usernm.Trim() == "") { MessageBox.Show("Invalid Signatory Username"); return; }

										//Password
										var usertbpw = _('SigPassw');
										if (usertbpw == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Password Field"); return; }
										usernmpw = usertbpw.TextContent();
										if (usernmpw.Trim() == "") { MessageBox.Show("Invalid Signatory Password"); return; }

										Exams.ResultReport.PerformSign(sigdet, reportparam, [usernm, usernmpw]);
									},
									Parameter: [sig, para['param']]
								});
							}
							OptionBox.Show({
								Title: "Append Signature",
								TitleHTML: resobj.HTML,
								Logo: "pencil",
								Options: Options
							});
							return;
						}
					}
					MessageBox.Show("#Invalid Response");

					//alert(res);
				},
				OnError: function (res) {
					MessageBox.Show("#Internal Error - " + res);
				},
				PostData: "param=" + signparam + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php"
			});

		},
		PSignAjax: new Ajax(),
		PerformSign: function (sigdet, reportparam, userDet) {

			Exams.ResultReport.PSignAjax.Post({
				PostData: "SignDet=" + sigdet + "&ReportDet=" + reportparam + "&UserName=" + escape(userDet[0]) + "&UserPassw=" + escape(userDet[1]) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php",
				OnComplete: function (res) {
					var resobj = JSON.parse(res);
					if (typeof resobj.Error != _UND) {
						MessageBox.Show(resobj.Error);
						return;
					}

					//regenerate the report
					PDFPrinter.Preview();
				},
				OnError: function (res) {
					MessageBox.Show("Internal Error: " + res);
				}
			});
		}

	},
	//Exam.MasterMark
	MasterMark: {
		GenLoader: new GenLoading({ StudyID: "mstudstudy", FacID: "mstudfac", DeptID: "mstuddept", ProgID: "mstudprog", LevelID: "mstudlvl", SemID: "msemest", ClassID: "mstudclass" }),
		LoadRstAjax: new Ajax(),
		LoadResult: ()=>{
			var reqired = _("textBx & mstmrkgrpelem & req err");
			if (reqired != null) {
				MessageBox.Show("Invalid Selection: All Fields are Required");
				return;
			}
			//_('rstrptcontdiv').FadeOut(200);
			_('mstrptsht_title').innerHTML = Icon('check-square-o') + " MASTER RESULT SHEET"
			_('mstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load and Proccess Master Result</small>");
			var progobj = _('mstudprog');
			var progid = progobj.classList.contains("textBx") ? progobj.TextContent() : progobj.value;
			var studobj = _('mstudstudy');
			var studyID = studobj == null ? 0 : studobj.TextContent()
			var datastr = "StudyID=" + studyID + "&ProgID=" + progid  + "&SesID=" + _('msestb').TextContent() + "&ClassID=" + _('mstudclass').TextContent();
			Exams.MasterMark.LoadRstAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadmasterrst.php",
				PostData: datastr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_('mstrptcontdiv').innerHTML = res;

					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(100);
					var infobx = _('mstinfobs');
					if (infobx != null) {
						_('mstrptsht_title').innerHTML = Icon('check-square-o') + " " + infobx.value;
					}
					_('msheethome').Hide();
					_('mstrptsht').Show();
					Tabs.HideSideBar("Exams", 3);
					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					_('mstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>Operation Aborted</small>", 'altColor');
				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
					_('mstrptcontdiv').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>" + "Internal Error: " + res + "</small>", 'danger-text');
				}
			})
			// console.log(datastr,'Data record');
		}
		,
		PrintAjax: new Ajax(),
		Print: function () {
			var reqired = _("textBx & mstmrkgrpelem & req err");
			if (reqired != null) {
				MessageBox.Show("Invalid Selection: All Fields are Required");
				return;
			}/* OptionBox.TextBox({id:'techcodetb',logo:'unlock',title:'Technical Personel ID (TPID)',type:'password'}) */
			Exams.MasterMark.PrintAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadreports.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir'])+"&Marker=ResultMasterSheet",
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var reports = JSON.parse(res);
					//console.log(reports);
					var Options = [];
					if (reports) {
						for (var d = 0; d < reports.length; d++) {
							var indrp = reports[d];
							Options.push(
								{
									Title: indrp.Title,
									Info: indrp.Descr,
									Logo: indrp.Logo,
									Function: function (param) {
										param[0] += "&utitle=" + escape(_('sheettit').TextContent());
										Exams.MasterMark.PrintReal(param[0], param[1], param[2]);
									},
									Parameter: [indrp.Param, indrp.Script, indrp.ID]
								}
							);
						}
						//console.log(Options);
						OptionBox.Show({
							Title: "Select Sheet Type",
							//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
							TitleHTML: OptionBox.TextBox({ id: 'sheettit', logo: 'font', title: 'Sheet Title', type: 'text' }),
							Options: Options
						});
					} else {
						MessageBox.Show("No Report Set");
					}
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(100);
					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(3).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);

				}
			})

			// _('rstrptcontdiv').FadeOut(200);

			// MessageBox.Show(datastr);
		},
		PrintReal: function (param, script, ReportID) {
			//typee = (typeof typee == _UND) ? "main" : typee;
			progobj = _('mstudprog');
			var progid = progobj.classList.contains("textBx") ? progobj.TextContent() : progobj.value;
			var studobj = _('mstudstudy');
			var studyID = studobj == null ? 0 : studobj.TextContent();
			var  ses = _('msestb').TextContent(), classid = _('mstudclass').TextContent();
			var datastr = "StudyID=" + studyID + "&ProgID=" + progid  + "&SesID=" + ses + "&ClassID=" + classid+ "&" + param + "&ReportID=" + ReportID ;
			var fname = datastr.Replace("=", "");
			fname = fname.Replace("&", "");
			var signparam = { "StudyID": studyID, "ProgID": progid, "SesID": ses, "ReportID": ReportID, "ClassID":classid };
			datastr += "&sigparam=" + escape(JSON.stringify(signparam));
			//var signparam = studyID+"~"+progid+"~"+lvl+"~"+sem+"~"+ses+"~"+ReportID; //ReportID Must be the last
			//console.log(datastr);
			//PDFPrinter.Print("Reports/Exams/resultBroadSheet.php", datastr, "BroadSheet_" + fname + ".pdf");
			//"root://cportal/Reports/Exams/broadsheet.epr"
			 var action = [{ "Action": 'Exams.MasterMark.Sign(\'' + escape(JSON.stringify(signparam)) + '\')', "Logo": "pencil", "Title": "Append Signature", "DisplayText": "Sign" }];
			scriptarr = script.split("/"); 
			if (scriptarr[0] == "Reports") { //for old script url
				script = configdata.Core + "cportal/" + script;
			}
			PDFPrinter.Print(script, datastr, "BroadSheet_" + fname + ".pdf",action);
		},
		SignAjax: new Ajax(),
		Sign: function (signparam) {
			//alert(signparam);
			//get the report signatures
			Exams.MasterMark.SignAjax.Post({
				OnComplete: function (res, url, para) {
					if (res.Trim() != "") {
						//alert(res);
						var resobj = JSON.parse(res);
						if (typeof resobj.Error != _UND) {
							MessageBox.Show("#" + resobj.Error); return;
						}

						if (typeof resobj.Signatories != _UND) {
							//signatories found
							//form Signatory Options
							var Options = [];
							for (var dd = 0; dd < resobj.Signatories.length; dd++) {
								var sig = resobj.Signatories[dd];
								Options.push({
									Title: sig.Title,
									Info: "Sign Report as " + sig.Title,
									Logo: "pencil",
									Function: function (param) {
										var sigdet = escape(JSON.stringify(param[0]));
										var reportparam = param[1];
										/* var userdet = Login.User();
											if (userdet == null) { MessageBox.Show("User Identification Failed"); return; }
											var userID = userdet[0]; */
										var usertb = _('SigUserName');
										if (usertb == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Username Field"); return; }
										usernm = usertb.TextContent();
										if (usernm.Trim() == "") { MessageBox.Show("Invalid Signatory Username"); return; }

										//Password
										var usertbpw = _('SigPassw');
										if (usertbpw == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Password Field"); return; }
										usernmpw = usertbpw.TextContent();
										if (usernmpw.Trim() == "") { MessageBox.Show("Invalid Signatory Password"); return; }

										Exams.ResultReport.PerformSign(sigdet, reportparam, [usernm, usernmpw]);
									},
									Parameter: [sig, para['param']]
								});
							}
							OptionBox.Show({
								Title: "Append Signature",
								TitleHTML: resobj.HTML,
								Logo: "pencil",
								Options: Options
							});
							return;
						}
					}
					MessageBox.Show("#Invalid Response");

					//alert(res);
				},
				OnError: function (res) {
					MessageBox.Show("#Internal Error - " + res);
				},
				PostData: "param=" + signparam + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php"
			});

		},
		PSignAjax: new Ajax(),
		PerformSign: function (sigdet, reportparam, userDet) {

			Exams.MasterMark.PSignAjax.Post({
				PostData: "SignDet=" + sigdet + "&ReportDet=" + reportparam + "&UserName=" + escape(userDet[0]) + "&UserPassw=" + escape(userDet[1]) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php",
				OnComplete: function (res) {
					var resobj = JSON.parse(res);
					if (typeof resobj.Error != _UND) {
						MessageBox.Show(resobj.Error);
						return;
					}

					//regenerate the report
					PDFPrinter.Preview();
				},
				OnError: function (res) {
					MessageBox.Show("Internal Error: " + res);
				}
			});
		}
	},
	//Exams.ResultReport
	ResultFixer: {
		Clear: function () {
			_('resultfixtitle').innerHTML = '';
			_('rstfixcontdiv').innerHTML = '';
		},
		GenLoader: new GenLoading({ StudyID: "fstudstudy", FacID: "fstudfac", DeptID: "fstuddept", ProgID: "fstudprog", LevelID: "fstudlvl" }),
		FixerAjax: new Ajax(),
		//toggle the fixer scope type
		FixerType: function (swi) {
			var state = swi.GetStatus();
			if (state == 1) {
				_('fixbyregno').Show();
				_('fixbyrange').Hide();
				_('fspecreg').TextFocus();//fspecreg
			} else {
				_('fixbyregno').Hide();
				_('fixbyrange').Show();
			}
		},
		AutoFix: function (swi) {
			var state = swi.GetStatus();
			if (state == 1) {
				_('fixbtn').ButtonText("Troubleshoot & Fix Result");
			} else {
				_('fixbtn').ButtonText("Troubleshoot Result");
			}
			//fixbtn
		},
		FixRegNos: [],
		GetAllStudent: function () {
			var fixbtn = _('fixbtn');
			if (fixbtn.IsLoading()) {
				MessageBox.Show("A process is on-going, wait until completion or Stop Process");
				return;
			}
			//check fixer type
			var state = _('fixertype').GetStatus();
			var userDeptsobj = _('userdepts');
			var userDepts = userDeptsobj == null ? "" : userDeptsobj.value;
			if (state == 1) { //if specific student 
				//get the regNos
				RegNos = _('fspecreg').TextContent();
				if (RegNos.Trim() == "") {
					MessageBox.Show("Enter Student Registration Number <br/> <i>(Seperate multiple Registration Number with space or comma)</i>");
					_('fspecreg_pad').focus();
					return;
				} else {
					//get total regno
					studet = RegNos.Trim().Replace(" ", ",").split(",");
					//$data = "RegNos="+escape(RegNos);
				}
			} else {
				var studet = {};
				//fsestb
				// studet['SesID'] = _('fsestb').ValueContent().ToNumber();
				var studyobj = _('fstudstudy');
				studet['StudyID'] = studyobj == null ? -1 : studyobj.ValueContent().ToNumber();

				var facobj = _('fstudfac');
				studet['FacID'] = facobj == null ? 0 : facobj.ValueContent().ToNumber();

				var deptobj = _('fstuddept');
				studet['DeptID'] = deptobj == null ? 0 : deptobj.ValueContent().ToNumber();

				studet['ProgID'] = _('fstudprog').ValueContent().ToNumber();
				studet['LvlID'] = _('fstudlvl').ValueContent().ToNumber();

			}
			if (studet['StudyID'] == -1 && studet['ProgID'] == 0) {
				MessageBox.Show("INVALID SELECTION: PROGRAMME FIELD IS COMPULSARY"); return;
			}
			//alert(JSON.stringify(studet));
			//return;'<strong>348</strong> - Troubleshooting <span>AKS/NAS/MTH/019</span> Results ...'
			_('rstfixerhome').Hide();
			_('rstfixterm').Show();

			_('fixbtn').StartLoading();
			_('resultfixtitle').innerHTML = 'Reading and Processing Students ....';
			_('rstfixcontdiv').innerHTML = '';
			//alert("GetRegNos=" + escape(JSON.stringify(studet))+"&UserDet="+escape(userDepts));
			//studet['UserDept'] = userDepts;
			//load valid students
			Exams.ResultFixer.FixerAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/fix.php",
				PostData: "GetRegNos=" + escape(JSON.stringify(studet)) + "&UserDet=" + escape(userDepts) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(5).ProgressTo(Math.floor(delta * 19));
					//Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta*95));
				},
				OnComplete: function (res) {
					//alert(res);
					if (!Login.Authenticate(res)) return;
					Exams.ResultFixer.FixRegNos = []; Exams.ResultFixer.FixerIndex = 0;
					_('resultfixtitle').innerHTML = '';
					_('rstfixcontdiv').innerHTML = '';
					_('cntrbtn + cntrbtnfixall + fixallbtn').Hide();
					_('fixbtn').StopLoading();
					//_('').Hide();
					if (res == "#") {

						Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#No Valid Student Found");');

						return;
					}
					if (res == "##") {

						Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#Error Loading Students");');

						return;
					}

					if (res == "###") {//access denied

						Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#Access Denied <br /> Browser-Reload the system and Try Again");');

						return;
					}
					//_('rstfixcontdiv').innerHTML = res;
					//alert(res);
					//return;

					Tabs.Tab("Exams").ProgressGet(5).ProgressTo(20);
					resarr = res.split('@@##!!~~');
					var studDet = JSON.parse(resarr[0]);
					var totstud = studDet.Total;
					if (totstud < 1) {

						Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("No Valid Student Found");');
						return;
					}
					var studs = studDet.RegNos;
					var totbad = studDet.TotalBad;
					var studsbad = studDet.BadRegNos;
					//alert(studDet.Q)
					Exams.ResultFixer.FixRegNos = studDet.RegNos;
					_('resultfixtitle').innerHTML = '<strong class="ok">' + totstud + '</strong> Valid Student Found';
					//alert(totstud + " => " +JSON.stringify(studDet.RegNos)+" ; " + totbad+ " => " +JSON.stringify(studDet.BadRegNos));
					OptionBox.Show({
						Title: "Trobleshoot / Fix Student Result",
						TitleHTML: '<table class="tbl rwb greyShadow" style="width:95%;font-size:0.8em;margin:auto" bordercolor="#CCCCCC" border="1"><tr class=""  ><th style="text-align:left">Valid Student</th><td>' + totstud + '</td></tr><tr><th style="text-align:left">Invalid Student</th><td>' + totbad + '</td></tr></table><div style="font-size:0.7em;padding:10px" class="altColor"><i>(All Invalid Student will be Ignored)</i></div>' + resarr[1],
						ShowClose: false,
						Options: [{
							Title: "Troubleshoot",
							Info: "Troubleshoot and report student result issues",
							Logo: "cogs",
							Function: function () {
								Exams.ResultFixer.FixerState = "Play";
								var RstInfoID = _('RstInfoID').ValueContent();
								Exams.ResultFixer.Fixer(0, RstInfoID);
								_('resultfixtitle').innerHTML = '<strong>Initializing Troubleshooting ....</strong>';

								Tabs.Tab("Exams").ProgressGet(5).ProgressTo(100);
								Tabs.HideSideBar("Exams", 5);
							}
						},
						{
							Title: "Troubleshoot & Fix",
							Info: "Troubleshoot, Fix and report student result issues",
							Logo: "wrench",
							Function: function () {
								Exams.ResultFixer.FixerState = "Play";
								var RstInfoID = _('RstInfoID').ValueContent();

								Exams.ResultFixer.Fixer(1, RstInfoID);
								_('resultfixtitle').innerHTML = '<strong>Initializing Troubleshooting and Fixing ....</strong>';

								Tabs.Tab("Exams").ProgressGet(5).ProgressTo(100);
								Tabs.HideSideBar("Exams", 5);
							}
						},
						{
							Title: "CANCEL",
							Info: "Cancel Operation",
							Logo: "times",
							Function: function () {


								_('resultfixtitle').innerHTML = '';
								Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');
							}
						}]
					})

				},
				OnAbort: function () {
					Exams.ResultFixer.FixRegNos = []; Exams.ResultFixer.FixerIndex = 0;
					_('resultfixtitle').innerHTML = '';
					_('rstfixcontdiv').innerHTML = '';
					Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1);
					_('fixbtn').StopLoading();
				},
				OnError: function (res) {
					Exams.ResultFixer.FixRegNos = []; Exams.ResultFixer.FixerIndex = 0;
					_('resultfixtitle').innerHTML = '';
					_('rstfixcontdiv').innerHTML = '';
					Tabs.Tab("Exams").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
					_('fixbtn').StopLoading();
				}
			});


		},
		FixerIndex: 0,
		FixerState: 'Play',
		Play: function () {
			//Exams.ResultFixer.FixerState = "Play";
			if (Exams.ResultFixer.FixerState == 'Pause') {
				Exams.ResultFixer.FixerState = "Play";
				Exams.ResultFixer.Fixer(Exams.ResultFixer.CType);
				_('fixplaybtn').style.display = 'none';
				_('fixpausebtn').style.display = 'inline-block';
				_('resultfixtitle').innerHTML = '<strong>Resuming ...</strong>';
			} else if (Exams.ResultFixer.FixerState == 'Stop') {
				Exams.ResultFixer.FixerState = "Play";
				_('fixbtn').click();
			}


		},
		Pause: function () {
			if (Exams.ResultFixer.FixerState == 'Play') {
				_('resultfixtitle').innerHTML = '<strong>Pausing ...</strong>';
				Exams.ResultFixer.FixerState = "Pause";
				_('fixpausebtn').style.display = 'none';
				_('fixplaybtn').style.display = 'inline-block';
			}

		},
		Stop: function () {
			if (Exams.ResultFixer.FixerState == 'Play') {
				_('resultfixtitle').innerHTML = '<strong>Stoping ...</strong>';
				Exams.ResultFixer.FixerState = "Stop";
			} else if (Exams.ResultFixer.FixerState == 'Pause') {
				_('resultfixtitle').innerHTML = '<strong>' + (Exams.ResultFixer.FixerIndex + 1) + ' of ' + Exams.ResultFixer.FixRegNos.length + '</strong> -<span class="err"> Troubleshooting ' + $typetxt + " Process Stoped</span>";
				Exams.ResultFixer.FixRegNos = [];
				Exams.ResultFixer.FixerIndex = 0;
				Exams.ResultFixer.FixerState = "Stop";
				_('fixbtn').StopLoading();
				_('cntrbtn + cntrbtnfixall').Hide();
				_('fixallbtn').Show();
				_('fixplaybtn').style.display = 'none';
				_('fixpausebtn').style.display = 'inline-block';
			}

		},
		CType: 0,
		DefaultRInfoID: 1,
		Fixer: function (Type, RstInfoID) {
			Type = Type || 0;
			CType = Type;
			Exams.ResultFixer.DefaultRInfoID = RstInfoID;
			$typetxt = Type == 0 ? "" : " & Fixing";
			if (Exams.ResultFixer.FixerState == 'Stop') {
				_('resultfixtitle').innerHTML = '<strong>' + (Exams.ResultFixer.FixerIndex) + ' of ' + Exams.ResultFixer.FixRegNos.length + '</strong> -<span class="err"> Troubleshooting ' + $typetxt + " Process Stoped</span>";
				Exams.ResultFixer.FixRegNos = [];
				Exams.ResultFixer.FixerIndex = 0;
				_('fixbtn').StopLoading();
				_('cntrbtn + cntrbtnfixall').Hide();
				_('fixallbtn').Show();
				return;
			}

			if (Exams.ResultFixer.FixerState == 'Pause') {
				_('resultfixtitle').innerHTML = '<strong>' + (Exams.ResultFixer.FixerIndex) + ' of ' + Exams.ResultFixer.FixRegNos.length + '</strong> -<span class="altColor2"> Troubleshooting ' + $typetxt + " Process Paused</span>";
				//Exams.ResultFixer.FixRegNos = [];
				//Exams.ResultFixer.FixerIndex = 0;
				return;
			}

			if (Exams.ResultFixer.FixRegNos.length < 1) {
				MessageBox.Show("No Valid Student Loaded");
				_('resultfixtitle').innerHTML = '';
				_('rstfixcontdiv').innerHTML = '';
				Tabs.Tab("Exams").ProgressGet(5).ProgressTo(100);
				_('cntrbtn + cntrbtnfixall').Hide();
				_('fixallbtn').Hide();
				return;
			}
			_('fixbtn').StartLoading();
			//start individual troubleshoting
			//$startInd = 0;

			//perform trouble shoting

			//get the regno
			$RegNo = Exams.ResultFixer.FixRegNos[Exams.ResultFixer.FixerIndex];
			_('cntrbtn').Show();
			_('fixallbtn + cntrbtnfixall').Hide();
			//alert(JSON.stringify(Exams.ResultFixer.FixRegNos))
			//Exams.ResultFixer.FixerIndex++;
			if ($RegNo.Trim() == "") {
				Exams.ResultFixer.FixerIndex++;
				if (Exams.ResultFixer.FixerIndex < Exams.ResultFixer.FixRegNos.length) {
					Exams.ResultFixer.Fixer(param['Type']);
				} else {
					_('fixbtn').StopLoading();
					_('resultfixtitle').innerHTML = '<strong class="ok">' + Exams.ResultFixer.FixRegNos.length + ' Student<small>(s)</small> Processed Successfully</strong>';
					_('cntrbtn + cntrbtnfixall').Hide();
					_('fixallbtn').Show();
					//_('rstfixcontdiv').innerHTML = '';
				}

			} else {
				_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixerIndex + ' of ' + Exams.ResultFixer.FixRegNos.length + '</strong> - Troubleshooting ' + $typetxt + " (" + $RegNo + ") Result<small>(s)</small> ....";
				var RegAj = new Ajax();
				RegAj.Post({//
					PostData: "RegNo=" + escape($RegNo) + "&Type=" + Type + "&RstInfoID=" + RstInfoID + "&Num=" + (Exams.ResultFixer.FixerIndex + 1) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/fix.php",
					OnProgress: function (delta) {

					},
					OnComplete: (res, url, param) => {
						if (!Login.Authenticate(res)) return;
						//alert(res);
						//rstfixcontdiv
						_('rstfixcontdiv').insertAdjacentHTML('beforeend', res);
						Exams.ResultFixer.FixerIndex++;
						if (Exams.ResultFixer.FixerIndex < Exams.ResultFixer.FixRegNos.length) {
							Exams.ResultFixer.Fixer(param['Type'], RstInfoID);
						} else {
							_('fixbtn').StopLoading();
							_('resultfixtitle').innerHTML = '<strong class="ok">' + Exams.ResultFixer.FixRegNos.length + ' Student<small>(s)</small> Processed Successfully</strong>';
							_('cntrbtn + cntrbtnfixall').Hide();
							_('fixallbtn').Show();
						}
						var rind = _(param['RegNo'] + '_scroll');
						if (rind != null) {
							//rind.scrollIntoView();
						}

					},
					OnAbort: function () {
						Exams.ResultFixer.FixRegNos = [];
						Exams.ResultFixer.FixerIndex = 0;
						_('resultfixtitle').innerHTML = '<strong class="err">Process Aborted by User</strong>';
						_('fixbtn').StopLoading();
						_('cntrbtn + cntrbtnfixall').Hide();
						_('fixallbtn').Show();
					},
					OnError: function () {
						Exams.ResultFixer.FixRegNos = [];
						Exams.ResultFixer.FixerIndex = 0;
						_('resultfixtitle').innerHTML = '';
						_('resultfixtitle').innerHTML = '<strong class="err">Process Aborted due to Internal error</strong>';
						_('fixbtn').StopLoading();
						_('cntrbtn + cntrbtnfixall').Hide();
						_('fixallbtn').Hide();
					}
				})
			}
		},
		IndFixAjax: [],
		FixAllStatus: 'Stop',
		FixAllTotal: 0,
		FixAllBtn: [],
		FixCurrent: 0,
		//fix all student
		FixAll: function (fixallbtn) { //function to fix all
			if (Exams.ResultFixer.FixAllStatus == "Play") {
				MessageBox.Show("Fixing Process is already on-going");
				return;
			}
			var temptitle = _('resultfixtitle').innerHTML;
			_('resultfixtitle').innerHTML = 'Reading Troubleshooted Student(s) ....';
			//get all loaded student to be fixed
			var allstud = _('indfixbtn');
			if (allstud == null) { //if no student loaded
				MessageBox.Show("No Student Loaded");
				_('resultfixtitle').innerHTML = temptitle;
				return;
			}


			//get the total number of student
			var totstud = allstud.length;
			Exams.ResultFixer.FixAllBtn = allstud;
			Exams.ResultFixer.FixAllTotal = totstud;
			_('resultfixtitle').innerHTML = '<strong>' + 0 + ' of ' + totstud + '</strong> - Fixed ...';
			//get the current individual button
			var fbtn = Exams.ResultFixer.FixAllBtn[Exams.ResultFixer.FixCurrent];
			while (typeof fbtn == _UND && Exams.ResultFixer.FixCurrent < Exams.ResultFixer.FixAllTotal) { //if btn not exist go to the next
				Exams.ResultFixer.FixCurrent++;
				fbtn = Exams.ResultFixer.FixAllBtn[Exams.ResultFixer.FixCurrent];
			}
			if (typeof fbtn != _UND) {
				fixallbtn.style.display = 'none';
				Exams.ResultFixer.FixAllStatus = "Play";
				_('cntrbtnfixall').Show();
				Exams.ResultFixer.IndFixer(fbtn, true);
			} else {
				MessageBox.Show("No Valid Troubleshooted Student Found");
				_('resultfixtitle').innerHTML = temptitle;
			}

		},


		//Individual fixer
		IndFixer: function (obj, fixall) {
			fixall = fixall || false;
			//check if a valid button
			if (typeof obj == _UND || typeof obj.id == _UND) return;
			var btnid = obj.id;

			//get the regno
			var idarr = btnid.split("_");
			if (idarr.length == 2) {
				var regno = idarr[0];
				if (typeof Exams.ResultFixer.IndFixAjax[regno] != _UND && Exams.ResultFixer.IndFixAjax[regno] != null) {
					Exams.ResultFixer.IndFixAjax[regno].abort();
				}
				if (fixall) _('resultfixtitle').innerHTML = '<strong>' + (Exams.ResultFixer.FixCurrent + 1) + ' of ' + Exams.ResultFixer.FixAllTotal + '</strong> - Fixing (' + regno + ') Result<small>(s)</small> ...';
				//indicate loading in the button
				obj.disabled = true;
				obj.innerHTML = '<i class="fa fa-spin fa-cog"></i>';
				//send regno to database
				Exams.ResultFixer.IndFixAjax[regno] = new Ajax();
				Exams.ResultFixer.IndFixAjax[regno].Post({
					PostData: "RegNo=" + escape(regno) + "&Type=1" + "&RstInfoID=" + Exams.ResultFixer.DefaultRInfoID + "&Num=-1&fixall=" + (fixall ? 1 : 0) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/fix.php",
					OnProgress: function (delta) {

					},
					OnComplete: function (res, url, param) {
						if (!Login.Authenticate(res)) return;
						Exams.ResultFixer.IndFixAjax[regno] = null;
						//get the regno
						var regno = param['RegNo'];
						//get the container
						var cont = _(regno + "_det");
						if (cont != null) {
							// alert(res);
							//pupulate the detail container
							cont.innerHTML = res;
						}
						var obj = _(regno + "_fixbtn");
						//enable fix button
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-check"></i>';
						var fall = param['fixall'].ToNumber();
						//alert(param['fixall']);
						if (fall == 1) { //if called from fixall
							Exams.ResultFixer.FixCurrent++; //increment current
							if (Exams.ResultFixer.FixCurrent == Exams.ResultFixer.FixAllTotal || Exams.ResultFixer.FixAllStatus == "Stop") { //if no more 
								if (Exams.ResultFixer.FixAllStatus == "Stop") {
									_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixCurrent + ' of ' + Exams.ResultFixer.FixAllTotal + ' - <span  class="err">Fixing Process Stoped</span></strong>';
								} else {
									_('resultfixtitle').innerHTML = '<strong class="ok">' + Exams.ResultFixer.FixCurrent + ' Student<small>(s)</small> Fixed Successfully</strong>';
								}

								Exams.ResultFixer.FixCurrent = Exams.ResultFixer.FixAllTotal = 0; //reset
								Exams.ResultFixer.FixAllBtn = [];
								_('fixallbtn').style.display = 'inline-block';
								_('cntrbtnfixall').style.display = 'none';
								Exams.ResultFixer.FixAllStatus = "Stop";
							} else if (Exams.ResultFixer.FixAllStatus == "Pause") { //if to be paused
								_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixCurrent + ' of ' + Exams.ResultFixer.FixAllTotal + ' - <span class="altColor2">Fixing Process Paused</span></strong>';
								_('fixallpausebtn').style.display = 'none';
								_('fixallplaybtn').style.display = 'inline-block';
								//_('cregallpausebtn').disabled = false;

							} else {
								//fix next student
								Exams.ResultFixer.FixNext();
							}



						}
					},
					OnAbort: function (res, url, param) {
						//enable fix button
						var regno = param['RegNo'];
						var obj = _(regno + "_fixbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-wrench"></i>';
						var fall = _.ToNumber(param['fixall']);
						if (fall == 1) { //if called from fixall
							_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixCurrent + ' Student<small>(s)</small> Fixed Successfully</strong> - <span class="err">Process Aborted</span>';
							Exams.ResultFixer.FixCurrent = Exams.ResultFixer.FixAllTotal = 0; //reset
							Exams.ResultFixer.FixAllBtn = [];
							_('fixallbtn').style.display = 'inline-block';
							_('cntrbtnfixall').style.display = 'none';
							Exams.ResultFixer.FixAllStatus = "Stop";
						}
					},
					OnError: function (res, url, param) {
						//enable fix button
						var regno = param['RegNo'];
						var obj = _(regno + "_fixbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-wrench"></i>';
						var fall = _.ToNumber(param['fixall']);
						if (fall == 1) { //if called from fixall
							_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixCurrent + ' Student<small>(s)</small> Fixed Successfully</strong> - <span class="err">Error</span>';
							Exams.ResultFixer.FixCurrent = Exams.ResultFixer.FixAllTotal = 0; //reset
							Exams.ResultFixer.FixAllBtn = [];
							_('fixallbtn').style.display = 'inline-block';
							_('cntrbtnfixall').style.display = 'none';
							Exams.ResultFixer.FixAllStatus = "Stop";
						}
					}
				})
			}

		},
		//FixNext
		FixNext: function () {
			var fbtn = Exams.ResultFixer.FixAllBtn[Exams.ResultFixer.FixCurrent];
			while (typeof fbtn == _UND && Exams.ResultFixer.FixCurrent < Exams.ResultFixer.FixAllTotal) { //if btn not exist go to the next
				Exams.ResultFixer.FixCurrent++;
				fbtn = Exams.ResultFixer.FixAllBtn[Exams.ResultFixer.FixCurrent];
			}
			if (typeof fbtn != _UND) { //if btn found
				Exams.ResultFixer.IndFixer(fbtn, true);
			} else { // if not found
				_('resultfixtitle').innerHTML = '<strong class="ok">' + Exams.ResultFixer.FixCurrent + ' Student<small>(s)</small> Fixed Successfully</strong>';
				Exams.ResultFixer.FixCurrent = Exams.ResultFixer.FixAllTotal = 0; //reset
				Exams.ResultFixer.FixAllBtn = [];
				_('fixallbtn').style.display = 'inline-block';
				_('cntrbtnfixall').style.display = 'none';
				Exams.ResultFixer.FixAllStatus = "Stop";
			}
		},
		//FixAll Controls
		//Stop
		FixAllStop: function () {
			//if playing or paused
			if (Exams.ResultFixer.FixAllStatus != "Stop") {
				if (Exams.ResultFixer.FixAllStatus == "Pause") { //if currently paused
					_('resultfixtitle').innerHTML = '<strong>' + Exams.ResultFixer.FixCurrent + ' of ' + Exams.ResultFixer.FixAllTotal + ' - <span class="err">Fixing Process Stoped</span></strong>';
					Exams.ResultFixer.FixCurrent = Exams.ResultFixer.FixAllTotal = 0; //reset
					Exams.ResultFixer.FixAllBtn = [];
					_('fixallbtn').style.display = 'inline-block';
					_('cntrbtnfixall').style.display = 'none';
					_('fixallplaybtn').style.display = 'none';
					_('fixallpausebtn').style.display = 'inline-block';
					Exams.ResultFixer.FixAllStatus = 'Stop';
				} else {
					Exams.ResultFixer.FixAllStatus = 'Stop';
					_('resultfixtitle').innerHTML = 'Stoping ...';
				}



				//_('fixallpausebtn').disabled = true;
			}

		},
		//Pause
		FixAllPause: function () {
			//if paused
			if (Exams.ResultFixer.FixAllStatus == "Play") {
				Exams.ResultFixer.FixAllStatus = 'Pause';
				_('resultfixtitle').innerHTML = 'Pausing ...';
				//_('fixallpausebtn').disabled = true;
			}

		},
		//Play
		FixAllPlay: function () {
			//if paused
			if (Exams.ResultFixer.FixAllStatus == "Pause") {
				Exams.ResultFixer.FixAllStatus = 'Play';
				_('resultfixtitle').innerHTML = 'Resuming ...';
				_('fixallplaybtn').style.display = 'none';
				_('fixallpausebtn').style.display = 'inline-block';
				//fix next student
				Exams.ResultFixer.FixNext();
			}

		}

	},

	ResultSetting: {
		Ajax: new Ajax(),
		//Toogle the PrePament display
		TogglePaySel: (sw) => {
			var swst = sw.GetStatus();
			var prepaybx = _('selprepaybx');
			if (swst == 1) {
				prepaybx.Show();
			} else {
				prepaybx.Hide();
			}
		},
		//Add Predefined Method
		Save: function () {
			//get the selected Preset
			var selectedPresetName = DropDownLine.Selected('rpreset').Text;
			OptionBox.Show({
				Title: "Save Result Settings",
				Logo: "cogs",
				TitleHTML: '<table class="tbl rwb greyShadow" style="width:95%;font-size:0.8em;margin:auto" bordercolor="#CCCCCC" border="1"><tr class=""  ><th style="text-align:left">Save As</th><th  class="altColor2" style="font-size:1.2em">' + selectedPresetName + '</th></tr></table><div style="font-size:0.7em;padding:10px" class="altColor"><i>(Confirm Preset before Continuing)</i></div>',
				Options: [
					{
						Title: "Continue",
						Info: "Save Settings as " + selectedPresetName,
						Logo: "save",
						Function: () => {
							_('grprstsetfrm').submit();
						}
					}
				]
			});

			//Save code
		},

		PerformSave: function () {

			if (Page.ValidateText("rstsetgrpelem")) {
				var data = {};
				/* data['paycheckStatus'] = _('paycheckStatus').GetStatus();
				data['paycheckID'] = _('paycheckID').ValueContent();
				if(data['paycheckStatus'] == 1 && data['paycheckID'] == 0){
					MessageBox.Show("Select a Valid Payment Verification Type");
					return;
				} */
				//alert(Page.DataString("rstsetgrpelem"));return;
				data['TextData'] = Page.DataString("rstsetgrpelem");
				//alert(data['TextData']);
				data['gradesprsheet'] = _('gradesprsheet').GetDataString();
				data['classpsprsheet'] = _('classpsprsheet').GetDataString();
				data['grstrsprsheet'] = _('grstrsprsheet').GetDataString();
				data['clspstrsprsheet'] = _('clspstrsprsheet').GetDataString();
				data['rstrptsetsprsheet'] = _('rstrptsetsprsheet').GetDataString();
				data['rstattrsprsheet'] = _('rstattrsprsheet').GetDataString();
				data['scrstrsprsheet'] = _('scrstrsprsheet').GetDataString();
				data['rpreset'] = DropDownLine.Selected('rpreset').Value;
				if (data['rpreset'] == "-1") {
					MessageBox.Show("NO PRESET SET CREATED"); return;
				}

				Exams.ResultSetting.Ajax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/savesett.php",
					PostData: "data=" + escape(JSON.stringify(data)) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(Math.floor(delta * 45));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						MessageBox.Show(res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(100);
					},
					OnAbort: function (res) {

						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("Opeartion Aborted");');
					},
					OnError: function (res) {
						//MessageBox.Show("".res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR:' + res.Replace('"', '\"') + '");');
					}
				});
				//alert("1data="+escape(JSON.stringify(data)));
			} else {
				MessageBox.Show('All Fields are Required');
			}
		},
		ToFloat: function (obj) {
			var objid = obj.id.split("_")[3];
			if (objid == 'ScrStrTotal') {
				var max = Number(obj.textContent);
				//if(isNaN(max))
				max = (isNaN(max) || max < 1) ? "0.00" : max.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
				obj.textContent = (max + "").Replace(",", "");
			}
			//
			//alert(objid);
		},
		Load: SetID => {

			if (SetID == '0') {
				//Create New Preset

				//console.log(Options);
				OptionBox.Show({
					Title: "Create New Preset",
					//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
					TitleHTML: OptionBox.TextBox({ id: 'newrstpreste', logo: 'cogs', title: 'Preset Name', type: 'text' }),
					Options: [
						{
							Title: "Create",
							Info: "Create a New Preset",
							Logo: "plus",
							Function: function () {
								Exams.ResultSetting.CreatePreset(_('newrstpreste').TextContent());
							}
						}
					]
				});
				//settingbox.innerHTML = '';
				return;
			}

			//load the preset
			Exams.ResultSetting.LoadPreset(SetID);
		},
		PresetAjax: new Ajax,
		CreatePreset: PresetName => {
			var settingbox = _('rstsetbox');
			if (PresetName.Trim() == "") {
				MessageBox.Show("#INVALID PRESET NAME");
				return;
			}
			Exams.ResultSetting.PresetAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/setting_create_preset.php",
				PostData: "PresetName=" + encodeURIComponent(PresetName) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(Math.floor(delta * 45));
				},
				OnComplete: function (res) {
					//if(!Login.Authenticate(res))return;
					var fchar = res.substr(0, 1);
					if (fchar == "#") {
						MessageBox.Show(res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
					} else {
						MessageBox.Show("*PRESET CREATED SUCCESSFULLY");
						settingbox.innerHTML = res;
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(100);
					}

				},
				OnAbort: function (res) {
					MessageBox.Show("Opeartion Aborted");
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				},
				OnError: function (res) {
					MessageBox.Show("".res);
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				}
			})
		},
		LoadPreset: PresetID => {
			var settingbox = _('rstsetbox');
			Exams.ResultSetting.PresetAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/setting_load_preset.php",
				PostData: "PresetID=" + encodeURIComponent(PresetID) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(Math.floor(delta * 45));
				},
				OnComplete: function (res) {
					//if(!Login.Authenticate(res))return;
					var fchar = res.substr(0, 1);
					if (fchar == "#") {
						MessageBox.Show(res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
					} else {
						//MessageBox.Show("*PRESET CREATED SUCCESSFULLY");
						settingbox.innerHTML = res;
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(100);
					}

				},
				OnAbort: function (res) {
					MessageBox.Show("Opeartion Aborted");
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				},
				OnError: function (res) {
					MessageBox.Show("".res);
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				}
			})
		},
		LoadMenu: function (obj) {
			var GroupID = obj.ValueContent();
			// TextBox.Load("rstsubmenudd", configdata.Core+"cportal/Pages/Scripts/Exams/getrstsubmenu.php?GroupID=" + escape(GroupID) + "&SubDir=" + encodeURIComponent(configdata.SubDir));
			TextBox.Load("rstsubmenudd", "ID", "Name", "GroupID=" + GroupID + "", "new_apply_tb");
		},
		Edit: obj => {
			if (obj == 0) return false;
			OptionBox.Show({
				Title: "Manage Preset",
				//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Exams/loadpresetnm.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&PrID=" + obj },
				Options: [
					{
						Title: "Update",
						Info: "Update Preset Name",
						Logo: "edit",
						Function: function (PID) {
							Exams.ResultSetting.UpdatePreset(_('updaterstpreste').TextContent(), PID);
						},
						Parameter: obj
					},
					{
						Title: "Load",
						Info: "Load Preset",
						Logo: "cogs",
						Function: function (PID) {
							Exams.ResultSetting.LoadPreset(PID);
						},
						Parameter: obj
					},
					{
						Title: "Delete",
						Info: "Delete Preset",
						Logo: "trash",
						Function: function (PID) {
							Exams.ResultSetting.DeletePreset(PID);
						},
						Parameter: obj
					}
				]
			});
			return false;
		},
		UpdatePreset: (PresetName, PID) => {
			var settingbox = _('rstsetbox');
			if (PresetName.Trim() == "") {
				MessageBox.Show("#INVALID PRESET NAME");
				return;
			}
			Exams.ResultSetting.PresetAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/setting_create_preset.php",
				PostData: "PresetName=" + encodeURIComponent(PresetName) + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&PID=" + PID,
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(Math.floor(delta * 45));
				},
				OnComplete: res => {
					//if(!Login.Authenticate(res))return;
					var fchar = res.substr(0, 1);
					if (fchar == "#") {
						MessageBox.Show(res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
					} else {
						MessageBox.Show("*PRESET NAME UPDATED SUCCESSFULLY");
						_('rpreset_' + PID).textContent = PresetName;
						//settingbox.innerHTML = res;
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(100);
					}

				},
				OnAbort: function (res) {
					MessageBox.Show("Opeartion Aborted");
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				},
				OnError: function (res) {
					MessageBox.Show("".res);
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				}
			})
		},
		DeletePreset: PID => {
			OptionBox.Show({
				Title: "Delete Preset",
				//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Exams/loadpresetnm.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&PrID=" + PID + "&isdelete=1" },
				Options: [

					{
						Title: "Continue",
						Info: "Continue Delete Anyway",
						Logo: "trash",
						Function: function (PID) {
							Exams.ResultSetting.RealDeletePreset(PID);
						},
						Parameter: PID
					}
				]
			});
		},
		RealDeletePreset: PID => {
			Exams.ResultSetting.PresetAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/presetdel.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&PID=" + PID,
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(Math.floor(delta * 45));
				},
				OnComplete: res => {
					//if(!Login.Authenticate(res))return;
					var fchar = res.substr(0, 1);
					if (fchar == "#") {
						MessageBox.Show(res);
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
					} else {
						MessageBox.Show("*PRESET REMOVED");
						var pdis = _('rpreset_' + PID);
						pdis.parentElement.removeChild(pdis);
						//settingbox.innerHTML = res;
						Tabs.Tab("Exams").ProgressGet(4).ProgressTo(100);
					}

				},
				OnAbort: function (res) {
					MessageBox.Show("Opeartion Aborted");
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				},
				OnError: function (res) {
					MessageBox.Show("".res);
					Tabs.Tab("Exams").ProgressGet(4).ProgressTo(-1);
				}
			})
		}

	},

	RstLedger:{
		LoadLedger:(obj)=>{
			if (typeof obj == 'undefined') {
				_('studentledgerdefault').Hide();
				_('studledgerfrm').Show();
				return;
			}
			//#Loading Student'.__()
			//Start Student Data Loading'.__()
			//alert(obj.Text());return;
			var RegNo = obj.Data("id");
			//alert(RegNo);
			RegNo = RegNo.Trim();
			//	Student.BioData.StartLoadStudent(RegNo);
			Exams.RstLedger.LoadLedgerReal(RegNo);
		},
		LoadLedgerAjax: new Ajax(),
		LoadLedgerReal:(RegNo)=>{
			if(RegNo && Trim(RegNo) === '') return;
			let datastr = "RegNo="+encodeURIComponent(RegNo);
			Exams.RstLedger.LoadLedgerAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadstudledger.php",
				PostData: datastr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Exams").ProgressGet(6).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					_('studledgerfrm').innerHTML = res;

					Tabs.Tab("Exams").ProgressGet(6).ProgressTo(100);
					
					_('studentledgerdefault').Hide();
				_('studledgerfrm').Show();
					Tabs.HideSideBar("Exams", 6);
					//alert(_('rstinfobs').value);
					//_('rstrptcontdiv').FadeIn(200);

				},
				OnAbort: function () {
					Tabs.Tab("Exams").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					_('studledgerfrm').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>Operation Aborted</small>", 'altColor');
				},
				OnError: function (res) {
					Tabs.Tab("Exams").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
					_('studledgerfrm').innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle", "Hoops !!!! </br><small>" + "Internal Error: " + res + "</small>", 'danger-text');
				}
			})
		},
		PrintAjax: new Ajax(),
	Print: function () {
		var reqired = _("loadedRegNo");
		if (reqired == null) {
			MessageBox.Show("Invalid Selection: Search and Select a Student");
			return;
		}/* OptionBox.TextBox({id:'techcodetb',logo:'unlock',title:'Technical Personel ID (TPID)',type:'password'}) */
		Exams.RstLedger.PrintAjax.Post({
			Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/loadreports.php",
			PostData: "SubDir=" + encodeURIComponent(configdata['SubDir'])+"&Marker=ResultLedgerSheet",
			OnProgress: function (delta) {
				Tabs.Tab("Exams").ProgressGet(6).ProgressTo(Math.floor(delta * 95));
			},
			OnComplete: function (res) {
				if (!Login.Authenticate(res)) return;
				//console.log(res);
				var reports = JSON.parse(res);
				//console.log(reports);
				var Options = [];
				if (reports) {
					for (var d = 0; d < reports.length; d++) {
						var indrp = reports[d];
						Options.push(
							{
								Title: indrp.Title,
								Info: indrp.Descr,
								Logo: indrp.Logo,
								Function: function (param) {
									param[0] += "&utitle=" + escape(_('sheettit').TextContent());
									Exams.RstLedger.PrintReal(param[0], param[1], param[2]);
								},
								Parameter: [indrp.Param, indrp.Script, indrp.ID]
							}
						);
					}
					//console.log(Options);
					OptionBox.Show({
						Title: "Select Sheet Type",
						//TitleHTML: TextBox.Form({ id: "sheettit", title: "Result Sheet Title", logo: "font", info: "For Main Result Sheet Only", style: "width:inherit" }),
						TitleHTML: OptionBox.TextBox({ id: 'sheettit', logo: 'font', title: 'Sheet Title', type: 'text' }),
						Options: Options
					});
				} else {
					MessageBox.Show("No Report Set");
				}
				Tabs.Tab("Exams").ProgressGet(6).ProgressTo(100);
				//alert(_('rstinfobs').value);
				//_('rstrptcontdiv').FadeIn(200);

			},
			OnAbort: function () {
				Tabs.Tab("Exams").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

			},
			OnError: function (res) {
				Tabs.Tab("Exams").ProgressGet(6).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
				//MessageBox.Show("" + res);

			}
		})

		// _('rstrptcontdiv').FadeOut(200);

		// MessageBox.Show(datastr);
	},
	PrintReal: function (param, script, ReportID) {
		//typee = (typeof typee == _UND) ? "main" : typee;
		var RegNo = _("loadedRegNo").textContent;
		 
		var datastr = "RegNo=" + encodeURIComponent(RegNo) + "&" + param + "&ReportID=" + ReportID ;
		var fname = datastr.Replace("=", "");
		fname = fname.Replace("&", "");
		var signparam = { "RegNo": RegNo, "ReportID": ReportID };
		datastr += "&sigparam=" + encodeURIComponent(JSON.stringify(signparam));
		
		 var action = [{ "Action": 'Exams.RstLedger.Sign(\'' + escape(JSON.stringify(signparam)) + '\')', "Logo": "pencil", "Title": "Append Signature", "DisplayText": "Sign" }];
		scriptarr = script.split("/"); 
		if (scriptarr[0] == "Reports") { //for old script url
			script = configdata.Core + "cportal/" + script;
		}
		PDFPrinter.Print(script, datastr, "Ledger_" + fname + ".pdf",action); 
	},
	SignAjax: new Ajax(),
	Sign: function (signparam) {
		//alert(signparam);
		//get the report signatures
		Exams.RstLedger.SignAjax.Post({
			OnComplete: function (res, url, para) {
				if (res.Trim() != "") {
					//alert(res);
					var resobj = JSON.parse(res);
					if (typeof resobj.Error != _UND) {
						MessageBox.Show("#" + resobj.Error); return;
					}

					if (typeof resobj.Signatories != _UND) {
						//signatories found
						//form Signatory Options
						var Options = [];
						for (var dd = 0; dd < resobj.Signatories.length; dd++) {
							var sig = resobj.Signatories[dd];
							Options.push({
								Title: sig.Title,
								Info: "Sign Report as " + sig.Title,
								Logo: "pencil",
								Function: function (param) {
									var sigdet = escape(JSON.stringify(param[0]));
									var reportparam = param[1];
									/* var userdet = Login.User();
										if (userdet == null) { MessageBox.Show("User Identification Failed"); return; }
										var userID = userdet[0]; */
									var usertb = _('SigUserName');
									if (usertb == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Username Field"); return; }
									usernm = usertb.TextContent();
									if (usernm.Trim() == "") { MessageBox.Show("Invalid Signatory Username"); return; }

									//Password
									var usertbpw = _('SigPassw');
									if (usertbpw == null) { MessageBox.Show("Error on Page. Cannot Locate Signatory Password Field"); return; }
									usernmpw = usertbpw.TextContent();
									if (usernmpw.Trim() == "") { MessageBox.Show("Invalid Signatory Password"); return; }

									Exams.RstLedger.PerformSign(sigdet, reportparam, [usernm, usernmpw]);
								},
								Parameter: [sig, para['param']]
							});
						}
						OptionBox.Show({
							Title: "Append Signature",
							TitleHTML: resobj.HTML,
							Logo: "pencil",
							Options: Options
						});
						return;
					}
				}
				MessageBox.Show("#Invalid Response");

				//alert(res);
			},
			OnError: function (res) {
				MessageBox.Show("#Internal Error - " + res);
			},
			PostData: "param=" + signparam + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
			Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php"
		});

	},
	PSignAjax: new Ajax(),
	PerformSign: function (sigdet, reportparam, userDet) {

		Exams.RstLedger.PSignAjax.Post({
			PostData: "SignDet=" + sigdet + "&ReportDet=" + reportparam + "&UserName=" + escape(userDet[0]) + "&UserPassw=" + escape(userDet[1]) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
			Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Exams/signatory.php",
			OnComplete: function (res) {
				var resobj = JSON.parse(res);
				if (typeof resobj.Error != _UND) {
					MessageBox.Show(resobj.Error);
					return;
				}

				//regenerate the report
				PDFPrinter.Preview();
			},
			OnError: function (res) {
				MessageBox.Show("Internal Error: " + res);
			}
		});
	}
	},
	

}

//Schoo Object 
var School = {
	Staff: {
		Ajax: new Ajax(),
		Grpweight: [10, 30, 60, 80, 99],
		Grpid: ["staffbinfo", "staffpasspgrp", "staffschdet", "staffDeptsGrp", "staffCoursesGrp", "staffsiggrp"],
		CurGrp: 0,
		Load: function (obj) {
			var hometxt = _('staffhome');
			if (hometxt.style.display != "none") { //if home welcome display
				hometxt.Hide();
				_('grpobjstafffrm').Show();
				if (typeof obj == 'undefined') return;
			}

			if (typeof obj == 'undefined') {
				School.Staff.Clear();
				return;
			}
			//"Enter Load".__();
			var stid = obj.Data("id");
			var rwid = obj.id;
			if (stid.ToNumber() < 1) { MessageBox.Show("#INVALID PARAMETER"); return; }
			School.Staff.Reload(stid, 0);
		},
		Reload: function (stid, grp) {
			if (typeof School.Staff.Grpid[grp] != _UND) {
				_(School.Staff.Grpid[grp]).Animate({ CSSRule: "opacity:0.8", Time: 300, EndAction: "School.Staff.PerformLoad(" + stid + "," + grp + ")", DoAt: 1 });
			}
		},
		PerformLoad: function (stid, grp) {
			if (grp == 4) { _("courselecbx").FadeOut(300); }
			if (grp == 3) { _("deptsbx").FadeOut(300); }
			School.Staff.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/loadstaff.php",
				PostData: "stid=" + escape(stid) + "&Grp=" + grp + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta, url, param) {
					/*var grpPriv = param['Grp'].ToNumber() - 1;
					if(grpPriv  < 0){
						var privwe = 0;
					}else{
					
						var privwe = School.Staff.Grpweight[grpPriv];
					}
					 Tabs.Tab("School").ProgressGet(6).ProgressTo(Math.floor(delta * School.Staff.Grpweight[param['Grp'].ToNumber()]) + privwe);*/
					//Tabs.Tab("Exams").ProgressGet(0).ProgressTo(Math.floor(delta*90));
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					// res.__();
					$stchar = res.substr(0, 1);
					if ($stchar == "*") {
						var NGrp = param['Grp'].ToNumber();
						var datstr = res.substr(1);
						if (NGrp < 3 || NGrp == 5) {

							var datarr = datstr.ToDataArray();
						}

						//param['Grp'].__();_("courselecbx").FadeOut(300)
						switch (NGrp) {
							case 0: //basic info
								//CoverScreen.Show("loadfirst", "Working ..", function () {

								_("stuserId").value = datarr['UserID'];
								_("staffFullnme").SetText(datarr['StaffName']);
								_('staffDOB').SetText(Utility.FromMySqlDate(datarr['DOB']));
								_("staffstateorig").SetText(datarr['StateID'], "staffstateoriglga:" + datarr['LGAID']);
								_("staffnat").SetText(datarr['Nat']);
								_("staffemail").SetText(datarr['Email']);
								_("staffphone").SetText(datarr["Phone"]);
								_("staffemmg").SetText(datarr["Emergency"]);
								_("staffaddr").SetText(datarr["Addrs"]);
								//	CoverScreen.Close(_("loadfirst"));
								//});

								break;
							// case 1: //contact
							//_("studstudy").SetText(resarr[2],"studfac:"+resarr[3]+";studdept:"+resarr[4]+";studprog:"+resarr[5]+";studlvl:"+resarr[6]);_("modeentry").SetText(resarr[7]);
							/*_("staffstateorig").SetText(datarr['StateID'],"staffstateoriglga:"+datarr['LGAID']);
							_("staffnat").SetText(datarr['Nat']);
							_("staffemail").SetText(datarr['Email']);
							_("staffphone").SetText(datarr["Phone"]);
							_("staffemmg").SetText(datarr["Emergency"]);
							_("staffaddr").SetText(datarr["Addrs"]);*/
							// break;

							case 1://passport
								var UserID = datarr['UserID'];
								//alert(datarr['Sig']);
								_('staffpasspd').SetPadImage("Files/UserImages/" + UserID + ".jpg");
								break;
							case 2: //School 
								_('staffposition').SetText(datarr['Rank']);
								_('staffIDSch').SetText(datarr['StaffSchID']);
								_('staffunit').SetText(datarr['StaffUnit']);
								_('staffqual').SetText(datarr['EduQual']);
								var priv = datarr['Priv'].ToNumber();
								//datarr['Priv'].__();
								if (priv > 0) { _('staffrstup').SwitchOn() } else { _('staffrstup').SwitchOff() }
								break;
							case 3: //courses 
								// datstr.__();
								_("deptsbx").innerHTML = datstr;
								_("deptsbx").FadeIn(300)
								break;
							case 4: //courses 
								// datstr.__();
								_("courselecbx").innerHTML = datstr;
								_("courselecbx").FadeIn(300)
								break;

							case 5: //courses 
								// datstr.__();
								var Sign = datarr['Sig'];
								//alert(datarr['Sig']);
								if (Sign.Trim() == "") {
									_('staffsigpd').ClearImagePad();
								} else {
									Signarr = Sign.split("/");
									_('staffsigpd').SetPadImage("Files/UserImages/" + Signarr[Signarr.length - 1]);
								}

								break;

						}
						//Basic Deteails
						/* 
	   
						 //Contact
						 //_("studstudy").SetText(resarr[2],"studfac:"+resarr[3]+";studdept:"+resarr[4]+";studprog:"+resarr[5]+";studlvl:"+resarr[6]);_("modeentry").SetText(resarr[7]);
						 _("staffstateorig").SetText(datarr['StateID'],"staffstateoriglga:"+datarr['LGAID']);
						}else{
						MessageBox.Show(res);*/

					} else {
						MessageBox.Show(res);
					}
					var grpnum = param['Grp'].ToNumber();
					Tabs.Tab("School").ProgressGet(6).ProgressTo((grpnum * 20));
					var nwgrp = grpnum + 1;
					_(School.Staff.Grpid[param['Grp']]).Animate({ CSSRule: "opacity:1", Time: 300, EndAction: "School.Staff.Reload(" + param['stid'] + "," + nwgrp + ")", DoAt: 1 });
					Tabs.HideSideBar("School", 6);
					//School.Staff.CurGrp++;



				}, OnAbort: function (res) {
					MessageBox.Show("Operation Aborted");
				},
				OnError: function (res) {
					MessageBox.Show("#INTERNAL EROR: " + res);
				}
			});
		}, Save: function () {
			//alert("save");
			_('grpobjstafffrm').submit();
		},
		SaveAjax: new Ajax(),
		//Perform Save 
		PerformSave: function () {
			//validate input 
			if (Page.ValidateText("objgrpstaffelem")) {
				//validate passport
				if (!_('staffpasspd').IsSet()) {
					MessageBox.Show("INVALID PASSPORT PHOTOGRAPH");
					return;
				}
				//get current staff from search box 
				var sb = _('staffsearch');
				//alert();
				var staffID = sb == null ? 0 : sb.SelectedDataID().ToNumber();
				//alert(staffID);
				var postSave = function (staffID) {
					//get all user data
					var datas = Page.DataString("objgrpstaffelem");
					//alert(datas);

					var GetColumnData = function (spsid, collnum) {
						staffCourses = "";
						var courses = _(spsid).GetDataString();
						if (courses.Trim() != "") {
							var maxrow = DataString.Get(courses, "MaxDataRow").ToNumber();
							//console.log(collnum);
							collnum = Array.isArray(collnum) ? collnum : [collnum];
							//console.log(collnum);
							if (maxrow > 0) {
								for (var d = 1; d <= maxrow; d++) {
									var deleted = DataString.Get(courses, d + "_deleted");
									if (deleted == "true") continue;
									var courseIDs = collnum.map(indcol => {
										//console.log(indcol);
										return DataString.Get(courses, d + "_" + indcol);
									})
									//var courseID = DataString.Get(courses, d + "_" + collnum);
									var courseID = courseIDs.join(":");
									if (courseID.Trim() != "") {
										staffCourses += courseID + "~";
									}
								}
								staffCourses = staffCourses.TrimRight("~");
							}

						}
						return staffCourses;
					}
					staffPCourses = GetColumnData('staffcourses', [8, 5]);
					//console.log(staffPCourses);
					staffDept = GetColumnData('staffdepts', 3);
					//alert(staffDept)
					datas += "&courses=" + escape(staffPCourses) + "&depts=" + escape(staffDept) + "&staffid=" + staffID + "&stuserId=" + _('stuserId').value;
					//datas.__();
					//console.log(datas);
					//return;
					//Post data to server
					School.Staff.SaveAjax.Post({
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/staffupd.php",
						PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnProgress: function (delta) {
							Tabs.Tab("School").ProgressGet(6).ProgressTo(Math.floor(delta * 95));
						},
						OnComplete: function (res) {
							if (!Login.Authenticate(res)) return;
							var resarr = res.split("`_`");
							if (resarr.length > 1) {
								_("stuserId").value = resarr[1];
							}
							res = resarr[0];
							//MessageBox.Show(res);
							Tabs.Tab("School").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
						},
						OnAbort: function (res) {
							//

							Tabs.Tab("School").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
						},
						OnError: function (res) {
							//
							Tabs.Tab("School").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
							//MessageBox.Show("" + res);
						}
					})
					//alert(datas);
				}
				if (staffID == 0) { //if new Staff
					OptionBox.Show({
						Title: "ADD NEW STAFF",
						Options: [
							{
								Title: "Add New Staff",
								Logo: "plus",
								Info: "Add a new Staff",
								Function: postSave,
								Parameter: staffID
							},
							{
								Title: "Cancel",
								Logo: "times",
								Info: "Terminate Operation"
							}
						]
					})
				} else {
					postSave(staffID);
				}
				//alert(staffID);
			} else {
				MessageBox.Show("INVALID ENTERING FOUND");
			}
		},
		Clear: function () {
			CoverScreen.Show("covv", "Working ...", function (obj) {
				_("textBx & objgrpstaffelem ~ staffsearchsearchtxt").ClearText(); //clear all textbox 
				_("staffaddr staffqual").ClearPad(); //clear all textpad 
				_("stuserId").value = ""; //clear the userid 
				_("staffsearchrefreshsearch").click();//deselect the search box;
				_("staffrstup").SwitchOff(); //switch off the Result Upload switch 
				_("staffpasspd").ClearImagePad(); //clear the image pad
				_("staffsigpd").ClearImagePad(); //clear the image pad
				_("staffcourses").ClearSpreadSheet();
				_("staffdepts").ClearSpreadSheet();
				CoverScreen.Close(_('covv'));
			});
			/* */
		}
		, Copy: () => {
			var sb = _('staffsearch');
			//alert();
			var staffID = sb == null ? 0 : sb.SelectedDataID().ToNumber();
			//check if a staff is selected
			if (staffID == 0) { //if new Staff
				OptionBox.Show({
					Title: "COPY ALL STAFF",
					Logo: "copy",
					Options: [
						{
							Title: "RCORDS",
							Logo: "users",
							Info: "Copy all Staff Record",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						}, {
							Title: "CONTACT",
							Logo: "address-book",
							Info: "Copy all Staff Name, Phone, email and Address",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						},
						{
							Title: "PHONE NUMBERS",
							Logo: "phone",
							Info: "Copy all Staff Phone Numbers",
							Function: staffID => {
								School.Staff.CopyReal(staffID, 'phone');
							},
							Parameter: staffID
						},
						{
							Title: "EMAIL ADDRESS",
							Logo: "envelope",
							Info: "Copy all Staff Email Address",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						}
					]
				});
			} else {
				OptionBox.Show({
					Title: "COPY STAFF",
					Logo: "copy",
					Options: [
						{
							Title: "RCORDS",
							Logo: "users",
							Info: "Copy Staff Record",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						}, {
							Title: "CONTACT",
							Logo: "address-book",
							Info: "Copy Staff Name, Phone, email and Address",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						},
						{
							Title: "PHONE NUMBER",
							Logo: "phone",
							Info: "Copy Staff Phone Number",
							Function: staffID => {
								School.Staff.CopyReal(staffID, 'phone');
							},
							Parameter: staffID
						},
						{
							Title: "EMAIL ADDRESS",
							Logo: "envelop",
							Info: "Copy Staff Email Address",
							Function: staffID => {
								MessageBox.Show("Operation Tempoarily not Available");
							},
							Parameter: staffID
						}
					]
				});
			}
		},
		CopyReal: (staffID, type) => {
			//type => record, contact, phone, email
			var datas = "StaffID=" + staffID + "&Type=" + type;
			School.Staff.SaveAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/copystaff.php",
				PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(6).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: res => {
					if (!Login.Authenticate(res)) return;
					res = JSON.parse(res);
					if (typeof res.Error != _UND) {
						MessageBox.Show(res.Error);
					} else {
						if (ClipBoard.CopyText('*' + res.Result)) {
							MessageBox.Show("*" + res.Message);
						} else {
							MessageBox.Show("#Copy Operation Failed");
						}
					}
					Tabs.Tab("School").ProgressGet(6).ProgressTo(100);
				},
				OnAbort: function (res) {
					//

					Tabs.Tab("School").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//
					Tabs.Tab("School").ProgressGet(6).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
				}
			})
		}
		, Print: function () {
			// if(Tabs.Tab("Users").ProgressGet(0).ProgressState() != 0){MessageBox.Show("System Busy, Try Again Later");return}
			//get selected user and validate it
			var selStaffID = "";
			var sbobj = _('staffsearch');
			if (sbobj != null) {
				var selobj = sbobj.SelectedObject(true);

				if (selobj != null) {
					selStaffID = selobj.Data("id").Trim();
				}
			}


			if (selStaffID == "") { //if no staff selected
				OptionBox.Show({
					Title: "Print All",
					Options: [{
						Logo: "print",
						Title: "Print",
						Info: "Print All School Staff Details",
						Function: function () {
							School.Staff.PerformPrint(0);
							//MessageBox.Show('All');
						}

						// Parameter:selUserID
					},
					{
						Logo: "list-alt",
						Title: "Print Template",
						Info: "Print a Staff Form Template",
						Function: function () {
							School.Staff.PerformPrint(-1);
							//MessageBox.Show('All');
						}

						// Parameter:selUserID
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort the Print Operation",
						Function: function () {
							MessageBox.Show("Print Operation Canceled");
						}
						//Parameter:selectedRegNo
					}]

				});
			} else {
				School.Staff.PerformPrint(selStaffID);
				//user selected
				//Users.Manage.PerformPrint(selUserID.ToNumber());
			}

		},
		PerformPrint: function (staffID) {
			if (staffID < 0) {
				PDFPrinter.Print(configdata.Core + "cportal/Reports/School/stafftemplate.php", "&paper=A4&orientation=P&MT=44&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir), 'staff_template' + ".pdf");
			} else {
				//alert(configdata.Core);
				PDFPrinter.Print(configdata.Core + "cportal/Reports/School/staffdetials.php", 'SID=' + staffID + "&paper=A4&orientation=P&MT=42&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir), 'Staff_' + staffID + ".pdf");
			}

			//MessageBox.Show(staffID);
		}


	},
	SchoolSettings: {

		Ajax: new Ajax(),
		//Add custom methods
		//perform the save operation
		PerformSave: function (perf) {
			perf = perf || false;
			if (!Page.ValidateText("objgrpssettingselem")) {
				MessageBox.Show("INVALID ENTERING");
				return;
			}
			//validate passport
			if (!_('schsetlogo').IsSet()) {
				MessageBox.Show("INVALID PASSPORT PHOTOGRAPH");
				return;
			}

			if (perf == false) { //
				migratest = _('schsetmigrate').GetStatus();
				if (migratest == 1) {
					OptionBox.Show({
						Title: "Auto Migration",
						TitleHTML: '<div class="altColor"><b>Note:</b> If School Type Changed, Current related record will be moved to New School Type (apply to empty records only)</div>',
						Logo: "share",
						Options: [{
							Logo: "thumbs-up",
							Title: "Continue",
							Info: "Move Related Records",
							Function: function () {
								School.SchoolSettings.PerformSave(true);
								//MessageBox.Show('All');
							}
						},
						{
							Logo: "times",
							Title: "Cancel",
							Info: "Abort the Operation",
							Function: function () {
								//MessageBox.Show("Print Operation Canceled");
							}
							//Parameter:selectedRegNo
						}]

					});
					return;
				}
			}

			var datas = Page.DataString("objgrpssettingselem");
			var sessds = _('schsessionspsh').GetDataString();
			var semds = _('schsemspsh').GetDataString();
			datas = datas + "&sess=" + escape(sessds) + "&sems=" + escape(semds);
			//alert(datas);return;
			School.SchoolSettings.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/saveset.php",
				PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(5).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//MessageBox.Show(res);
					//alert(res);
					//check res type
					var fchar = res.substr(0, 1);
					if (fchar == "*" || fchar == "#") {
						Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					} else {
						resmks = res.split('~~@@!!#@');
						//update the semester
						var disobj = _('schsemloadbx');
						if (disobj != null) {
							disobj.Hide();
							disobj.innerHTML = resmks[0];
							disobj.Show();
							//var titgrp = _('schSemGrp_title');
							//if(titgrp != null){
							semtitle = document.querySelector("#schSemGrp_title > span");
							if (semtitle != null) semtitle.textContent = resmks[2];
							//}
						}
						//sess
						var disobj1 = _('schsesloadbx');
						if (disobj1 != null) {
							disobj1.Hide();
							disobj1.innerHTML = resmks[1];
							disobj1.Show();
						}
						Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("*School Settings Saved Successfully");');
					}

				},
				OnAbort: function (res) {
					//
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');


				},
				OnError: function (res) {
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					//MessageBox.Show("" + res);
				}
			})
			//alert(datas);
			//alert('Save')
		},

		//Add Predefined Method
		Save: function () {
			//Save code
			_('grpobjssettingsfrm').submit();
		},
		Clear: function () {
			//clear code
			_("objgrpssettingselem").ClearText();
			_('schsetlogo').ClearImagePad();
			_('schsetloadlvl').SwitchOff();
			_('schsetdescr + schsetlongaddr').ClearPad();
		},
		Print: function () {
			PDFPrinter.Print(configdata.Core + "cportal/Reports/School/schooldet.php", "paper=A4&orientation=P&MT=45&MB=14", "school.pdf");
		},
		SetSession(SesID, SesName) {
			OptionBox.Show({
				Title: "Set As",
				TitleHTML: '<div class="altColor" style="width:300px"><b>Note:</b> This Session will be use accross the entire System where Current Academic Session is needed</div>',
				Logo: "exclamation-triangle",
				Options: [
					{
						Logo: "calendar",
						Title: "Curent",
						Info: "Set " + SesName + " as the School Current Session",
						Function: function (SesID) {
							School.SchoolSettings.PerformSetSession(SesID);
							//MessageBox.Show('All');
						},

						Parameter: SesID
					},
					{
						Logo: "university",
						Title: "Start",
						Info: "Set " + SesName + " as the School Start Session",
						Function: function (SesID) {
							School.SchoolSettings.PerformSetSession(SesID, 1);
							//MessageBox.Show('All');
						},

						Parameter: SesID
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort the Operation",
						Function: function () {
							//MessageBox.Show("Print Operation Canceled");
						}
						//Parameter:selectedRegNo
					}]

			});
		},

		PerformSetSession: function (SesID, asStart) {
			asStart = asStart || 0;
			School.SchoolSettings.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/setactiveses.php",
				PostData: "SesID=" + SesID + "&AsStart=" + asStart + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(5).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//break response to determine if success
					var resarr = res.split('@%7&^%');
					var mes = res;
					if (resarr.length > 1) {
						mes = resarr[0];
						//display new session sheet
						var disobj = _('schsesloadbx');
						if (disobj != null) {
							disobj.Hide();
							disobj.innerHTML = resarr[1];
							disobj.Show();
						}

					}
					//MessageBox.Show(mes);					
					//alert(res);
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("' + mes.Replace('"', '\"') + '");');
				},
				OnAbort: function (res) {
					//'MessageBox.Show("'+res.Replace('"','\"')+'");'

					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {

					//MessageBox.Show("" + res);
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
				}
			})
		},
		SetSem(SemID, SemName) {
			var semLabel = "Semester";
			var semLabelobj = _('schsemlabel_inp');
			//alert(semLabelobj);
			if (semLabelobj != null && semLabelobj.value.Trim() != "") {
				semLabel = semLabelobj.value;
			}
			OptionBox.Show({
				Title: "Set " + semLabel + " As",
				TitleHTML: '<div class="altColor" style="width:300px"><b>Note:</b> if Auto-' + semLabel + ' is Disabled in (Payment or Course Settings), This ' + semLabel + ' will be use accross the entire System where Current Academic ' + semLabel + ' is needed</div>',
				Logo: "exclamation-triangle",
				Options: [{
					Logo: "calendar",
					Title: "Current",
					Info: "Set " + SemName + " as Active " + semLabel,
					Function: function (SemID) {
						School.SchoolSettings.PerformSetSem(SemID);
						//MessageBox.Show('All');
					},

					Parameter: SemID
				}, {
					Logo: "university",
					Title: "Start",
					Info: "Set " + SemName + " as School Start " + semLabel,
					Function: function (SemID) {
						School.SchoolSettings.PerformSetSem(SemID, 1);
						//MessageBox.Show('All');
					},

					Parameter: SemID
				},
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Abort the Operation",
					Function: function () {
						//MessageBox.Show("Print Operation Canceled");
					}
					//Parameter:selectedRegNo
				}]

			});
		},

		PerformSetSem: function (SemID, asStart) {
			asStart = asStart || 0;
			School.SchoolSettings.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/setactivesem.php",
				PostData: "SemID=" + SemID + "&AsStart=" + asStart + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(5).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res) {
					//alert(res);
					if (!Login.Authenticate(res)) return;
					//break response to determine if success
					var resarr = res.split('@%7&^%');
					var mes = res;
					if (resarr.length > 1) {
						mes = resarr[0];
						//display new session sheet
						var disobj = _('schsemloadbx');
						if (disobj != null) {
							disobj.Hide();
							disobj.innerHTML = resarr[1];
							disobj.Show();
						}

					}
					//MessageBox.Show(mes);					
					//alert(res);
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("' + mes.Replace('"', '\"') + '");');
				},
				OnAbort: function (res) {
					//
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');


				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					Tabs.Tab("School").ProgressGet(5).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
				}
			})
		}

	},
	Structure: {
		Loading: false,
		Ajax: new Ajax(),
		Load: function (value, key, itemname, silentmode, rowcnt, setsilentmode) {
			if (School.Structure.Loading) return;
			silentmode = silentmode || 0;
			rowcnt = rowcnt || 0;
			setsilentmode = setsilentmode || -1; //if 0 or 1 will update the silent mode
			if (silentmode == 1 && rowcnt > 1) {
				MessageBox.Show("Only the First Record is valid in Silent Mode");
				return;
			}
			var sdata = _('schstrucdatabx').textContent;
			var loading = _('strucload');
			var loadingtitle = _('strucloadtitle');
			loadingtitle.textContent = itemname == 'a' ? "Schools" : itemname + " Structure";
			loading.Show();
			School.Structure.Loading = true;
			School.Structure.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/loadstructure.php",
				PostData: "Key=" + key + "&Value=" + value + "&Name=" + itemname + "&Data=" + escape(sdata) + "&SetSilentMode=" + setsilentmode + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					loading.Hide();
					School.Structure.Loading = false;
					if (res.Trim() == "#") {
						MessageBox.Show("#Invalid Parameter")
						//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,'MessageBox.Show("#Invalid Parameter")');
						return;
					}
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(100);
					if (setsilentmode > -1) {
						var ww = (setsilentmode == 1) ? "Enabled" : "Disabled";
						MessageBox.Show("*Silent Mode " + ww);
					}
					_('schstrcinner').innerHTML = res;
				},
				OnError: function (res) {
					loading.Hide();
					School.Structure.Loading = false;
					MessageBox.Show("#Internal Error: " + res);
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,"MessageBox.Show('#Internal Error: "+res+"')");
				},
				OnAbort: function (res) {
					loading.Hide();
					School.Structure.Loading = false;
					MessageBox.Show('Operation Aborted');
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,"MessageBox.Show('Operation Aborted')");
				}
			});
		},
		Refresh: function (setSilentMode) {
			setSilentMode = setSilentMode || -1;
			//get the current details
			var curdetobj = JSON.parse(_('schstrucdatabx').textContent);

			var curdisdet = curdetobj[curdetobj['Details']['Current']];
			//console.log(curdisdet);
			//alert(curdisdet['Prev']);
			if (curdisdet['Prev'] != "") {
				//console.log(curdetobj)
				var prvdet = curdetobj[curdisdet['Prev']];
				//perform a reload
				School.Structure.Load(prvdet["ID"], curdisdet['Prev'], prvdet["Loaded"], 0, 0, setSilentMode);
			} else {
				//alert('no prev');
				School.Structure.Load(0, 'a', '');
			}


		},
		SetSilentMode: (swi) => {
			var status = swi.GetStatus();
			School.Structure.Refresh(status);
		},
		Save: function () {
			OptionBox.Show({
				Title: "Save Structure",
				TitleHTML: '<div class="altColor"><b>Note:</b> Delete operation will be ignored on Parent Items (Items that has sub items)</div>',
				Logo: "save",
				Options: [{
					Logo: "save",
					Title: "Save",
					Info: "Save current display structure",
					Function: function () {
						School.Structure.PerformSave();
						//MessageBox.Show('All');
					}
				},
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Abort the Operation",
					Function: function () {
						//MessageBox.Show("Print Operation Canceled");
					}
					//Parameter:selectedRegNo
				}]

			});
		},
		PerformSave: function () {
			var SilentMode = _('schstrcsilentmode');
			var silentmd = (SilentMode != null) ? SilentMode.GetStatus() : 0;
			var sdata = _('schstrucdatabx').textContent;
			var spreads = _('schstrss').GetDataString();
			//console.log(spreads);
			var currentStrucName = _('currenStrucName').textContent;
			//alert(currentStrucName);return;
			School.Structure.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/savestructure.php",
				PostData: "Data=" + encodeURIComponent(sdata) + "&Sheet=" + escape(spreads) + "&SilentMode=" + silentmd + "&StrucName=" + encodeURIComponent(currentStrucName) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (res.Trim() != "#") {
						Tabs.Tab("School").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("' + res + '")');
						return;
					}
					Tabs.Tab("School").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("*Saved Successfully<br />System will Reload Sheet Automatically");School.Structure.Refresh()');
					//_('schstrcinner').innerHTML = res;
				},
				OnError: function (res) {
					Tabs.Tab("School").ProgressGet(0).ProgressTo(-1, "MessageBox.Show('#Internal Error: " + res + "')");
				},
				OnAbort: function (res) {
					Tabs.Tab("School").ProgressGet(0).ProgressTo(-1, "MessageBox.Show('Operation Aborted')");
				}
			});
		}
	},

	//school levels management
	Levels: {
		Ajax: new Ajax,
		Load: function (StudyID) {
			//get the user selected school and 
			StudyID = typeof StudyID == _UND ? _('sclvlstudschstudy').ValueContent() : StudyID;
			Tabs.Tab("School").ProgressGet(1).ProgressTo(1);
			School.Levels.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/loadlevels.php",
				PostData: "StudyID=" + StudyID + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(Math.floor(delta * 70));
				},
				OnComplete: function (res) {
					if (res.Trim() == "#") {
						Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, "MessageBox.Show('#INVALID STUDY SELECTED')"); return;
					}
					Tabs.Tab("School").ProgressGet(1).ProgressTo(100);
					_('schlevdetgrp_title').innerHTML = '<i class="fa fa-th" aria-hidden="true" style=""></i> <span>' + _('sclvlstudschstudy_inp').value + ' Levels</span>';
					_('schlvldetbx').innerHTML = res;
					_('schlevelhome').Hide();
					_('schlevdetgrp').Show();
					Tabs.HideSideBar("School", 1);
				},
				OnError: function (res) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, "MessageBox.Show('#Internal Error: " + res + "')");
				},
				OnAbort: function (res) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, "MessageBox.Show('Operation Aborted')");
				}
			})
		},
		Refresh: function () {
			var StudyID = _('SchLvlLoadDet').value;
			School.Levels.Load(StudyID);
		},
		SaveAjax: new Ajax,
		Save: function () {
			sprobj = _('schlvldetsprs');
			if (sprobj == null) { MessageBox.Show('No Record Loaded'); return }
			var spreads = sprobj.GetDataString();
			var StudyID = _('SchLvlLoadDet').value;
			School.Levels.SaveAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/School/savelevels.php",
				PostData: "StudyID=" + StudyID + "&Sheet=" + escape(spreads) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (res.Trim() != "#") {
						Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, 'MessageBox.Show("' + res + '")');
						return;
					}
					Tabs.Tab("School").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("*Saved Successfully<br />System will Reload Sheet Automatically");School.Levels.Refresh()');
					//_('schstrcinner').innerHTML = res;
				},
				OnError: function (res) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, "MessageBox.Show('#Internal Error: " + res + "')");
				},
				OnAbort: function (res) {
					Tabs.Tab("School").ProgressGet(1).ProgressTo(-1, "MessageBox.Show('Operation Aborted')");
				}
			});
		}
	}
}

/************************************************************************************************** */
//*Course Module
/************************************************************************************************** */
var Course = {
	ManageCourse: {
		GenLoader: new GenLoading({ StudyID: "cstudy", FacID: "coursefac", DeptID: "coursedept", ProgID: "courseprog", LevelID: "courselvl", SemID: "coursesemest" }),
		GenLoaderImport: new GenLoading({ StudyID: "icstudy", FacID: "icoursefac", DeptID: "icoursedept", ProgID: "icourseprog", LevelID: "icourselvl", SemID: "icoursesemest" }),
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		//Load Courses for the selected level/semester
		LoadAjax: new Ajax(),
		CurLoaded: "",
		Load: function (datas) {
			if (typeof datas == _UND) {
				if (Tabs.Tab("Course").ProgressGet(0).ProgressState() != 0) {
					MessageBox.Show("#System Busy, Try again later");
					return;
				}
				//get all parameters
				datas = Page.DataString("objgrpelemmgecourse");
				// 'Fresh Load'.__();
			}

			//datas.__();
			//alert(datas);
			var dataarr = datas.ToDataArray();
			//cstudy=2&coursefac=5&coursedept=48&courseprog=49&courselvl=1&coursesemest=1
			if (dataarr['courseprog'].ToNumber() < 1 || dataarr['courselvl'].ToNumber() < 1 || dataarr['coursesemest'].ToNumber() < 1) {
				MessageBox.Show("#INVALID PARAMETER.<br/>Make sure you select all field");
				return;
			}
			Course.ManageCourse.CurLoaded = datas;
			Course.ManageCourse.LoadAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadcourse.php",
					PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//"Loaded".__();
						_('coursecontdiv').innerHTML = res;
						//"Populated".__();
						_('managecoursehome').Hide();
						_('coursepgagrp').Show();
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(100);
						Tabs.HideSideBar("Course", 0);
					},
					OnAbort: function (res) {

						Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		},
		Method2: function () {
			//method code
		},

		//Add Predefined Method
		Save: function () {
			var loadtype = _('loadtype').value;
			if (loadtype == "normal") {
				_('grpmngcoursefrm').submit();
			} else {
				OptionBox.Show({
					Title: "Save Imported Courses/Subjects",
					Logo: "save",
					Options: [{
						Logo: "list-alt",
						Title: "Override",
						Info: "All current courses/subject will be disabled",
						Function: function () {
							//alert(_('icourseprog'));
							_('loadtype').value = "import_1";
							_('grpmngcoursefrm').submit();
							//MessageBox.Show('All');
						}

						// Parameter:selUserID
					}, {
						Logo: "plus",
						Title: "Append",
						Info: "Append imported courses/subjects with the current courses/subjects",
						Function: function () {
							//alert(_('icourseprog'));
							_('loadtype').value = "import_2";
							_('grpmngcoursefrm').submit();
							//MessageBox.Show('All');
						}

						// Parameter:selUserID
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Cancel the Course/Subject Update Operation",
						Function: function () {
							//
							Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');

						}
						//Parameter:selectedRegNo
					}]

				});
			}

			//Save code
		},
		SaveAjax: new Ajax(),

		PerformSave: function (checkdup) {

			checkdup = typeof checkdup == _UND ? 1 : 0;
			//check if data exist var shdatastr = _('sprstupload_datastring').value;
			if (Tabs.Tab("Course").ProgressGet(0).ProgressState() != 0) {
				MessageBox.Show("#System Busy, Try again later");
				return;
			}
			var coursesdet = _('lcoursesdet');
			if (coursesdet == null || coursesdet.Trim() == "") {
				MessageBox.Show("#No Semester Courses Details Found");
				return;
			}
			if (!SpreadSheet.ColumnDataExist("sprstcourses", "CCode") && !SpreadSheet.ColumnDataExist("sprstcourses", "CTitle") && !SpreadSheet.ColumnDataExist("sprstcourses", "CH") && !SpreadSheet.ColumnDataExist("sprstcourses", "CourseID")) {
				MessageBox.Show("#Empty Result Set");
				return;
			}
			var courses = _('sprstcourses_datastring').value;

			var cdet = rawescape(_('lcoursesdet').Text());
			//checkdup = checkdup?1:0;
			var datas = "courses=" + rawescape(courses) + "&cdet=" + cdet + "&checkdupl=" + checkdup + "&loadtype=" + _('loadtype').value;

			Course.ManageCourse.SaveAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/save.php",
					PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
						if (delta >= 1) {
							Tabs.Tab("Course").ProgressGet(0).ProgressStepTo(90);
						}
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(100);
						res = res.Trim();
						//alert(res);
						var fchar = res.substr(0, 1);
						if (fchar == "*") { //if successfull

							//"Save Successfull".__();
							//alert("Success");
							//reload the courses to display updaated copy (with course id)
							//"Start Reloading".__();
							Course.ManageCourse.Load(Course.ManageCourse.CurLoaded);
							//"Run Reloaded".__();
							//Course.ManageCourse.CurLoaded = datas;
						} else if (fchar == "~") {//if duplicate found
							res = res.substr(1);
							//display the popup
							OptionBox.Show({
								Title: "Duplicate Courses Found",
								TitleHTML: res,
								Options: [{
									Logo: "check",
									Title: "Continue",
									Info: "Continue Course Update Process",
									Function: function () {
										Course.ManageCourse.PerformSave(0);
										//MessageBox.Show('All');
									}

									// Parameter:selUserID
								},
								{
									Logo: "times",
									Title: "Cancel",
									Info: "Cancel the Course Update Operation",
									Function: function () {
										//
										Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');

									}
									//Parameter:selectedRegNo
								}]

							});
							return;
						}
						MessageBox.Show(res);

					},
					OnAbort: function (res) {

						Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		},
		Clear: function () {
			//clear code
			MessageBox.Show("Not Applicable");
		},
		Print: function () {
			//print code
			var coursesdet = _('lcoursesdet');
			if (coursesdet == null || coursesdet.Text().Trim() == "") {
				MessageBox.Show("#No Course/Subject Loaded");
				return;
			}
			PDFPrinter.Print(configdata.Core + "cportal/Reports/Course/semcourse.php", 'cdet=' + rawescape(coursesdet.Text()) + "&paper=A4&orientation=P&MT=4&MB=14" + "&SubDir=" + encodeURIComponent(configdata.SubDir), 'SemCourse' + ".pdf");

		},
		Export: function () {
			var coursesdet = _('lcoursesdet');
			if (coursesdet == null || coursesdet.Text().Trim() == "") {
				MessageBox.Show("#No Course/Subject Loaded");
				return;
			}
			if (!SpreadSheet.ColumnDataExist("sprstcourses", "CCode") && !SpreadSheet.ColumnDataExist("sprstcourses", "CTitle") && !SpreadSheet.ColumnDataExist("sprstcourses", "CH")) {
				MessageBox.Show("#Empty Result Set");
				return;
			}
			//export code sprstcourses
			tableToExcel(_('sprstcourses').outerHTML, 'Courses');
		},
		Import: function () {
			var coursesdet = _('lcoursesdet');
			if (coursesdet == null || coursesdet.Text().Trim() == "") {
				MessageBox.Show("#No Course/Subject Loaded");
				return;
			}
			OptionBox.Show({
				Title: "Import Courses/Subjects",/* 
				TitleHTML: OptionBox.Note(), */
				Options: [{
					Logo: "server",
					Title: "Existing",
					Info: "Import form existing Courses/Subjects",
					Function: function () {
						Course.ManageCourse.ImportCourses(0);
						//MessageBox.Show('All');
					}

					// Parameter:selUserID
				},
				{
					Logo: "file-excel-o",
					Title: "Excel Workbook",
					Info: "Microsoft Office Excel Workbook (*.xlsx)",
					Function: function (param) {
						Course.ManageCourse.ImportCourses(1);

					},
					//Parameter: loadedparamobj.value
				},
				{
					Logo: "file-text-o",
					Title: "Excel 97-2003 Workbook",
					Info: "Microsoft Office Excel 97-2003 Workbook (*.xls)",
					Function: function (param) {
						Course.ManageCourse.ImportCourses(2);

					},
					//Parameter: loadedparamobj.value
				},
				{
					Logo: "file-o",
					Title: "CSV",
					Info: "Comma Seperated Value (*.csv)",
					Function: function (param) {
						Course.ManageCourse.ImportCourses(3);

					},
					//Parameter: loadedparamobj.value
				},
				{
					Logo: "file-code-o",
					Title: "JSON",
					Info: "JSON File (*.json)",
					Function: function (param) {
						Course.ManageCourse.ImportCourses(4);

					},
					//Parameter: loadedparamobj.value
				}/* ,
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Cancel the Course Import Operation",
					Function: function () {
						//
						//Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1,'MessageBox.Show("Operation Canceled");');
						
					}
					//Parameter:selectedRegNo
				} */]

			});
		},
		ImportAjax: new Ajax(),
		ImportCourses: (id) => {
			if (id == 0) {
				//load from existing
				Course.ManageCourse.ImportAjax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadstruc.php",
						PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnProgress: function (delta) {
							Tabs.Tab("Course").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
							if (delta >= 1) {
								Tabs.Tab("Course").ProgressGet(0).ProgressStepTo(90);
							}
						},
						OnComplete: function (res) {
							//if(!Login.Authenticate(res))return;
							Tabs.Tab("Course").ProgressGet(0).ProgressTo(100);

							//res = res.substr(1);
							//display the popup
							OptionBox.Show({
								Title: "Load From Existing",
								TitleHTML: res,
								Options: [{
									Logo: "check",
									Title: "Continue",
									Info: "Load Courses/Subjects",
									Function: function () {
										//alert(_('icourseprog'));
										Course.ManageCourse.ImportExisting();
										//MessageBox.Show('All');
									}

									// Parameter:selUserID
								},
								{
									Logo: "times",
									Title: "Cancel",
									Info: "Cancel the Course Update Operation",
									Function: function () {
										//
										Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');

									}
									//Parameter:selectedRegNo
								}]

							});



						},
						OnAbort: function (res) {

							Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
						},
						OnError: function (res) {
							//MessageBox.Show("" + res);
							Tabs.Tab("Course").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
						}
					}
				);
			} else {
				MessageBox.Show("Not Available");
			}
		},
		ImportExisting: () => {
			//get the details
			icourseprog = _('icourseprog').ValueContent();
			icourselvl = _('icourselvl').ValueContent();
			icoursesemest = _('icoursesemest').ValueContent();
			var datas = "icourseprog=" + icourseprog + "&icourselvl=" + icourselvl + "&icoursesemest=" + icoursesemest + "&importtype=0";
			if (icourseprog == "" || icourselvl == "" || icoursesemest == "") {
				MessageBox.Show("INVALID SELECTION: No Existing Course/Subject Details Selected");
			}
			//return;

			Course.ManageCourse.ImportAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/importload.php",
					PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						var fchar = res.substr(0, 1);
						if (fchar != "#") {
							_('loadcsprsheet').innerHTML = res;
						} else {
							MessageBox.Show(res);
						}
						//if(!Login.Authenticate(res))return;
						//"Loaded".__();

						//"Populated".__();
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(100);
					},
					OnAbort: function (res) {

						Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Course").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		},
		Delete: function () {
			MessageBox.Show("Not Applicable");
		}
	},

	MonitorCourse: {
		Save: function () {
			alert("monitor save");
		}
	},

	CourseSetting: {
		SaveAjax: new Ajax(),
		Save: function () {
			var openportal = _('openportal').GetStatus();
			var semcntr = _('semcntr').GetStatus();
			var lowlvl = _('lowlvl').GetStatus();
			var unregcourses = _('unregcourses').GetStatus();
			var reptcourses = _('reptcourses').GetStatus();
			var chkprob = _('chkprob').GetStatus();
			var duplcourse = _('duplcourse').GetStatus();
			var chkprev = _('chkprev').GetStatus();
			var rngval = _('maxelectivegrp').RangeValue();
			var coursegrp = _('cgrpsprsheet').GetDataString();
			var maxch = _('mxxhspsh').GetDataString();
			var autoregst = _('autoregst').GetStatus();//
			var adminprepaycntr = _('adminprepaycntr').GetStatus();
			var dymlvl = _('dymlvl').GetStatus();
			//alert(maxch);
			//alert(coursegrp);return;
			var obj = _('paytbll').Selected();
			if (obj == null) {
				MessageBox.Show("Select The Course Registration Preceeding Payment Type");
				return;
			}
			var payidarr = _("inp_" + obj.id).value.split("_");
			if (payidarr.length != 2) {
				MessageBox.Show("Invalid Course Registration Preceeding Payment Type Selected");
				return;
			}

			var PayID = payidarr[0];
			var data = "OpenPortal=" + openportal + "&SemControl=" + semcntr + "&LowerLevel=" + lowlvl + "&UnregCourse=" + unregcourses + "&ReptCourse=" + reptcourses + "&Prob=" + chkprob + "&Duplicate=" + duplcourse + "&PrevCourse=" + chkprev + "&PayID=" + PayID + "&MaxElective=" + rngval + "&CGrps=" + escape(coursegrp) + "&maxch=" + escape(maxch) + "&AutoRegStatus=" + autoregst + "&AdminPrePay=" + adminprepaycntr + "&dymlvl=" + dymlvl;
			//OpenPortal=0&SemControl=0&LowerLevel=1&UnregCourse=0&Prob=0&Duplicate=0&PrevCourse=1&PayID=2
			//	alert(data);
			Course.CourseSetting.SaveAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/setsave.php",
					PostData: data + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//console.log(res);
						//alert(res);
						var fchar = res.Trim().substr(0, 1);
						if (fchar == "~") { //if course group reload exist
							_('coursegrpbx').innerHTML = res.Trim().substr(1);
							res = "*Course Settings Saved";
						}
						//MessageBox.Show(res);
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					},
					OnAbort: function (res) {

						Tabs.Tab("Course").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);

			//MessageBox.Show("Open Registration Status =" + st);
		},
		Print: function () {
			//alert('Print')
		},
		StatusChange: function (obj) {
			var stus = obj.GetStatus();
			if (stus == 1) { //if course registration Enabled
				//get the settins html
				Course.CourseSetting.SaveAjax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/getnewyearhtml.php",
						PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnProgress: function (delta) {
							//Tabs.Tab("Course").ProgressGet(3).ProgressTo(Math.floor(delta * 90));
						},
						OnComplete: function (res) {
							if (!Login.Validate(res)) { return; };
							OptionBox.Show({
								Title: "New Academic Year/Semester",
								TitleHTML: res,
								Logo: "cogs",
								Options: [{
									Logo: "tasks",
									Title: "Save",
									Info: "Update School Academic Details",
									Function: function () {
										Course.CourseSetting.UpdateAccDet();
										//MessageBox.Show('All');
									}

									// Parameter:selUserID
								}]

							});

						},
						OnAbort: function (res) {

						},
						OnError: function (res) {
							MessageBox.Show("#INTERNAL ERROR: " + res);
							//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100);
						}
					}
				);


			}
		},
		UpdateAccadaAjax: new Ajax(),
		UpdateAccDet: function () {
			var newses = _('schnewsession').TextContent();
			var activesem = _('coursestsem').ValueContent();
			var abbr = _('schnewsessionabb').TextContent();
			Course.CourseSetting.UpdateAccadaAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/saveaccdet.php",
					PostData: "newses=" + escape(newses) + "&activesem=" + activesem + "&abbr=" + abbr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;

						//MessageBox.Show(res);
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					},
					OnAbort: function (res) {

						Tabs.Tab("Course").ProgressGet(3).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Course").ProgressGet(3).ProgressTo(100, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		}
	},
	Register: {
		Unregister: (RegNo, cid) => {
			//alert(RegNo+" - "+cid);
			OptionBox.Show({
				Title: "Unregister All Courses/Subject",
				TitleHTML: "The entire Courses/Subject record will be deleted",
				Logo: "trash",
				Options: [{
					Logo: "thumbs-up",
					Title: "Continue",
					Info: "Unregister all courses/subject of " + RegNo,
					Function: function (param) {
						Course.Register.UnregisterNow(param);
					},

					Parameter: [RegNo, cid]
				}]

			});
		},
		UnregisterNow: param => {
			var unregbtn = _(param[0] +"_"+param[1] + "_unregbtn");
			var modifybtn = _(param[0] + "_modifybtn");
			var cregbtn = _(param[0] + "_cregbtn");
			unregbtn.disabled = true;
			modifybtn.disabled = true;
			cregbtn.disabled = true;
			unregbtn.innerHTML = '<i class="fa fa-spin fa-cog"></i> Deleting ...';
			_(param[0] + '_disnote').innerHTML = "<span class='err'>Deleting ...<span>";
			Course.CourseSetting.UpdateAccadaAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/unregister.php",
					PostData: "cid=" + escape(param[1]) + "&regno=" + escape(param[0]) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						if (res == "#") { //unregister success
							_(param[0] + '_disnote').innerHTML = "<span class='err'>Unregisterd Successfully<span>";
							unregbtn.Hide();
							modifybtn.Hide();
							//cregbtn.Hide();
						} else {
							unregbtn.innerHTML = '<i class="fa fa-trash"></i> Unregister';
							unregbtn.disabled = false;
							modifybtn.disabled = false;
							cregbtn.disabled = false;
							MessageBox.Show(res);
						}


						//MessageBox.Show(res);
						//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100,'MessageBox.Show("'+res.Replace('"','\"')+'");');
					},
					OnAbort: function (res) {
						MessageBox.Show("Operation Aborted");
						_(param[0] + '_disnote').innerHTML = "<span class='err'>Registration Delete Aborted<span>";
						unregbtn.innerHTML = '<i class="fa fa-trash"></i> Unregister';
						unregbtn.disabled = false;
						modifybtn.disabled = false;
						cregbtn.disabled = false;
					},
					OnError: function (res) {
						MessageBox.Show("#INTERNAL ERROR:" + res);
						_(param[0] + '_disnote').innerHTML = "<span class='err'>Registration Delete Failed<span>";
						unregbtn.innerHTML = '<i class="fa fa-trash"></i> Unregister';
						unregbtn.disabled = false;
						modifybtn.disabled = false;
						cregbtn.disabled = false;
					}
				}
			);
		},
		UpdateReg: swi => {
			var st = swi.GetStatus();
			var id = swi.id || null;
			if (id != null) {
				var idarr = id.split("_");
				var regpart = idarr[0];
				var fieldID = idarr[3];
				var fieldpre = fieldID.substr(fieldID.length - 1, 1);
				if (fieldpre != "2") fieldpre = "";
				var RegNoarr = regpart.split("|");
				var RegNo = RegNoarr[1];//cregsheet|AK2019/NAS/BOT/003_rw_16_RegCID_edit
				var cidcell = _(idarr[0] + "_" + idarr[1] + "_" + idarr[2] + "_RegCID" + fieldpre + "_edit");
				if (cidcell != null) {
					var courseID = cidcell.textContent;
					//get the sheet data
					var StudData = _(RegNo + '_regdatat');
					if (StudData != null) {
						StudDataObj = JSON.parse(StudData.textContent);
						//console.log(courseID)
						//search for the course id
						course = StudDataObj.SheetData.findIndex(course => course[0] == courseID);
						if (typeof StudDataObj.SheetData[course] == _UND) {
							//add a new entering
							//["428","BIO 401","Research Methods And Scientific Writing","3",1]
							//get other setails
							var Code = _(idarr[0] + "_" + idarr[1] + "_" + idarr[2] + "_RegCCode" + fieldpre + "_edit").textContent;
							var tit = _(idarr[0] + "_" + idarr[1] + "_" + idarr[2] + "_RegCTitle" + fieldpre + "_edit").textContent;
							var ch = _(idarr[0] + "_" + idarr[1] + "_" + idarr[2] + "_RegCCH" + fieldpre + "_edit").textContent;
							StudDataObj.SheetData[StudDataObj.SheetData.length] = [courseID, Code, tit, ch, st];

						} else {
							//update existing entering
							StudDataObj.SheetData[course][4] = st;
						}
						StudData.textContent = JSON.stringify(StudDataObj);
						var regcoursecnt = _(RegNo + '_totregcourse');

						if (regcoursecnt != null) {
							regcoursecntval = regcoursecnt.textContent.ToNumber();
							regcoursecntval = (st == 1) ? (regcoursecntval + 1) : (regcoursecntval - 1);
							regcoursecnt.textContent = regcoursecntval;
						}
						//console.log(StudData.textContent);

					}
					//console.log(courseID);
					/* var rw = idarr[2].ToNumber() - 2;
					 var col = swi.Data('column').ToNumber() - 1;
					 if(rw >= 0){
						 //get the sheet data
						 var StudData = _(RegNo+'_regdatat');
						 if(StudData != null){
							 StudDataObj = JSON.parse(StudData.textContent);
							  if(typeof StudDataObj.SheetData[rw][col] != _UND && typeof StudDataObj.SheetData[rw][col])
							 StudDataObj.SheetData[rw][col] = st;
							 StudData.textContent = JSON.stringify(StudDataObj); 
						 }
					 } */
				}

				//get the corrent register string

			} else {
				swi.Undo();
			}

		},
		LoadLLC: function (RegNo, ProgID, LevelID, SemesterID) {
			//_(sheetid+"_datastring")
			//@@@@@@@@@@@@@
			//Switcher not Updating in spreadsheet
			//alert(_('cregsheet_'+RegNo+"_datastring").value);
			//alert('sjsjsj');
			var regdisplayl = _(RegNo + "_llc");
			regdisplayl.innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load the Student Lower Level Courses</small>");
			var modifAjax = new Ajax();
			modifAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadlls.php",
				PostData: "RegNo=" + encodeURIComponent(RegNo) + "&ProgID=" + ProgID + "&LevelID=" + LevelID + "&SemesterID=" + SemesterID + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					//if(!Login.Authenticate(res))return;
					//alert(res);
					regdisplayl.innerHTML = res;
					//MessageBox.Show(res);
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100,'MessageBox.Show("'+res.Replace('"','\"')+'");');
				},
				OnAbort: function (res) {
					regdisplayl.innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle appcolor", 'Operation Aborted !!!<br /><a href="javascript:Course.Register.Modify(\'' + $RegNo + '\',' + ProgID + ',' + LevelID + ',' + SemesterID + ')" >Try Again</a>');
					//MessageBox.Show("Operation Aborted");
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(-1,'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					//MessageBox.Show("#INTERNAL ERROR: "+res);
					regdisplay.innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle appcolor", 'INTERNAL ERROR: ' + res + '<br /><a href="javascript:Course.Register.Modify(\'' + $RegNo + '\',' + ProgID + ',' + LevelID + ',' + SemesterID + ')" >Try Again</a>');
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100,'MessageBox.Show("#INTERNAL ERROR: '+res.Replace('"','\"')+'");');
				}
			});
		},
		Modify: function (RegNo) {

			//check if details exist
			var detobj = _(RegNo + '_regdatat');

			if (detobj == null) return;
			//get the content
			var detcont = detobj.textContent;
			var regdisplay = _("regdisplays_" + RegNo);
			regdisplay.innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load the Student Course Registration Sheet</small>");
			var modifAjax = new Ajax();
			modifAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadcourseregsheet.php",
				PostData: "Data=" + encodeURIComponent(detcont) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					//if(!Login.Authenticate(res))return;
					regdisplay.innerHTML = res;
					//MessageBox.Show(res);
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100,'MessageBox.Show("'+res.Replace('"','\"')+'");');
				},
				OnAbort: function (res) {
					regdisplay.innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle appcolor", 'Operation Aborted !!!<br /><a href="javascript:Course.Register.Modify(\'' + $RegNo + '\')" >Try Again</a>');
					//MessageBox.Show("Operation Aborted");
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(-1,'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show("" + res);
					//MessageBox.Show("#INTERNAL ERROR: "+res);
					regdisplay.innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle appcolor", 'INTERNAL ERROR: ' + res + '<br /><a href="javascript:Course.Register.Modify(\'' + $RegNo + '\')" >Try Again</a>');
					//Tabs.Tab("Course").ProgressGet(3).ProgressTo(100,'MessageBox.Show("#INTERNAL ERROR: '+res.Replace('"','\"')+'");');
				}
			});
		},
		PrintSlip: function (RegNo, Lvl, Sem) {
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Course&regno=" + escape(RegNo) + "&Lvl=" + Lvl + "&Sem=" + Sem + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "CRF_" + RegNo.Replace("/", "_") + "_" + Lvl + "_" + Sem + ".pdf");
		}
		,
		PrintSlipi: function (CourseRegID) {
			PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Course&file=Slipi.php&CourseRegID="+CourseRegID + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "CRF_" +CourseRegID+  ".pdf");
		}
		,//ptrobstudstudy:;ptrobstudfac:;ptrobstuddept:;ptrobstudprog:;ptrobstudlvl:;
		GenLoader: new GenLoading({ StudyID: "cregstudstudy", FacID: "cregstudfac", DeptID: "cregstuddept", ProgID: "cregstudprog", LevelID: "cregstudlvl", DisplayLevelID: "blvl", StartSesID: "cregsestb", DisplayLevelIDNum: "hlvl" }),
		StudyLoad: function () {
			if (_('cregtype').GetStatus() == 1) { //if regno load the level direct
				Course.Register.GenLoader.LoadLevel();
			} else {
				Course.Register.GenLoader.LoadFac(); //if details load the faculty
				Course.Register.GenLoader.LoadLevel();
			}
		},
		// Course.Register.GenLoader.LoadFac
		ChangeType: function (swi) {

			var state = swi.GetStatus();
			if (state == 1) {
				_('cregregnoc').Show();
				_('cregrangec').Hide();
				_('cregspec_inp').focus();
			} else {
				_('cregregnoc').Hide();
				_('cregrangec').Show();
			}

		},
		AutoLSChange: function (swi) {
			if (swi.GetStatus() == 1) {
				_('autoLSbox').Hide();
			} else {
				_('autoLSbox').Show();
				var study = _('cregstudstudy').ValueContent().ToNumber();
				if (study < 1) MessageBox.Show("Select a Study to Load Level");
			}
		},
		TRegNos: [],
		RegDet: {},
		TIndex: 0,
		CourseRegType: null,
		Ajax: new Ajax(),
		GetAllStudent: function () {
			var ptrobtn = _('cregbtn');
			if (ptrobtn.IsLoading()) {
				MessageBox.Show("A process is on-going, wait until completion or Stop Process");
				return;
			}
			var studet = {};
			studet['StudyID'] = _('cregstudstudy').ValueContent().ToNumber();
			//check fixer type
			var state = _('cregtype').GetStatus();
			studet['Type'] = state; //1-> RegNos, 0->Range
			if (state == 1) { //if specific student 
				//get the regNos
				var RegNotbx = _('cregspec');
				var RegNos = RegNotbx.TextContent();
				if (RegNos.Trim() == "") {
					MessageBox.Show("Enter Student Registration Number(s) <br/> <i>(Seperate multiple Entering with space or comma)</i>");
					RegNotbx.TextFocus();
					return;
				} else {
					//get total regno
					studet['RegNos'] = RegNos.Trim().Replace(" ", ",").split(",");
					var prid = _('cregstudprog').ValueContent().ToNumber();
					if (prid > 0) {
						studet['ProgID'] = prid;
					}
					//$data = "RegNos="+escape(RegNos);
				}
			} else {

				//fsestb
				// studet['SesID'] = _('fsestb').ValueContent().ToNumber();

				var pfac = _('cregstudfac');
				if (pfac != null) {
					studet['FacID'] = pfac.ValueContent().ToNumber();
					studet['DeptID'] = _('cregstuddept').ValueContent().ToNumber();
					studet['ProgID'] = _('cregstudprog').ValueContent().ToNumber();
					studet['Batch'] = _('cregsestb').ValueContent().ToNumber();//cregmode
					studet['Mode'] = _('cregmode').ValueContent().ToNumber();//
				}




			}

			//get the lvl 	and sem if manual reg
			var autoLS = _('cregautoreg').GetStatus();
			studet['AutoLS'] = autoLS;
			if (autoLS == 0) {
				var lvlelem = _('cregstudlvl');
				var semelem = _('cregstudsem');
				if (lvlelem != null) {
					studet['LvlID'] = lvlelem.ValueContent().ToNumber();
				} else {
					studet['LvlID'] = _('hlvl').textContent.ToNumber();
				}
				// 

				studet['SemID'] = semelem.ValueContent().ToNumber();

				 /* if (studet['LvlID'] == 0 || studet['SemID'] == 0) {
					MessageBox.Show("For Manual Level/Semester Selection, Both Level and Semester Field are Compulsary");
					return;
				}  */
				if (studet['SemID'] == 0) {
					const semName = _('rcsemName').value;
					MessageBox.Show("Select Registration "+semName);
					return;
				} 
				/* if(state == 0 && studet['Batch'] == 0){ //if range selection and auto level semester selection is disabled, promt user to select a batch - we will not be able to determine student that is in the selected level, if ther batch is not provided
					MessageBox.Show("For Range and Manual Level/Semester Selection, Batch Field is Compulsary");
					return;
				} */
				if (lvlelem != null) {
					studet['LvlName'] = TextBox.GetText(lvlelem);
				} else {
					studet['LvlName'] = _('blvl').textContent;
				}
				// 

				studet['SemName'] = TextBox.GetText(semelem);
				//alert(lvlelem.TextContent());
			}
			//alert(JSON.stringify(studet));
			//return;'<strong>348</strong> - Troubleshooting <span>AKS/NAS/MTH/019</span> Results ...'
			_('bulkcreghome').Hide();
			_('cregtrem').Show();
			ptrobtn.StartLoading();
			_('cregtitle').innerHTML = 'Reading and Processing Students ....';
			_('cregcontdiv').innerHTML = '';
			//load valid students
			Course.Register.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadstudreg.php",
				PostData: "GetRegNos=" + encodeURIComponent(JSON.stringify(studet)) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Course").ProgressGet(4).ProgressTo(Math.floor(delta * 50));
					//Tabs.Tab("Exams").ProgressGet(2).ProgressTo(Math.floor(delta*95));
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					Course.Register.TRegNos = []; Course.Register.RegDet = []; Course.Register.TIndex = 0;
					var titbx = _('cregtitle');
					titbx.innerHTML = '';
					_('cregcontdiv').innerHTML = '';
					_('cregcntrbtn + cntrbtncregall + cregallbtn + cunregallbtn').Hide();
					_('cregbtn').StopLoading();
					//_('').Hide();
					if (res == "#") {

						Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("#No Valid Student Found");');

						return;
					}
					if (res == "##") {

						Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("#Error Loading Students");');

						return;
					}

					if (res == "###") {//access denied

						Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("#Access Denied <br /> Browser-Reload the system and Try Again");');

						return;
					}
					//_('rstfixcontdiv').innerHTML = res;
					//alert(res);
					//return;

					/* Tabs.Tab("Course").ProgressGet(4).ProgressTo(100);
					alert(res);return; */
					Tabs.Tab("Course").ProgressGet(4).ProgressTo(100);
					var studDet = JSON.parse(res);
					var totstud = studDet.Total;
					if (totstud < 1) {

						Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("No Valid Student/Payment Found");');
						return;
					}
					var studs = studDet.RegNos;
					var totbad = studDet.TotalBad;
					var studsbad = studDet.BadRegNos;
					//alert(studDet.Q)
					Course.Register.TRegNos = studDet.RegNos;
					Course.Register.RegDet = studDet;
					titbx.innerHTML = '<strong class="ok">' + totstud + '</strong> Valid Student Found';
					//alert(totstud + " => " +JSON.stringify(studDet.RegNos)+" ; " + totbad+ " => " +JSON.stringify(studDet.BadRegNos));
					OptionBox.Show({
						Title: "Load & Register Student Courses",
						TitleHTML: '<table class="tbl rwb greyShadow" style="width:95%;font-size:0.8em;margin:auto" bordercolor="#CCCCCC" border="1"><tr class=""  ><th style="text-align:left">Valid Student</th><td>' + totstud + '</td></tr><tr><th style="text-align:left">Invalid Student</th><td>' + totbad + '</td></tr><tr class=""  ><th style="text-align:left">Level</th><td>' + studDet.LvlName + '</td></tr><tr><th style="text-align:left">Semester</th><td>' + studDet.SemName + '</td></tr></table><div style="font-size:0.7em;padding:10px" class="altColor"><i>(All Invalid Student will be Ignored)</i></div>',
						ShowClose: false,
						Options: [{
							Title: "Load Only",
							Info: "Load Student Course Registration. Allows Modification before final Submit",
							Logo: "check-square",
							Function: function () {
								Course.Register.TState = "Play";
								Course.Register.Verify(0);
								_('cregtitle').innerHTML = '<strong>Initializing Registration ....</strong>';

								Tabs.Tab("Course").ProgressGet(4).ProgressTo(100);
								Tabs.HideSideBar("Course", 4);
							}
						},
						{
							Title: "Load & Register",
							Info: "Load & Register Student Courses.",
							Logo: "check",
							Function: function () {
								Course.Register.TState = "Play";
								Course.Register.Verify(1);
								_('cregtitle').innerHTML = '<strong>Initializing Registration ....</strong>';

								Tabs.Tab("Course").ProgressGet(4).ProgressTo(100);
								Tabs.HideSideBar("Course", 4);
							}
						},
						{
							Title: "CANCEL",
							Info: "Cancel Operation",
							Logo: "times",
							Function: function () {


								_('cregtitle').innerHTML = '';
								Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("Operation Canceled");');
							}
						}]
					})

				},
				OnAbort: function () {
					Course.Register.TRegNos = []; Course.Register.RegDet = {}; Course.Register.TIndex = 0;
					_('cregtitle').innerHTML = '';
					_('cregcontdiv').innerHTML = '';
					Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1);
					_('cregbtn').StopLoading();
				},
				OnError: function (res) {
					Course.Register.TRegNos = []; Course.Register.RegDet = {}; Course.Register.TIndex = 0;
					_('cregtitle').innerHTML = '';
					_('cregcontdiv').innerHTML = '';
					res = res.Replace('"', '\"');
					Tabs.Tab("Course").ProgressGet(4).ProgressTo(-1, 'MessageBox.Show("Internal Error: ' + res + '");');

					_('cregbtn').StopLoading();
				}
			});


		},
		TState: "Stop",
		Play: function () {
			//Exams.ResultFixer.FixerState = "Play";
			if (Course.Register.TState == 'Pause') {
				Course.Register.TState = "Play";
				Course.Register.Verify(Course.Register.CType);
				_('cregplaybtn').style.display = 'none';
				_('cregpausebtn').style.display = 'inline-block';
				_('cregtitle').innerHTML = '<strong>Resuming ...</strong>';
			} else if (Course.Register.TState == 'Stop') {
				Course.Register.TState = "Play";
				Course.Register.GetAllStudent();
			}


		},
		Pause: function () {
			if (Course.Register.TState == 'Play') {
				_('cregtitle').innerHTML = '<strong>Pausing ...</strong>';
				Course.Register.TState = "Pause";
				_('cregpausebtn').style.display = 'none';
				_('cregplaybtn').style.display = 'inline-block';
			}

		},
		Stop: function () {
			if (Course.Register.TState == 'Play') {
				_('cregtitle').innerHTML = '<strong>Stoping ...</strong>';
				Course.Register.TState = "Stop";
			} else if (Course.Register.TState == 'Pause') {
				_('cregtitle').innerHTML = '<strong>' + (Course.Register.TIndex + 1) + ' of ' + Course.Register.TRegNos.length + '</strong> -<span class="err"> Course Registration Process Stoped</span>';
				Course.Register.TRegNos = [];
				Course.Register.TIndex = 0;
				Course.Register.TState = "Stop";
				_('cregbtn').StopLoading();
				_('cregcntrbtn + cntrbtncregall').Hide();
				_('cregallbtn + cunregallbtn').Show();
				_('cregplaybtn').style.display = 'none';
				_('cregpausebtn').style.display = 'inline-block';
			}

		},
		CType: 0,
		Verify: function (Type) {
			Type = Type || 0;
			Course.Register.CType = Type;
			var nwregdet = Course.Register.RegDet;
			nwregdet['RegNos'] = "";
			nwregdet['BadRegNos'] = "";
			nwregdet['Q'] = "";
			nwregdet['Type'] = Course.Register.CType;
			var ptit = _('cregtitle');
			var trobtn = _('cregbtn');
			var ptobcntrbtn = _('cregcntrbtn');
			var cregcontdiv = _('cregcontdiv');
			//$typetxt = Type == 0 ? "" : " & Fixing";
			if (Course.Register.TState == 'Stop') {
				ptit.innerHTML = '<strong>' + (Course.Register.TIndex) + ' of ' + Course.Register.TRegNos.length + '</strong> -<span class="err"> Verification Process Stoped</span>';
				Course.Register.TRegNos = [];
				Course.Register.TIndex = 0;
				trobtn.StopLoading();
				_('cregcntrbtn + cntrbtncregall').Hide();
				if (Course.Register.TRegNos.length > 1) _('cregallbtn + cunregallbtn').Show();
				return;
			}

			if (Course.Register.TState == 'Pause') {
				ptit.innerHTML = '<strong>' + (Course.Register.TIndex) + ' of ' + Course.Register.TRegNos.length + '</strong> -<span class="altColor2">Course Registration Process Paused</span>';
				//Exams.ResultFixer.FixRegNos = [];
				//Exams.ResultFixer.FixerIndex = 0;
				return;
			}

			if (Course.Register.TRegNos.length < 1) {
				MessageBox.Show("No Valid Student Loaded");
				ptit.innerHTML = '';
				cregcontdiv.innerHTML = '';
				//Tabs.Tab("Course").ProgressGet(4).ProgressTo(100);
				_('cregcntrbtn + cntrbtncregall').Hide();
				_('cregallbtn + cunregallbtn').Hide();
				return;
			}
			trobtn.StartLoading();
			//start individual troubleshoting
			//$startInd = 0;

			//perform trouble shoting

			//get the regno
			$RegNo = Course.Register.TRegNos[Course.Register.TIndex];
			_('cregcntrbtn').Show();
			_('cregallbtn + cntrbtncregall + cunregallbtn').Hide();
			//alert(JSON.stringify(Exams.ResultFixer.FixRegNos))
			//Exams.ResultFixer.FixerIndex++;
			if ($RegNo.Trim() == "") {
				Course.Register.TIndex++;
				if (Course.Register.TIndex < Course.Register.TRegNos.length) {
					Course.Register.Verify(Course.Register.CType);
				} else {
					trobtn.StopLoading();
					ptit.innerHTML = '<strong class="ok">' + Course.Register.TRegNos.length + ' Student<small>(s)</small> Course Registration Processed Successfully</strong>';
					_('cregcntrbtn + cntrbtncregall').Hide();
					if (Course.Register.TRegNos.length > 1) _('cregallbtn + cunregallbtn').Show();
					//_('fixallbtn').Show();
					//_('rstfixcontdiv').innerHTML = '';
				}

			} else {
				ptit.innerHTML = '<strong>' + Course.Register.TIndex + ' of ' + Course.Register.TRegNos.length + '</strong> - Processing ' + " (" + $RegNo + ") Course Registration<small>(s)</small> ....";
				var FixerAj = new Ajax();
				FixerAj.Post({
					PostData: "RegNo=" + escape($RegNo) + "&Tot=" + Course.Register.TRegNos.length + "&Num=" + (Course.Register.TIndex + 1) + "&Details=" + encodeURIComponent(JSON.stringify(nwregdet)) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/loadstudreg.php",
					OnProgress: function (delta) {

					},
					OnComplete: function (res, url, param) {
						if (!Login.Authenticate(res)) return;
						//alert(res);
						//rstfixcontdiv
						_('cregcontdiv').insertAdjacentHTML('beforeend', res);
						Course.Register.TIndex++;
						if (Course.Register.TIndex < Course.Register.TRegNos.length) {
							Course.Register.Verify(Course.Register.CType);
						} else {
							_('cregbtn').StopLoading();
							_('cregtitle').innerHTML = '<strong class="ok">' + Course.Register.TRegNos.length + ' Student<small>(s)</small> Course Registration Processed Successfully</strong>';
							_('cregcntrbtn + cntrbtncregall').Hide();
							if (Course.Register.TRegNos.length > 1) _('cregallbtn + cunregallbtn').Show();
							//_('fixallbtn').Show();
						}
						var rind = _(param['RegNo'] + '_scroll');
						if (rind != null) {
							//rind.scrollIntoView();
						}

					},
					OnAbort: function () {

						Course.Register.TIndex = 0;
						_('cregtitle').innerHTML = '<strong class="err">Process Aborted by User</strong>';
						_('cregbtn').StopLoading();
						_('cregcntrbtn + cntrbtncregall').Hide();
						if (Course.Register.TRegNos.length > 1) _('cregallbtn + cunregallbtn').Show();
						Course.Register.TRegNos = [];
						//_('fixallbtn').Show();
					},
					OnError: function () {

						Course.Register.TIndex = 0;
						//_('resultfixtitle').innerHTML = '';
						_('cregtitle').innerHTML = '<strong class="err">Process Aborted due to Internal error</strong>';
						_('cregbtn').StopLoading();
						_('cregcntrbtn + cntrbtncregall').Hide();
						if (Course.Register.TRegNos.length > 1) _('cregallbtn + cunregallbtn').Show();
						Course.Register.TRegNos = [];
						//_('fixallbtn').Hide();
					}
				})
			}
		},
		IndRegAjax: [],
		RegAllStatus: 'Stop',
		RegAllTotal: 0,
		RegAllBtn: [],
		RegCurrent: 0,
		//fix all student
		RegAll: function (regallbtn) { //function to fix all
			if (Course.Register.RegAllStatus == "Play") {
				MessageBox.Show("Registration Process is already on-going");
				return;
			}
			var temptitle = _('cregtitle').innerHTML;
			_('cregtitle').innerHTML = 'Reading Loaded Student(s) ....';
			//get all loaded student to be fixed
			var allstud = _('indcregbtn');
			if (allstud == null) { //if no student loaded
				MessageBox.Show("No Student Loaded");
				_('cregtitle').innerHTML = temptitle;
				return;
			}


			//get the total number of student
			var totstud = allstud.length;
			Course.Register.RegAllBtn = allstud;
			Course.Register.RegAllTotal = totstud;
			_('cregtitle').innerHTML = '<strong>' + 0 + ' of ' + totstud + '</strong> - Registered ...';
			//get the current individual button
			var fbtn = Course.Register.RegAllBtn[Course.Register.RegCurrent];
			while (typeof fbtn == _UND && Course.Register.RegCurrent < Course.Register.RegAllTotal) { //if btn not exist go to the next
				Course.Register.RegCurrent++;
				fbtn = Course.Register.RegAllBtn[Course.Register.RegCurrent];
			}
			if (typeof fbtn != _UND) {
				regallbtn.style.display = 'none';
				Course.Register.RegAllStatus = "Play";
				_('cntrbtncregall').Show();
				_('cunregallbtn').Hide();
				Course.Register.IndReger(fbtn, true);
			} else {
				MessageBox.Show("No Valid Student Found");
				_('cregtitle').innerHTML = temptitle;
			}

		},


		//Individual fixer
		IndReger: function (obj, cregall) {

			cregall = cregall || false;
			//check if a valid button
			if (typeof obj == _UND || typeof obj.id == _UND) return;
			var btnid = obj.id;

			//get the regno
			var idarr = btnid.split("_");
			if (idarr.length == 2) {
				var regno = idarr[0];
				if (typeof Course.Register.IndRegAjax[regno] != _UND && Course.Register.IndRegAjax[regno] != null) {
					Course.Register.IndRegAjax[regno].abort();
				}

				//get the reg details
				//AK2019/NAS/BOT/003_regdatat
				var StudData = _(regno + '_regdatat');
				if (StudData == null) return;
				if (cregall) _('cregtitle').innerHTML = '<strong>' + (Course.Register.RegCurrent + 1) + ' of ' + Course.Register.RegAllTotal + '</strong> - Registering (' + regno + ') Course<small>(s)</small> ...';
				//indicate loading in the button
				obj.disabled = true;
				obj.innerHTML = '<i class="fa fa-spin fa-cog"></i>';
				//alert(StudData.textContent);
				//console.log(regno);
				//send regno to database
				Course.Register.IndRegAjax[regno] = new Ajax();
				Course.Register.IndRegAjax[regno].Post({
					PostData: "RegNo=" + escape(regno) + "&Type=1" + "&Num=-1&cregall=" + (cregall ? 1 : 0) + "&Data=" + encodeURIComponent(StudData.textContent) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/indcoursereg.php",
					OnProgress: function (delta) {

					},
					OnComplete: function (res, url, param) {
						//if(!Login.Authenticate(res))return;
						Course.Register.IndRegAjax[regno] = null;
						//get the regno
						var regno = param['RegNo'];
						//get the container
						/* var cont = _(regno + "_cdet");
						if (cont != null) {
							// alert(res);
							//pupulate the detail container
							cont.innerHTML = res;
						} */
						//console.log(res);
						resobj = JSON.parse(res);

						//update the display note if reg is successful or failed
						var obj = _(regno + "_cregbtn");
						var icon = "wrench";
						var notbx = _(regno + '_disnote');
						var msgbx = _(regno + '_umessage');
						if (typeof resobj.Success != _UND) {
							icon = "check";
							if (obj.classList.contains('danger')) {
								obj.classList.remove('danger');
								obj.classList.add('success');
							}

							if (notbx != null) notbx.innerHTML = '<span class="ok">' + resobj.Success + '</span>';
							if (msgbx != null) msgbx.innerHTML = '<span class="ok">' + resobj.Success + '</span>';
						} else {
							obj.classList.remove('success');
							obj.classList.add('danger');
							if (notbx != null) notbx.innerHTML = '<span class="err">' + resobj.Error + '</span>';
							if (msgbx != null) msgbx.innerHTML = '<span class="err">' + resobj.Error + '</span>';
						}
						//enable fix button
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-' + icon + '"></i>';
						var fall = param['cregall'].ToNumber();
						//alert(param['cregall']);
						if (fall == 1) { //if called from cregall
							Course.Register.RegCurrent++; //increment current
							if (Course.Register.RegCurrent == Course.Register.RegAllTotal || Course.Register.RegAllStatus == "Stop") { //if no more 
								if (Course.Register.RegAllStatus == "Stop") {
									_('cregtitle').innerHTML = '<strong>' + Course.Register.RegCurrent + ' of ' + Course.Register.RegAllTotal + ' - <span  class="err">Course Registration Process Stoped</span></strong>';
								} else {
									_('cregtitle').innerHTML = '<strong class="ok">' + Course.Register.RegCurrent + ' Student<small>(s)</small> Courses Registered Successfully</strong>';
								}

								Course.Register.RegCurrent = Course.Register.RegAllTotal = 0; //reset
								Course.Register.RegAllBtn = [];
								_('cregallbtn').style.display = 'inline-block';
								_('cunregallbtn').style.display = 'inline-block';
								_('cntrbtncregall').style.display = 'none';
								Course.Register.RegAllStatus = "Stop";
							} else if (Course.Register.RegAllStatus == "Pause") { //if to be paused
								_('cregtitle').innerHTML = '<strong>' + Course.Register.RegCurrent + ' of ' + Course.Register.RegAllTotal + ' - <span class="altColor2">Registration Process Paused</span></strong>';
								_('cregallpausebtn').style.display = 'none';
								_('cregallplaybtn').style.display = 'inline-block';
								//_('fixallpausebtn').disabled = false;

							} else {
								//fix next student
								Course.Register.RegNext();
							}



						}
					},
					OnAbort: function (res, url, param) {
						//enable fix button
						var regno = param['RegNo'];
						var obj = _(regno + "_cregbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-wrench"></i>';
						var fall = _.ToNumber(param['cregall']);
						if (fall == 1) { //if called from cregall
							_('cregtitle').innerHTML = '<strong>' + Course.Register.RegCurrent + ' Student<small>(s)</small> Courses Registered Successfully</strong> - <span class="err">Process Aborted</span>';
							Course.Register.RegCurrent = Course.Register.RegAllTotal = 0; //reset
							Course.Register.RegAllBtn = [];
							_('cregallbtn').style.display = 'inline-block';
							_('cunregallbtn').style.display = 'inline-block';
							_('cntrbtncregall').style.display = 'none';
							Course.Register.RegAllStatus = "Stop";
						}
					},
					OnError: function (res, url, param) {
						//enable fix button
						var regno = param['RegNo'];
						var obj = _(regno + "_cregbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-wrench"></i>';
						var fall = _.ToNumber(param['cregall']);
						if (fall == 1) { //if called from cregall
							_('cregtitle').innerHTML = '<strong>' + Course.Register.RegCurrent + ' Student<small>(s)</small> Courses Registered Successfully</strong> - <span class="err">Error</span>';
							Course.Register.RegCurrent = Course.Register.RegAllTotal = 0; //reset
							Course.Register.RegAllBtn = [];
							_('cregallbtn').style.display = 'inline-block';
							_('cunregallbtn').style.display = 'inline-block';
							_('cntrbtncregall').style.display = 'none';
							Course.Register.RegAllStatus = "Stop";
						}
					}
				})
			}

		},
		//FixNext
		RegNext: function () {
			var fbtn = Course.Register.RegAllBtn[Course.Register.RegCurrent];
			while (typeof fbtn == _UND && Course.Register.RegCurrent < Course.Register.RegAllTotal) { //if btn not exist go to the next
				Course.Register.RegCurrent++;
				fbtn = Course.Register.RegAllBtn[Course.Register.RegCurrent];
			}
			if (typeof fbtn != _UND) { //if btn found
				Course.Register.IndReger(fbtn, true);
			} else { // if not found
				_('cregtitle').innerHTML = '<strong class="ok">' + Course.Register.RegCurrent + ' Student<small>(s)</small> Courses Registered Successfully</strong>';
				Course.Register.RegCurrent = Course.Register.RegAllTotal = 0; //reset
				Course.Register.RegAllBtn = [];
				_('cregallbtn').style.display = 'inline-block';
				_('cunregallbtn').style.display = 'inline-block';
				_('cntrbtncregall').style.display = 'none';
				Course.Register.RegAllStatus = "Stop";
			}
		},
		//FixAll Controls
		//Stop
		RegAllStop: function () {
			//if playing or paused
			if (Course.Register.RegAllStatus != "Stop") {
				if (Course.Register.RegAllStatus == "Pause") { //if currently paused
					_('cregtitle').innerHTML = '<strong>' + Course.Register.RegCurrent + ' of ' + Course.Register.RegAllTotal + ' - <span class="err">Registration Process Stoped</span></strong>';
					Course.Register.RegCurrent = Course.Register.RegAllTotal = 0; //reset
					Course.Register.RegAllBtn = [];
					_('cregallbtn').style.display = 'inline-block';
					_('cunregallbtn').style.display = 'inline-block';
					_('cntrbtncregall').style.display = 'none';
					_('cregallplaybtn').style.display = 'none';
					_('cregallpausebtn').style.display = 'inline-block';
					Course.Register.RegAllStatus = 'Stop';
				} else {
					Course.Register.RegAllStatus = 'Stop';
					_('cregtitle').innerHTML = 'Stoping ...';
				}



				//_('cregallpausebtn').disabled = true;
			}

		},
		//Pause
		RegAllPause: function () {
			//if paused
			if (Course.Register.RegAllStatus == "Play") {
				Course.Register.RegAllStatus = 'Pause';
				_('cregtitle').innerHTML = 'Pausing ...';
				//_('cregallpausebtn').disabled = true;
			}

		},
		//Play
		RegAllPlay: function () {
			//if paused
			if (Course.Register.RegAllStatus == "Pause") {
				Course.Register.RegAllStatus = 'Play';
				_('cregtitle').innerHTML = 'Resuming ...';
				_('cregallplaybtn').style.display = 'none';
				_('cregallpausebtn').style.display = 'inline-block';
				//fix next student
				Course.Register.RegNext();
			}

		},
		UnIndRegAjax: [],
		UnRegAllStatus: 'Stop',
		UnRegAllTotal: 0,
		UnRegAllBtn: [],
		UnRegCurrent: 0,
		//fix all student
		UnRegAll: function (unregallbtn) { //function to fix all
			if (Course.Register.UnRegAllStatus == "Play") {
				MessageBox.Show("Delete Process is already on-going");
				return;
			}
			var temptitle = _('cregtitle').innerHTML;
			_('cregtitle').innerHTML = 'Reading Loaded Student(s) ....';
			//get all loaded student to be fixed
			var allstud = _('unregcbtn');
			if (allstud == null) { //if no student loaded
				MessageBox.Show("Registration Not Found, Reload Student to Update List");
				_('cregtitle').innerHTML = temptitle;
				return;
			}


			//get the total number of student
			var totstud = allstud.length;
			Course.Register.UnRegAllBtn = allstud;
			Course.Register.UnRegAllTotal = totstud;
			_('cregtitle').innerHTML = '<strong>' + 0 + ' of ' + totstud + '</strong> - Unregistered ...';
			//get the current individual button
			var fbtn = Course.Register.UnRegAllBtn[Course.Register.UnRegCurrent];
			while (typeof fbtn == _UND && Course.Register.UnRegCurrent < Course.Register.UnRegAllTotal) { //if btn not exist go to the next
				Course.Register.UnRegCurrent++;
				fbtn = Course.Register.UnRegAllBtn[Course.Register.UnRegCurrent];
			}
			if (typeof fbtn != _UND) {
				unregallbtn.style.display = 'none';
				Course.Register.UnRegAllStatus = "Play";
				_('cntrbtncunregall').Show();
				_('cregallbtn').Hide();
				Course.Register.UnIndReger(fbtn, true);
			} else {
				MessageBox.Show("No Valid Student Found");
				_('cregtitle').innerHTML = temptitle;
			}

		},
		//Individual fixer
		UnIndReger: function (obj, cregall) {

			cregall = cregall || false;
			//check if a valid button
			if (typeof obj == _UND || typeof obj.id == _UND) return;
			var btnid = obj.id;

			//get the regno
			var idarr = btnid.split("_");
			if (idarr.length >= 2) {
				var regno = idarr[0];
				var cid = idarr[1]; //course reg id
				if (typeof Course.Register.UnIndRegAjax[regno] != _UND && Course.Register.UnIndRegAjax[regno] != null) {
					Course.Register.UnIndRegAjax[regno].abort();
				}

				//get the reg details
				//AK2019/NAS/BOT/003_regdatat
				var StudData = _(regno + '_regdatat');
				if (StudData == null) return;
				if (cregall) _('cregtitle').innerHTML = '<strong>' + (Course.Register.UnRegCurrent + 1) + ' of ' + Course.Register.UnRegAllTotal + '</strong> - Deleting (' + regno + ') Course<small>(s)</small> ...';
				/* 	var unregbtn = _(param[0] + "_unregbtn");
				var modifybtn = _(param[0] + "_modifybtn");
				var cregbtn = _(param[0] + "_cregbtn");
				unregbtn.disabled = true;
				modifybtn.disabled = true;
				cregbtn.disabled = true;
				unregbtn.innerHTML = '<i class="fa fa-spin fa-cog"></i> Deleting ...'; */
				_(regno + '_disnote').innerHTML = "<span class='err'>Deleting ...<span>";
				//indicate loading in the button
				obj.disabled = true;
				obj.innerHTML = '<i class="fa fa-spin fa-cog"></i> Deleting ...';
				//alert(StudData.textContent);
				//console.log(regno);
				var cregalldata = cregall ? 1 : 0;
				//send regno to database
				Course.Register.UnIndRegAjax[regno] = new Ajax();
				Course.Register.UnIndRegAjax[regno].Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Course/unregister.php",
					PostData: "cid=" + escape(cid) + "&regno=" + escape(regno) + "&cregall=" + escape(cregalldata) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {

					},
					OnComplete: function (res, url, param) {
						//if(!Login.Authenticate(res))return;
						Course.Register.UnIndRegAjax[regno] = null;
						//get the regno
						var regno = param['regno'];

						var notbx = _(regno + '_disnote');
						// var msgbx = _(regno + '_umessage');
						if (res == "#") { //unregister success
							notbx.innerHTML = "<span class='err'>Unregisterd Successfully<span>";
							obj.Hide();
							//modifybtn.Hide();
							//cregbtn.Hide();
						} else {
							obj.innerHTML = '<i class="fa fa-trash"></i> Unregister';
							obj.disabled = false;
							//modifybtn.disabled = false;
							//cregbtn.disabled = false;
							// MessageBox.Show(res);
							notbx.innerHTML = "<span class='err'>" + res + "<span>";
						}
						/* 	if (typeof resobj.Success != _UND) {
								icon = "check";
								if (obj.classList.contains('danger')) {
									obj.classList.remove('danger');
									obj.classList.add('success');
								}
	
								if (notbx != null) notbx.innerHTML = '<span class="ok">' + resobj.Success + '</span>';
								if (msgbx != null) msgbx.innerHTML = '<span class="ok">' + resobj.Success + '</span>';
							} else {
								obj.classList.remove('success');
								obj.classList.add('danger');
								if (notbx != null) notbx.innerHTML = '<span class="err">' + resobj.Error + '</span>';
								if (msgbx != null) msgbx.innerHTML = '<span class="err">' + resobj.Error + '</span>';
							} */
						//enable fix button
						obj.disabled = false;
						// obj.innerHTML = '<i class="fa fa-' + icon + '"></i>';
						var fall = param['cregall'].ToNumber();
						//alert(param['cregall']);
						if (fall == 1) { //if called from cregall
							Course.Register.UnRegCurrent++; //increment current
							if (Course.Register.UnRegCurrent == Course.Register.UnRegAllTotal || Course.Register.UnRegAllStatus == "Stop") { //if no more 
								if (Course.Register.UnRegAllStatus == "Stop") {
									_('cregtitle').innerHTML = '<strong>' + Course.Register.UnRegCurrent + ' of ' + Course.Register.UnRegAllTotal + ' - <span  class="err">Delete Process Stoped</span></strong>';
								} else {
									_('cregtitle').innerHTML = '<strong class="ok">' + Course.Register.UnRegCurrent + ' Student<small>(s)</small> Courses Deleted Successfully</strong>';
								}

								Course.Register.UnRegCurrent = Course.Register.UnRegAllTotal = 0; //reset
								Course.Register.UnRegAllBtn = [];
								_('cregallbtn').style.display = 'inline-block';
								_('cunregallbtn').style.display = 'inline-block';
								_('cntrbtncunregall').style.display = 'none';
								Course.Register.UnRegAllStatus = "Stop";
							} else if (Course.Register.UnRegAllStatus == "Pause") { //if to be paused
								_('cregtitle').innerHTML = '<strong>' + Course.Register.UnRegCurrent + ' of ' + Course.Register.UnRegAllTotal + ' - <span class="altColor2">Delete Process Paused</span></strong>';
								_('cunregallpausebtn').style.display = 'none';
								_('cunregallplaybtn').style.display = 'inline-block';
								//_('fixallpausebtn').disabled = false;

							} else {
								//fix next student
								Course.Register.UnRegNext();
							}



						}
					},
					OnAbort: function (res, url, param) {
						//enable fix button
						var regno = param['regno'];
						var obj = _(regno + "_unregbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-trash"></i> Unregister';
						var fall = _.ToNumber(param['cregall']);
						if (fall == 1) { //if called from cregall
							_('cregtitle').innerHTML = '<strong>' + Course.Register.UnRegCurrent + ' Student<small>(s)</small> Courses Deleted Successfully</strong> - <span class="err">Process Aborted</span>';
							Course.Register.UnRegCurrent = Course.Register.UnRegAllTotal = 0; //reset
							Course.Register.UnRegAllBtn = [];
							_('cregallbtn').style.display = 'inline-block';
							_('cunregallbtn').style.display = 'inline-block';
							_('cntrbtncunregall').style.display = 'none';
							Course.Register.UnRegAllStatus = "Stop";
						}
					},
					OnError: function (res, url, param) {
						//enable fix button
						var regno = param['regno'];
						var obj = _(regno + "_unregbtn");
						obj.disabled = false;
						obj.innerHTML = '<i class="fa fa-trash"></i> Unregister';
						var fall = _.ToNumber(param['cregall']);
						if (fall == 1) { //if called from cregall
							_('cregtitle').innerHTML = '<strong>' + Course.Register.UnRegCurrent + ' Student<small>(s)</small> Courses Deleted Successfully</strong> - <span class="err">Error</span>';
							Course.Register.UnRegCurrent = Course.Register.UnRegAllTotal = 0; //reset
							Course.Register.UnRegAllBtn = [];
							_('cregallbtn').style.display = 'inline-block';
							_('cunregallbtn').style.display = 'inline-block';
							_('cntrbtncunregall').style.display = 'none';
							Course.Register.UnRegAllStatus = "Stop";
						}
					}
				})
			}

		},
		//FixNext
		UnRegNext: function () {
			var fbtn = Course.Register.UnRegAllBtn[Course.Register.UnRegCurrent];
			while (typeof fbtn == _UND && Course.Register.UnRegCurrent < Course.Register.UnRegAllTotal) { //if btn not exist go to the next
				Course.Register.UnRegCurrent++;
				fbtn = Course.Register.UnRegAllBtn[Course.Register.UnRegCurrent];
			}
			if (typeof fbtn != _UND) { //if btn found
				Course.Register.UnIndReger(fbtn, true);
			} else { // if not found
				_('cregtitle').innerHTML = '<strong class="ok">' + Course.Register.UnRegCurrent + ' Student<small>(s)</small> Courses Deleted Successfully</strong>';
				Course.Register.UnRegCurrent = Course.Register.UnRegAllTotal = 0; //reset
				Course.Register.UnRegAllBtn = [];
				_('cregallbtn').style.display = 'inline-block';
				_('cunregallbtn').style.display = 'inline-block';
				_('cntrbtncunregall').style.display = 'none';
				Course.Register.UnRegAllStatus = "Stop";
			}
		},
		//FixAll Controls
		//Stop
		UnRegAllStop: function () {
			//if playing or paused
			if (Course.Register.UnRegAllStatus != "Stop") {
				if (Course.Register.UnRegAllStatus == "Pause") { //if currently paused
					_('cregtitle').innerHTML = '<strong>' + Course.Register.UnRegCurrent + ' of ' + Course.Register.UnRegAllTotal + ' - <span class="err">Delete Process Stoped</span></strong>';
					Course.Register.UnRegCurrent = Course.Register.UnRegAllTotal = 0; //reset
					Course.Register.UnRegAllBtn = [];
					_('cregallbtn').style.display = 'inline-block';
					_('cunregallbtn').style.display = 'inline-block';
					_('cntrbtncunregall').style.display = 'none';
					_('cunregallplaybtn').style.display = 'none';
					_('cunregallpausebtn').style.display = 'inline-block';
					Course.Register.UnRegAllStatus = 'Stop';
				} else {
					Course.Register.UnRegAllStatus = 'Stop';
					_('cregtitle').innerHTML = 'Stoping ...';
				}



				//_('cregallpausebtn').disabled = true;
			}

		},
		//Pause
		UnRegAllPause: function () {
			//if paused
			if (Course.Register.UnRegAllStatus == "Play") {
				Course.Register.UnRegAllStatus = 'Pause';
				_('cregtitle').innerHTML = 'Pausing ...';
				//_('cregallpausebtn').disabled = true;
			}

		},
		//Play
		UnRegAllPlay: function () {
			//if paused
			if (Course.Register.UnRegAllStatus == "Pause") {
				Course.Register.UnRegAllStatus = 'Play';
				_('cregtitle').innerHTML = 'Resuming ...';
				_('cunregallplaybtn').style.display = 'none';
				_('cunregallpausebtn').style.display = 'inline-block';
				//fix next student
				Course.Register.UnRegNext();
			}

		}
	}

}

/************************************************************************************************** */
//*Portal
/************************************************************************************************** */
var Portal = {
	Appearance: {
		Ajax: new Ajax(),

		PerformSave: function () {
			var footnote = _("footnote").TextContent();
			var basecolor = _("basecolor").value;
			var forcolor = _("forecolor").value;
			var datas = "footnote=" + escape(footnote) + "&basecolor=" + escape(basecolor) + "&forecolor=" + escape(forcolor);
			Portal.Appearance.Ajax.Post({
				PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + 'Pages/Scripts/Portal/saveappearace.php',
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(1).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//MessageBox.Show(res);
					Tabs.Tab("Portal").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Portal").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show(""+res);
					Tabs.Tab("Portal").ProgressGet(1).ProgressTo(100, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
				}
			});
			//alert(datas);
			//method code
		},

		//Add Predefined Method
		Save: function () {
			_('grpappearanceobjfrm').submit();
		}
	},

	WallPaper: {
		Ajax: new Ajax(),
		SelectFunc: function (obj) {
			var wallID = obj.id;
			//get wall details
			Portal.WallPaper.Ajax.Post({
				PostData: "wallid=" + wallID + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']),
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Portal/getwalldet.php",
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(Math.floor(delta * 80));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					var char = res.substr(0, 1);
					if (char == "#" || char == "*") {
						MessageBox.Show(res);
					} else {
						var rtn = JSON.parse(res);
						if (rtn) {
							var wallheader = rtn.wallheader;
							var walltxt = rtn.walltext;
							var wallpaper = rtn.wallpaper;
							//set n page
							if (wallpaper == "") {
								_('walimage').ClearImagePad();
							} else {
								_('walimage').SetPadImage('Files/UserImages/wallpapers/bgs/' + wallpaper);
							}

							_('wallheadertxt').SetText(wallheader);
							_('walltxt').SetText(walltxt);
							if (rtn.state) {
								_('wallstatus').SwitchOn();
							} else {
								_('wallstatus').SwitchOff();
							}
						}
					}
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(100);
					Tabs.HideSideBar('Portal', 0);
				},
				OnAbort: function (res) {

					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					// MessageBox.Show(""+res);
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
				}
			});
		},
		Save: function () {
			//alert(_('wallpapertn').SelectedObject());
			var wallheader = _('wallheadertxt').TextContent().Trim();
			// alert(_('wallheadertxt_inp').value)
			var walltxt = _('walltxt').TextContent().Trim();
			if (wallheader == "" || walltxt == "") {
				MessageBox.Show("Wall Header and Text are Compulsary");
				return;
			}

			//validate passport
			if (!_('walimage').IsSet()) {
				MessageBox.Show("Wall Image is Required");
				return;
			}
			//var datas = "wallheadertxt="+wallheader+"&walltxt="+walltxt+"&"
			var datas = Page.DataString("objwallpapergrpelem");
			//alert(datas);
			//var state = _('wallstatus').GetStatus();
			//get the selected wallpaper
			var selwallpaper = _('class_wallpapertn & sel');
			// var selid = 0;
			if (selwallpaper == null) {
				datas += "&selid=0";
				//new entrying
				OptionBox.Show({
					Title: "Add New Wallpaper",
					Options: [{
						Logo: "plus",
						Title: "Add Wallpaper",
						Info: "Add as new wallpaper",
						Function: function (param) {
							Portal.WallPaper.PerformSave(param);
							//MessageBox.Show('All');
						},

						Parameter: datas
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort Operation",
						Function: function () {
							MessageBox.Show("Operation Aborted");
						}
						//Parameter:selectedRegNo
					}]

				});
			} else {
				datas += "&selid=" + selwallpaper.id;
				Portal.WallPaper.PerformSave(datas);
			}
			//alert('Save');
		},

		PerformSave: function (datas) { //perform save operation
			Portal.WallPaper.Ajax.Post({
				PostData: datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + 'Pages/Scripts/Portal/savewallpaper.php',
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//Portal.WallPaper.Refresh();
					//MessageBox.Show(res);
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
				},
				OnAbort: function (res) {

					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show(""+res);
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
				}
			});
		},
		Refresh: function () {
			_('wallpaperbx').innerHTML = '<div style="margin-top:20px;text-align:center"><i class="fa fa-sync fa-spin"></i></div>';
			"wallpaperbx".HTML(configdata.Core + "cportal/Pages/Scripts/Portal/loadwallpapers.php?SubDir=" + encodeURIComponent(configdata.SubDir), function () { }, function () { });
		},
		Delete: function () {
			var selwallpaper = _('class_wallpapertn & sel');
			// var selid = 0;
			if (selwallpaper == null) {
				MessageBox.Show("No Wallpaper Selected");
			} else {
				OptionBox.Show({
					Title: "Delete Wallpaper",
					Options: [{
						Logo: "trash",
						Title: "Delete Wallpaper",
						Info: "Completely Remove Selected Wallpaper",
						Function: function (param) {
							Portal.WallPaper.PerformDelete(param);
							//MessageBox.Show('All');
						},

						Parameter: selwallpaper.id
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Abort Operation",
						Function: function () {
							MessageBox.Show("Operation Aborted");
						}
						//Parameter:selectedRegNo
					}]

				});
			}
		},
		PerformDelete: function (wallid) {
			Portal.WallPaper.Ajax.Post({
				PostData: "wallid=" + wallid + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				Action: configdata['Core'] + "cportal/" + 'Pages/Scripts/Portal/deletewallpaper.php',
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//Portal.WallPaper.Refresh();
					//MessageBox.Show(res);
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + res.Replace('"', '\"') + '");');
					var chr = res.Trim().substr(0, 1);
					if (chr == "*") { //if successful
						Portal.WallPaper.Refresh();
						Portal.WallPaper.PerformClear();
					}

				},
				OnAbort: function (res) {

					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
				},
				OnError: function (res) {
					//MessageBox.Show(""+res);
					Tabs.Tab("Portal").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error: ' + res.Replace('"', '\"') + '");');
				}
			});
		},
		Clear: function () {
			var selwallpaper = _('class_wallpapertn & sel');
			if (selwallpaper != null) {
				selwallpaper.classList.remove("sel");
			}
			//set n page
			Portal.WallPaper.PerformClear();
		},
		PerformClear: function () {
			_('walimage').ClearImagePad();
			_('wallheadertxt').SetText("");
			_('walltxt').SetText("");
			_('wallstatus').SwitchOff();
		}

	},
	Menus: {
		Loading: false,
		Ajax: new Ajax(),
		Load: function (value, key, itemname, silentmode, rowcnt, setsilentmode) {
			if (School.Structure.Loading) return;
			silentmode = silentmode || 0;
			rowcnt = rowcnt || 0;
			setsilentmode = setsilentmode || -1; //if 0 or 1 will update the silent mode
			if (silentmode == 1 && rowcnt > 1) {
				MessageBox.Show("Only the First Record is valid in Silent Mode");
				return;
			}
			var sdata = _('pmenudatabx').textContent;
			var loading = _('menusload');
			var loadingtitle = _('menusloadtitle');
			loadingtitle.textContent = itemname == 'a' ? "Application" : itemname + " Structure";
			loading.Show();
			Portal.Menus.Loading = true;
			Portal.Menus.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Portal/loadmenus.php",
				PostData: "Key=" + key + "&Value=" + value + "&Name=" + itemname + "&Data=" + escape(sdata) + "&SetSilentMode=" + setsilentmode + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					loading.Hide();
					Portal.Menus.Loading = false;
					if (res.Trim() == "#") {
						MessageBox.Show("#Invalid Parameter")
						//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,'MessageBox.Show("#Invalid Parameter")');
						return;
					}
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(100);
					if (setsilentmode > -1) {
						var ww = (setsilentmode == 1) ? "Enabled" : "Disabled";
						MessageBox.Show("*Silent Mode " + ww);
					}
					_('menusetinner').innerHTML = res;
				},
				OnError: function (res) {
					loading.Hide();
					Portal.Menus.Loading = false;
					MessageBox.Show("#Internal Error: " + res);
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,"MessageBox.Show('#Internal Error: "+res+"')");
				},
				OnAbort: function (res) {
					loading.Hide();
					Portal.Menus.Loading = false;
					MessageBox.Show('Operation Aborted');
					//Tabs.Tab("School").ProgressGet(0).ProgressTo(-1,"MessageBox.Show('Operation Aborted')");
				}
			});
		},
		Refresh: function (setSilentMode) {
			setSilentMode = setSilentMode || -1;
			//get the current details
			var curdetobj = JSON.parse(_('pmenudatabx').textContent);

			var curdisdet = curdetobj[curdetobj['Details']['Current']];
			console.log(curdisdet);
			//alert(curdisdet['Prev']);
			if (curdisdet['Prev'] != "") {
				//console.log(curdetobj)
				var prvdet = curdetobj[curdisdet['Prev']];
				//perform a reload
				Portal.Menus.Load(prvdet["ID"], curdisdet['Prev'], prvdet["Loaded"], 0, 0, setSilentMode);
			} else {
				//alert('no prev');
				Portal.Menus.Load(0, 'a', '');
			}


		},
		Save: function () {
			/* var SilentMode = _('schstrcsilentmode');
			var silentmd = (SilentMode != null)?SilentMode.GetStatus():0; */
			var sdata = _('pmenudatabx').textContent;
			var spreads = _('pmenustrss').GetDataString();
			//alert(sdata);
			//console.log(spreads);
			//var currentStrucName = _('currenStrucName').textContent;
			//alert(currentStrucName);return;
			Portal.Menus.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Portal/savemenu.php",
				/* PostData: "Data=" + encodeURIComponent(sdata) + "&Sheet=" + encodeURIComponent(spreads) + "&SubDir=" + encodeURIComponent(configdata['SubDir']), */
				Data: {Data: sdata ,Sheet:spreads ,SubDir: configdata['SubDir']},
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(2).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					if (res.Trim() != "#") {
						//alert(res);
						Tabs.Tab("Portal").ProgressGet(2).ProgressTo(-1, 'MessageBox.Show("' + res + '")');
						return;
					}
					//alert('Success');
					Tabs.Tab("Portal").ProgressGet(2).ProgressTo(100, 'MessageBox.Show("*Saved Successfully<br />System will Reload Sheet Automatically");Portal.Menus.Refresh()');
					//_('schstrcinner').innerHTML = res;
				},
				OnError: function (res) {
					Tabs.Tab("Portal").ProgressGet(2).ProgressTo(-1, "MessageBox.Show('#Internal Error: " + res + "')");
				},
				OnAbort: function (res) {
					Tabs.Tab("Portal").ProgressGet(2).ProgressTo(-1, "MessageBox.Show('Operation Aborted')");
				}
			});
		}
	},
	PMSetting: {
		Ajax: new Ajax(),
		Save: () => {
			var spreads = _('sprshmenuset').GetDataString();
			Portal.PMSetting.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Portal/savepmsetting.php",
				PostData: "Sheet=" + encodeURIComponent(spreads) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Portal").ProgressGet(3).ProgressTo(Math.floor(delta * 50));
				},
				OnComplete: function (res) {
					// if(res.Trim() != "#"){
					//alert(res);
					Tabs.Tab("Portal").ProgressGet(3).ProgressTo(100);
					MessageBox.Show(res);
					// }

					//_('schstrcinner').innerHTML = res;
				},
				OnError: function (res) {
					Tabs.Tab("Portal").ProgressGet(3).ProgressTo(-1);
					MessageBox.Show("#Internal error: " + res);
				},
				OnAbort: function (res) {
					Tabs.Tab("Portal").ProgressGet(3).ProgressTo(-1);
					MessageBox.Show("Operation Aborted");
				}
			});
		}
	}

}

/* ********************Application******************** */
var Application = {
	AppUpdate: {
		Ajax: new Ajax(),
		//Add a new setup file
		AddSetup: function (obj) {
			//alert(obj.id);
			obj.BrowseFile(function () { }, function (s) {

				var data = _('appaddsetup').FileDataString();
				MessageBox.Show("Verifying and Adding Setup ...");
				//alert(_('appaddsetup_file').files[0]);

				Application.AppUpdate.Ajax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/addsetup.php",
					PostData: "appaddsetup_file=?" + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(Math.floor(delta * 70));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						//console.log(res);
						var resobj = JSON.parse(res);
						if (typeof resobj.Setups != _UND) { //valid responce
							var disbx = _('supspshtbx');
							disbx.innerHTML = resobj.Setups;
							MessageBox.Show(resobj.Message);
							if (resobj.Inuse == 1) {
								Application.AppUpdate.UpdateOption(resobj.ID, resobj.OptionMarkup, resobj.Version);
							} else {
								Application.AppUpdate.InstallOption(resobj.ID, resobj.OptionMarkup, resobj.Version);
							}

						} else if (typeof resobj.Message != _UND) {
							//MessageBox.Show();
							Tabs.Tab("Application").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + resobj.Message.Replace('"', '\"') + '");');
						} else {
							//
							//MessageBox.Show("".res);
							Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error: Unknown Error : ' + res.Replace('"', '\"') + '");');
						}


						//CoverScreen.Close(_('addnewsetup'));
					},
					OnError: function (res) {
						//MessageBox.Show("".res);
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error:' + res.Replace('"', '\"') + '");');
						//CoverScreen.Close(_('addnewsetup'));
					},
					OnAbort: function (res) {

						Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
						//CoverScreen.Close(_('addnewsetup'));
					}
					//})

				});

			}, 0, ".epx");
		},
		InstallOption: function (ID, Mk, Version) {
			OptionBox.Show({
				Title: "Installation",
				Logo: 'database',
				TitleHTML: Mk,
				Options: [{
					Logo: "cogs",
					Title: "Install Now",
					Info: "Running setup will be uninstalled before Installation",
					Function: function (ID) {
						Application.AppUpdate.PerformInstall(ID[0], ID[1], 1);
						//MessageBox.Show('All');
					},

					Parameter: [ID, Version]
				},
				{
					Logo: "trash",
					Title: "Remove Setup",
					Info: "Remove Setups From List",
					Function: function (ID) {
						Application.AppUpdate.Remove(ID);
					},

					Parameter: ID
				}]

			});
		},
		UninstallOption: function (ID, Mk, Version) {
			OptionBox.Show({
				Title: "Unnstallation",
				Logo: 'trash',
				TitleHTML: Mk,
				Options: [{
					Logo: "trash",
					Title: "Uninstall Now",
					Info: "Note: it recommended to uninstall by Installing a new version",
					Function: function (ID) {
						Application.AppUpdate.PerformUninstall(ID[0], ID[1], 1);
						//MessageBox.Show('All');
					},

					Parameter: [ID, Version]
				}]

			});
		}
		,
		UpdateOption: function (ID, Mk, Version) {
			OptionBox.Show({
				Title: "Update",
				Logo: 'cogs',
				TitleHTML: Mk,
				Options: [{
					Logo: "cog",
					Title: "Update Running Version",
					Info: "Selected Setup is same version as the Running, hense system will attempt to update the running version",
					Function: function (ID) {
						Application.AppUpdate.PerformInstall(ID[0], ID[1], 1);
						//MessageBox.Show('All');
					},

					Parameter: [ID, Version]
				}]

			});
		},
		InstallAjax: new Ajax(),
		FormTitle: function (Version, title) {
			return "Installing Eduporta " + Version + "<br /> <small>Please Wait, Installation migth take a while</small> <br /> <small>" + title + "</small>";
		},
		PerformInstall: function (ID, Version, setup) {
			if (setup == 1) {
				CoverScreen.ShowLoading("appinstallloading", Application.AppUpdate.FormTitle(Version, "Copying Files ..."), "Application.AppUpdate.InstallAjax.Abort()");
			}

			//return;
			Application.AppUpdate.InstallAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/install.php",
				PostData: "id=" + ID + "&group=" + setup + "&version=" + escape(Version) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var resobj = JSON.parse(res);

					if (typeof resobj.Done != _UND) {
						if (typeof resobj.NextSetup != _UND) { //next exist
							CoverScreen.SetTitle('appinstallloading', Application.AppUpdate.FormTitle(param['version'], resobj.NextOperation));
							Application.AppUpdate.PerformInstall(param['id'], param['version'], resobj.NextSetup);
							return;
						} else if (typeof resobj.Finish != _UND) {
							location.reload(true);
						} else {
							//Application.AppUpdate.Activate(param['id'],param['version']);
							OptionBox.Show({
								Title: "Activation",
								Logo: 'cogs',
								Options: [{
									Logo: "cog",
									Title: "Activate Eduporta " + param['version'],
									Info: "Activating the installed Version will deactivate the running version",
									Function: function (ID) {
										Application.AppUpdate.PerformInstall(ID[0], ID[1], 6);
										//MessageBox.Show('All');
									},
									Parameter: [param['id'], param['version']]
								}]

							});
						}

					}
					MessageBox.Show(resobj.Message);
					//console.log(resobj.Query);
					CoverScreen.Close(_('appinstallloading'));
				},
				OnError: function (res) {
					MessageBox.Show("#Internal Error:".res);
					CoverScreen.Close(_('appinstallloading'));
					//CoverScreen.Close(_('addnewsetup'));
				},
				OnAbort: function (res) {
					MessageBox.Show("Operation Aborted");
					CoverScreen.Close(_('appinstallloading'));
					//CoverScreen.Close(_('addnewsetup'));
				}
				//})

			});
		},

		FormPatchTitle: function (title) {
			return "Patching System<br /> <small>Please Wait, migth take a while</small> <br /> <small>" + title + "</small>";
		},
		ExePatch: function (patch, sid, data, start) {
			if (start == true) {
				CoverScreen.ShowLoading("appinstallloading", Application.AppUpdate.FormPatchTitle("Executing Patch ..."));
			}
			Application.AppUpdate.InstallAjax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/install.php",
				PostData: "id=" + sid + "&group=5&version=&Patch=" + escape(patch) + "&PatchParam=" + escape(data) + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var resobj = JSON.parse(res);

					if (typeof resobj.Done != _UND) {
						if (typeof resobj.NextSetup != _UND) { //next exist
							CoverScreen.SetTitle('appinstallloading', Application.AppUpdate.FormPatchTitle(resobj.NextOperation));
							Application.AppUpdate.ExePatch(param['Patch'], param['id'], param['PatchParam'], false);

						} else {
							MessageBox.Show("*Patch Executed Successfully");
							CoverScreen.Close(_('appinstallloading'));
						}
						//console.log(JSON.stringify(resobj));
						return;
					}
					MessageBox.Show(resobj.Message);
					//console.log(resobj.Message);
					CoverScreen.Close(_('appinstallloading'));
				},
				OnError: function (res) {
					MessageBox.Show("#Internal Error:".res);
					CoverScreen.Close(_('appinstallloading'));
					//CoverScreen.Close(_('addnewsetup'));
				},
				OnAbort: function (res) {
					MessageBox.Show("Operation Aborted");
					CoverScreen.Close(_('appinstallloading'));
					//CoverScreen.Close(_('addnewsetup'));
				}
				//})

			});
		},

		Activate: function (id, version) {
			//Application.AppUpdate.PerformInstall(param['id'],param['version'],resobj.NextSetup);
			//reload the browser

		},

		Remove: function (ID) {
			MessageBox.Show("Remove:" + ID);
		},

		PerformUninstall: function (ID) {
			MessageBox.Show("Install:" + ID);
		},

		Options: function (ID) {
			//get the setup details
			Application.AppUpdate.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/setupdet.php",
				PostData: "id=" + ID + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Application").ProgressGet(0).ProgressTo(Math.floor(delta * 70));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					var resobj = JSON.parse(res);
					if (typeof resobj.OptionMarkup != _UND) { //valid responce
						if (resobj.Inuse == 1) {
							Application.AppUpdate.UninstallOption(resobj.ID, resobj.OptionMarkup, resobj.Version);
						} else {
							Application.AppUpdate.InstallOption(resobj.ID, resobj.OptionMarkup, resobj.Version);
						}

					} else if (typeof resobj.Message != _UND) {
						//'MessageBox.Show("'+res.Replace('"','\"')+'");'
						//	MessageBox.Show();
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("' + resobj.Message.Replace('"', '\"') + '");');
					} else {
						//MessageBox.Show("".res);
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error: Unknown Error : ' + res.Replace('"', '\"') + '");');
					}

					//Tabs.Tab("Application").ProgressGet(0).ProgressTo(100);	
				},
				OnError: function (res) {
					//MessageBox.Show("#Internal Error:".res);

					Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error:' + res.Replace('"', '\"') + '");');
					//CoverScreen.Close(_('addnewsetup'));
				},
				OnAbort: function (res) {

					Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					//CoverScreen.Close(_('addnewsetup'));
				}
				//})

			});
		},
		PatchAjax: new Ajax(),
		RunPatch: function (obj) {
			obj.BrowseFile(function () { }, function (s) {

				//	var data = _('apprunpatch').FileDataString();
				MessageBox.Show("Verifying Patch Script ...");
				Application.AppUpdate.PatchAjax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/chkpatch.php",
					PostData: "apprunpatch_file=?" + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
					OnProgress: function (delta) {
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(Math.floor(delta * 70));
					},
					OnComplete: function (res) {
						if (!Login.Authenticate(res)) return;
						var resobj = JSON.parse(res);
						if (typeof resobj['Error'] != _UND) {
							MessageBox.Show(resobj['Error']); return;
						}
						var patch = resobj['Patch'];
						var sid = resobj['SID'];
						var TitleHTML = resobj['MarkUp'];
						//display Options
						OptionBox.Show({
							Title: "Execute Patch",
							Logo: 'cogs',
							ShowClose: false,
							TitleHTML: TitleHTML,
							Options: [{
								Logo: "cog",
								Title: "Execute Patch Now",
								Info: "Execute Selected Patch Script. <br /> Note:It is recommended to Run a Data Backup before executing Patch",
								Function: function (patch) {
									var dt = {};
									//get all data
									var patchfields = _('ep_patch_field');
									if (patchfields != null) {
										patchfields = IsArray(patchfields) ? patchfields : [patchfields];

										for (var pf = 0; pf < patchfields.length; pf++) {
											var pfield = patchfields[pf];
											//console.log(pfield.TextContent());
											dt[pfield.id] = pfield.TextContent();
										}
									}
									//console.log(dt);
									var data = JSON.stringify(dt);
									Application.AppUpdate.ExePatch(patch[0], patch[1], data, true);
									//MessageBox.Show('All');
								},
								Parameter: [patch, sid]
							},
							{
								Logo: "trash",
								Title: "Abort",
								Info: "Abort Patch Execution",
								Function: function (patch) {
									Application.AppUpdate.AbortPatch(patch);
									//MessageBox.Show('All');
								},
								Parameter: patch
							}]

						});

						Tabs.Tab("Application").ProgressGet(0).ProgressTo(100);
						//CoverScreen.Close(_('addnewsetup'));
					},
					OnError: function (res) {
						//MessageBox.Show("".res);
						Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error:' + res.Replace('"', '\"') + '");');
						//CoverScreen.Close(_('addnewsetup'));
					},
					OnAbort: function (res) {

						Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
						//CoverScreen.Close(_('addnewsetup'));
					}
					//})

				});
			}, 0, ".php");
		},
		AbortPatch: function (patch) {
			Application.AppUpdate.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/abortpatch.php",
				PostData: "patch=" + patch + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					Tabs.Tab("Application").ProgressGet(0).ProgressTo(Math.floor(delta * 70));
				},
				OnComplete: function (res) {
					if (!Login.Authenticate(res)) return;
					//console.log(res);
					MessageBox.Show(res);

					Tabs.Tab("Application").ProgressGet(0).ProgressTo(100);
				},
				OnError: function (res) {
					//MessageBox.Show("".res);
					Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("#Internal Error:' + res.Replace('"', '\"') + '");');
					//CoverScreen.Close(_('addnewsetup'));
				},
				OnAbort: function (res) {

					Tabs.Tab("Application").ProgressGet(0).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');
					//CoverScreen.Close(_('addnewsetup'));
				}
				//})

			});
		},

		//Add Predefined Method
		Save: function () {
			//Save code

		},
		Clear: function () {
			//clear code
		},
		Print: function () {
			//print code
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	},
	AppSetting: {
		Save: () => {
			_('grpappsetfrm').submit();
		},
		Ajax: new Ajax,
		PerformSave: () => {
			var pagedata = Page.DataString("appsetelem");
			var appbgcolor = _("appbgcolor").value;
			var appthemecolor = _("appthemecolor").value;
			var iconsstr = _("schactsessionspsh").GetDataString();
			var data = pagedata + "&appbgcolorr=" + encodeURIComponent(appbgcolor) + "&appthemecolorr=" + encodeURIComponent(appthemecolor) + "&" + iconsstr;

			//alert(data);
			/* var imgpd = _("appicon");
				if (imgpd.IsSet()) {
			var passpFileobj = imgpd.GetPadFile();
					if (passpFileobj != null) {
						pagedata += "&" + passpFileobj.PostData;
					}
				} */
			Application.AppSetting.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Application/saveappset.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&" + data,
				OnProgress: function (delta) {
					Tabs.Tab("Application").ProgressGet(3).ProgressTo(Math.floor(delta * 70));
				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					//if(res != "#"){ //if error message sent
					MessageBox.Show(res);
					Tabs.Tab("Application").ProgressGet(3).ProgressTo(100);
				},
				OnError: function (res) {
					MessageBox.Show(res);
					Tabs.Tab("Application").ProgressGet(3).ProgressTo(-1);
					//CoverScreen.Close(_('addnewsetup'));
				},
				OnAbort: function (res) {
					MessageBox.Show("Operation Aborted");
					Tabs.Tab("Application").ProgressGet(3).ProgressTo(-1);
					//CoverScreen.Close(_('addnewsetup'));
				}
			});
			//
		}
	}

}

/* ********************Application******************** */

// CBt

var Cbt = {
	Manage: {
		Ajax: new Ajax(),
		GenLoader: new GenLoading({ StudyID: "cbtexmstudy", FacID: "cbtexmfac", DeptID: "cbtexmdept", ProgID: "cbtexmprog", LevelID: "cbtexmlvl", SemID: "cbtexmsemest" }),
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		//Add custom methods
		AddExam: function () {
			//TitleHTML:{Action: configdata['Core']+"cportal/Pages/Scripts/Entrance/loadfields.php",Data: "SubDir="+encodeURIComponent(configdata['SubDir'])},
			//alert('add exam');
			OptionBox.Show({
				Title: "Add New Exam",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/cbt/newexam.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
				Options: [{
					Logo: "plus",
					Title: "Add Now",
					Info: "Add a New Exam Entering",
					Function: function () {
						var reqired = _("textBx & ExamParamGrp & req err");
						if (reqired != null) { MessageBox.Show("Invalid Entering: All Fields are Required"); return }
						//get all data
						var data = Page.DataString("ExamParamGrp");
						//console.log(data);
						Cbt.Manage.AddExamReal(data);
					}
				}]

			});
			/* Cbt.Manage.Ajax.Post({
				Action:configdata['Core']+"cportal/"+"Pages/Scripts/cbt/newexam.php",
				PostData:"SubDir="+encodeURIComponent(configdata['SubDir']),
						OnProgress:function(delta){
		
				},
				OnComplete:function(res){
					if(!Login.Authenticate(res))return;
				//	if(res == "#"){MessageBox.Show("#Internal Error: Payment Type Not Found");return;}
					
					
				}
				 }); */
		},
		AddExamReal: function (data) {
			var userdet = Login.User();
			if (userdet == null) { MessageBox.Show("#Login User Identification Failed"); return; }
			var userID = userdet[0];
			Cbt.Manage.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/addexam.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&" + data + "&UID=" + userID,
				OnProgress: function (delta) {

				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					/* if(res != "#"){ //if error message sent
						MessageBox.Show(res);return;
					} */

					//check if created successfull
					try {
						retnval = JSON.parse(res);
						//MessageBox.Show(`*${retnval.EName} (${retnval.ECode}) Added Successfully`);
						Cbt.Manage.LoadQuestion(retnval.EID);
					} catch (error) {
						MessageBox.Show(res);
					}




				}
			});
		},

		/* CellFocus:function(obj){
		 var	objid = obj.id;
		 var objidarr = objid.split("_");
		 if(objidarr.length >= 5){ //if valid
				var colname = objidarr[3];
				if(colname != "CBTAns" && colname != "Medias")return;
				if(colname == "CBTAns"){
		   CBT.Manage.PopOption(objid);
				}else{
					CBT.Manage.PopMedia(objid);
				}
		 }
		},
 
		PopOption:function(cellid){
			CBT.Manage.Ajax.Post({
				Action:configdata['Core']+"cportal/"+"Pages/Scripts/cbt/qoptans.php",
				PostData:"cellId = "+escape(cellid)+"&SubDir="+encodeURIComponent(configdata['SubDir']),
						OnProgress:function(delta){
		
				},
				OnComplete:function(res,url,param){
					if(!Login.Authenticate(res))return;
				//	if(res == "#"){MessageBox.Show("#Internal Error: Payment Type Not Found");return;}
					
					OptionBox.Show({
						Title: "Question Options/Answer",
						TitleHTML:res,
						Options: [{
							Logo: "check",
							Title: "Finish",
							Info: "Specify Option and Answer to the Question",
							Function: function (cellid) {
								//var reqired = _("textBx & ExamParamGrp & req err");
				
							}
							,Parameter:cellid
						}]
				
					});	
				}
				 });
		},
		
 
		PopMedia:function(cellid){
			CBT.Manage.Ajax.Post({
				Action:configdata['Core']+"cportal/"+"Pages/Scripts/cbt/qmedia.php",
				PostData:"cellId = "+escape(cellid)+"&SubDir="+encodeURIComponent(configdata['SubDir']),
						OnProgress:function(delta){
		
				},
				OnComplete:function(res,url,param){
					if(!Login.Authenticate(res))return;
				//	if(res == "#"){MessageBox.Show("#Internal Error: Payment Type Not Found");return;}
					
					OptionBox.Show({
						Title: "Question Medias",
						TitleHTML:res,
						Options: [{
							Logo: "check",
							Title: "Finish",
							Info: "Save Question Medias",
							Function: function (cellid) {
								//var reqired = _("textBx & ExamParamGrp & req err");
							
							}
							,Parameter:cellid
						}]
				
					});	
				}
				 });
		},
		OptionChange: function(sw){
			var st = sw.GetStatus();
	  var cbtsbjbx = _('cbtsbjbx');
	  var cbttheorybx = _('cbttheorybx');
	  var cbtobjbx = _('cbtobjbx');
			if(st == 0){ //objective
				[cbttheorybx,cbtsbjbx].Hide();
				cbtobjbx.Show();
			}else if(st < 0){ //subjective
				[cbttheorybx,cbtobjbx].Hide();
				cbtsbjbx.Show();
			}else{//thery
				[cbtsbjbx,cbtobjbx].Hide();
				cbttheorybx.Show();
			}
		}, */
		ClearOption: (d) => {
			var cbx = _('op' + d + '_check');
			if (cbx.Checked) check.UnCheck(cbx);
			var anscont = _('op' + d + '_ansCont');
			var label = _('op' + d + '_label');
			label.innerHTML = "Option " + d;
			anscont.innerHTML = "";
		},
		//Clear all options
		ClearOptions: () => {
			for (var d = 1; d <= 6; d++) {
				//get the Option Check box
				Cbt.Manage.ClearOption(d);
			}
		},
		ClearBoard: () => {
			_('cbtquetion_editor-body').innerHTML = "";
			_('qnum').textContent = 0;
			_('qtot').textContent = 0;
			//var curQID = _('curQID');
			curQID.value = 0;
			curQID.Data('value', 0);
			_('qmark').SetText('1');
			Cbt.Manage.ClearOptions();
			_('qanstheory').innerHTML = "";
			_('qansubj').innerHTML = "";
			_('questrpagrp_title').innerHTML = Icon("check-square-o") + " Questions";
		},
		//Load Question
		LoadQuestion: async (selectedexam, NewQ, isnew, deleteID) => {
			NewQ = NewQ || 0;
			isnew = isnew || false;
			deleteID = deleteID || 0;
			(new Promise((resolve, reject) => {
				var stid = typeof selectedexam == "number" ? selectedexam : selectedexam.Data("id");
				//load all exam questions
				Cbt.Manage.Ajax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadquestions.php",
					Data: { SubDir: encodeURIComponent(configdata['SubDir']), ExmID: stid, QNum: NewQ, IsNew: isnew ? "true" : "false", DeleteQID: deleteID },
					OnProgress: function (delta) {
						//alert(Tabs.Tab("Cbt").ProgressGet(0));
						Tabs.Tab("Cbt").ProgressGet(0).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {

						if (res.Trim().substr(0, 1) == "#") {
							reject(res); return;
						}
						//alert(res);
						try {
							var cdet = JSON.parse(res);

							_('cbtquetion_editor-body').innerHTML = cdet.QBody;
							_('qnum').textContent = cdet.Num;
							_('qtot').textContent = cdet.Total;
							_('cExamID').value = cdet.ExamID;
							var curQID = _('curQID');
							curQID.value = cdet.ID;
							curQID.Data('value', cdet.ID);
							_('qmark').SetText(cdet.Mark);
							var anstype = cdet.QAnswerType;
							//reset all objective box


							//objective
							if (anstype == "OBJECTIVE") {
								//get the option det
								var options = JSON.parse(cdet.QAnswerBody);
								// if(options.length > 0){
								for (var d = 1; d <= 6; d++) {
									if (typeof options[d - 1] != "undefined") {
										var cbx = _('op' + d + '_check');
										if (options[d - 1].IsCorrect) {
											check.Check(cbx);
										} else {
											check.UnCheck(cbx);
										}
										//set the label
										var label = _('op' + d + '_label');
										label.innerHTML = options[d - 1].Label;
										var anscont = _('op' + d + '_ansCont');
										anscont.innerHTML = options[d - 1].Body;
									} else {
										Cbt.Manage.ClearOption(d);
									}
								}
								Editor.BringToFront(_('optionansbx'), _('optionansbx_btn'), Cbt.Manage.EnableAnswerBtn);
								// }
							} else {
								Cbt.Manage.ClearOptions();
								if (anstype == "THEORY") {
									_('qansubj').innerHTML = "";
									_('qanstheory').innerHTML = cdet.QAnswerBody;
									Editor.BringToFront(_('theoryansbx'), _('theoryansbx_btn'), Cbt.Manage.EnableAnswerBtn);
								} else if (anstype == "SUBJECTIVE") {
									_('qanstheory').innerHTML = ""
									_('qansubj').innerHTML = cdet.QAnswerBody;
									Editor.BringToFront(_('subjectiveansbx'), _('subjectiveansbx_btn'), Cbt.Manage.EnableAnswerBtn);
								} else if (anstype == "VIDEO") {
									_('qanstheory').innerHTML = "";
									_('qansubj').innerHTML = "";
									Editor.BringToFront(_('videoansbx'), _('videoansbx_btn'), Cbt.Manage.EnableAnswerBtn);
								} else {
									_('qanstheory').innerHTML = "";
									_('qansubj').innerHTML = "";
									Editor.BringToFront(_('audioansbx'), _('audioansbx_btn'), Cbt.Manage.EnableAnswerBtn);
								}
							}
							if (cdet.Message != "") MessageBox.Show(cdet.Message);
							_('questrpagrp_title').innerHTML = Icon("check-square-o") + " " + cdet.ExamName + " (" + cdet.ExamAbbr + ")";
							_('questrpagrp').Show();
							//console.log(cdet.ID);
							if (cdet.ID == 0) { //if no question found

								//hide the question panels and display the n o question panel
								_('questionbx').Hide();
								_('noexambox').Hide();
								_('exmnamdis').innerHTML = `${cdet.ExamName} (${cdet.ExamAbbr})`;
								_('noquestionbox').style.display = "flex";
							} else {
								_('questionbx').Show();
								_('noexambox').Hide();
								_('exmnamdis').innerHTML = ``;
								_('noquestionbox').style.display = "none";
							}
						} catch (err) {
							reject("Invalid Question: " + err);
							//MessageBox.Show("Invalid Question: "+err)
						}
						Tabs.Tab("Cbt").ProgressGet(0).ProgressTo(100);
						Tabs.HideSideBar("Cbt", 0);
					},
					OnError: function (res) {
						reject(res);
						//MessageBox.Show(res)
					},
					OnAbort: function (res) {
						reject("Operation Aborted");
						//MessageBox.Show("Operation Aborted");
					}
				})
			})).then(res => {
				MessageBox("*Question Loaded");
				Tabs.Tab("Cbt").ProgressGet(0).ProgressTo(100);
			}).catch(err => {
				Cbt.Manage.ClearBoard();
				MessageBox.Show(err);
				Tabs.Tab("Cbt").ProgressGet(0).ProgressTo(100);
			})

		},

		EnableAnswerBtn: btns => {
			var ansbtns = ["ansaddtext", "ansaddimage", "ansaddaudio", "ansaddvideo"];
			ansbtns.forEach(btn => {
				if (btns.id == "optionansbx_btn" || (btns.id == "subjectiveansbx_btn" && btn == "ansaddtext")) {
					_(btn).disabled = false;
				} else {
					_(btn).disabled = true;
				}
			});
		},
		ExamSearchBox: null,
		SelectedExamID: () => {
			var ExmID = parseInt(_('cExamID').value);
			if (isNaN(ExmID) || ExmID < 1) {
				if (Cbt.Manage.ExamSearchBox == null) Cbt.Manage.ExamSearchBox = _('examsearch');
				ExmID = Cbt.Manage.ExamSearchBox == null ? 0 : Cbt.Manage.ExamSearchBox.SelectedDataID().ToNumber();
				if (ExmID == 0) {
					MessageBox.Show("#No Exam/Test Selected");
					return false;
				}
			}
			return ExmID;
		},
		DeleteQuestion: () => {
			ExmID = Cbt.Manage.SelectedExamID();
			if (ExmID === false) return;
			OptionBox.Show({
				Title: "Delete Question",
				Logo: "trash",
				Options: [{
					Logo: "trash",
					Title: "Delete Question",
					Info: "Delete current loaded Question",
					Function: function () {
						var QID = _('curQID').value.ToNumber();
						if (QID < 1) {
							MessageBox.Show("#No Question Loaded");
						}
						var cur = _('qnum').textContent.ToNumber();
						var lst = _('qtot').textContent.ToNumber();
						var nxt = 1;
						if (lst > 1 && cur > 1) {
							nxt = cur - 1;
						}
						Cbt.Manage.LoadQuestion(ExmID, nxt, false, QID);
					}
				}
				]
			});
		},
		First: () => {
			//var cur = _('qnum').textContent.ToNumber();
			Cbt.Manage.LoadQuestionByNum(1);
		},
		Prev: () => {
			var cur = _('qnum').textContent.ToNumber();
			Cbt.Manage.LoadQuestionByNum(cur - 1);
		},
		Next: () => {
			var cur = _('qnum').textContent.ToNumber();
			Cbt.Manage.LoadQuestionByNum(cur + 1)
		},
		Last: () => {
			var lst = _('qtot').textContent.ToNumber();
			Cbt.Manage.LoadQuestionByNum(lst);
		},
		SearchQuestions: () => {
			ExmID = Cbt.Manage.SelectedExamID();
			if (ExmID === false) return;
			OptionBox.Show({
				Title: "Search Question",
				TitleHTML: OptionBox.TextBox({ id: 'questionnum', logo: 'search', title: 'Question Number', type: 'number' }),
				Logo: "search",
				Options: [{
					Logo: "search",
					Title: "Search",
					Info: "Search Question",
					Function: function () {
						Cbt.Manage.LoadQuestionByNum(_('questionnum').TextContent());
					}
				}
				]
			});
		},
		QuestionMap: () => {
			ExmID = Cbt.Manage.SelectedExamID();
			if (ExmID === false || ExmID === 0) return;
			// console.log(ExmID);
			var cur = _('qtot').textContent.ToNumber();
			// console.log(cur);
			if (cur < 2) return;
			var bmk = '<div style="display:flex;max-width:350px;flex-wrap: wrap;">';
			for (var d = 1; d <= cur; d++) {
				bmk += `<button class="bbtn altColor2 card-1" onclick="Cbt.Manage.LoadQuestion(${ExmID},${d},false);return false;" title="Question ${d}" style="border-radius:3px;padding:5px 8px;margin:5px;background-color:#fff;border:none">${d}</button>`;
			}
			bmk += '</div>';
			OptionBox.Show({
				Title: "Question Map",
				TitleHTML: bmk,
				Logo: "th",
				Options: [
				]
			});
		},
		LoadQuestionByNum: (num) => {
			ExmID = Cbt.Manage.SelectedExamID();
			if (ExmID === false) return;
			curtot = _('qtot').textContent.ToNumber()
			if (num < 1 || num > curtot) {
				return;
			}
			//alert('aa');
			//get the current total
			//curtot = _('qtot').textContent.ToNumber()+1;
			//console.log(sb);
			Cbt.Manage.LoadQuestion(ExmID, num, false)
		},
		//Add New Question
		NewQuestion: async () => {
			//get the selected exam/Text

			ExmID = Cbt.Manage.SelectedExamID();
			if (ExmID === false) return;


			// alert('aa');
			//get the current total
			curtot = _('qtot').textContent.ToNumber() + 1;
			//console.log(sb);
			Cbt.Manage.LoadQuestion(ExmID, curtot, true)

		},
		VerifyLoaded: () => {
			var QID = _('curQID').value.ToNumber();
			if (QID < 1) {
				MessageBox.Show("#No Question Loaded");

			}
			return QID;
		},
		//Add Predefined Method
		Save: function () {
			Cbt.Manage.PerformSave().then(res => { MessageBox.Show(res) }).catch(err => { MessageBox.Show(err) });
			//alert('Save Mange')
			//Save code
		},
		PerformSave: () => {
			return new Promise((resolve, reject) => {
				//get question details
				var QID = _('curQID').value.ToNumber();
				if (QID < 1) {
					MessageBox.Show("#No Question Loaded");

				}
				var Mark = _('qmark').TextContent();
				//get the body markup
				var QBody = _('cbtquetion_editor-body').innerHTML;

				//get the display answer type
				var OptionContDis = _('ansmainbx').firstElementChild;
				var optiondistag = "";
				var optiondiscont = "";
				if (OptionContDis.id == "optionansbx") {
					optiondistag = "OBJECTIVE";
					var objarr = [];
					for (var d = 1; d <= 6; d++) {
						var cbx = _('op' + d + '_check');
						var checkst = cbx.Checked();
						var label = _('op' + d + '_label');
						var labelrst = label.innerHTML;

						var anscont = _('op' + d + '_ansCont');
						var opcont = anscont.innerHTML;
						if (labelrst.Trim() == "" && opcont.Trim() == "") continue;
						//alert(checkst);
						objarr.push({ Label: labelrst, Body: opcont, IsCorrect: checkst });

					}

					optiondiscon = JSON.stringify(objarr);
					//alert(optiondiscon);

				} else if (OptionContDis.id == "subjectiveansbx") {
					optiondistag = "SUBJECTIVE";
					optiondiscon = _('qansubj').innerHTML;
				} else if (OptionContDis.id == "theoryansbx") {
					optiondistag = "THEORY";
					optiondiscon = _('qanstheory').innerHTML;
				} else if (OptionContDis.id == "videoansbx") {
					optiondistag = "VIDEO";
				} else if (OptionContDis.id == "audioansbx") {
					optiondistag = "AUDIO";
				} else {
					reject("INVALID OPTION TYPE SELECTED");
					return;
				}
				Cbt.Manage.Ajax.Post(
					{
						Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/manage.php",
						Data: { SubDir: encodeURIComponent(configdata['SubDir']), QID: QID, Mark: Mark, QBody: QBody, QAnswerType: optiondistag, QAnswerBody: optiondiscon },
						OnProgress: function (delta) {
							Tabs.Tab("Cbt").ProgressGet(0).ProgressTo(Math.floor(delta * 100));
						},
						OnComplete: function (res) {
							if (res.Trim().substr(0, 1) == "#") {
								reject(res);
								return;
							}
							//alert(res);
							resolve(res)
						},
						OnError: function (res) {
							reject(res);
						},
						OnAbort: function (res) {
							reject("Aborted");
						}
					}
				);
			});
		},
		Clear: function () {
			_('sfdgdhdj').SwitchOn();
			_('sfdgdhdj').Disable();
		},
		Print: function () {
			OptionBox.Show({
				Title: "Print All",
				Options: [{
					Logo: "print",
					Title: "Print",
					Info: "Print Me",
					Function: function () {
						alert('Print')
						//MessageBox.Show('All');
					}

					// Parameter:selUserID
				},
				{
					Logo: "times",
					Title: "Cancel",
					Info: "Abort the Print Operation",
					Function: function () {
						MessageBox.Show("Cancel");
					}
					//Parameter:selectedRegNo
				}]

			});
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	},

	CbtSchedule: {
		Ajax: new Ajax(),
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		CheckItem: function (obj, selectval) {
			var cid = obj.id;
			var idarr = cid.split("_");
			var cellID = idarr[3];

			if (cellID == "cbtcandop") { //if Payment item cell, check if more condition is selected

				//diabbled no required cells
				var reqcell = ["cbtcandLevel", "cbtcandCond", "cbtcandCondOp", "cbtcandVal", "cbtcandStatus"];
				//alert(reqcell.length);
				for (var r = 0; r < reqcell.length; r++) {
					reqcellid = reqcell[r];
					//console.log(reqcellid);
					idarr[3] = reqcellid;
					var reqcellobj = _(idarr.join("_"));
					//alert(_('paytypeanal_rw_2_FPay'));//paytypeanal_rw_2_Fpay
					if (reqcellobj != null) {
						var swobj = reqcellobj.firstElementChild;
						if (selectval.ToNumber() == 3 || selectval.ToNumber() == 4) { //if more condition is selected
							reqcellobj.classList.add("head");
							if (reqcellid != "cbtcandStatus") {
								swobj.contentEditable = false;
							} else {
								rswitch = swobj.firstElementChild.firstElementChild;
								//console.log(rswitch);
								rswitch.SwitchOn();
								rswitch.Disable();
							}

						} else {
							if (!reqcellobj.classList.contains("head")) break;
							reqcellobj.classList.remove("head");
							if (reqcellid != "cbtcandStatus") {
								swobj.contentEditable = true;
							} else {
								rswitch = swobj.firstElementChild.firstElementChild;
								rswitch.SwitchOff();
								rswitch.Enable();
							}
						}

					}
				}

			}
		},

		LoadCand: function () {
			Cbt.CbtSchedule.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadcand.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {

				},
				OnComplete: function (res, url, param) {
					if (!Login.Authenticate(res)) return;
					//	if(res == "#"){MessageBox.Show("#Internal Error: Payment Type Not Found");return;}

					OptionBox.Show({
						Title: "Selected Candidates",
						TitleHTML: res,
						Options: [{
							Logo: "print",
							Title: "Print List",
							Info: "Print Schedule Exam Candidate List",
							Function: function (cellid) {
								//var reqired = _("textBx & ExamParamGrp & req err");
								/* if (reqired != null) { MessageBox.Show("Invalid Entering: All Fields are Required"); return }
									//get all data
									var data = Page.DataString("ExamParamGrp");
									//console.log(data);
									CBT.Manage.AddExamReal(data); */
							}
							, Parameter: 1
						}/* ,
						{
							Logo: "times",
							Title: "Cancel",
							Info: "Cancel Add Payment Type Operation",
							Function: function () {
								MessageBox.Show("Simulation Canceled");
							}
							,Parameter:selectedRegNo
						} */]

					});
				}
			});
		},
		AssignExm: () => {

		},
		AssignExam: (obj) => {

			//obj.StartLoading();

			(new Promise((resolve, reject) => {
				//return;
				Cbt.CbtSchedule.Ajax.Post({
					PostData: "CORE=" + encodeURIComponent(configdata['Core']),
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/searchschedule.php",
					OnProgress: function (delta) { },
					OnComplete: (res) => {

						resolve(res);
					}
				});
			})).then((res) => {

				//create the search box object
				obj_examsearch2 = new SSB('examsearch2');
				OptionBox.Show({
					Title: "Assign Exam/Text",
					TitleHTML: res,
					Options: [{
						Logo: "edit",
						Title: "Assign",
						Info: "Assign Selected Exam/Text to Schedule",
						Function: function () {
							//get the exam detaisl and input as required
							var seracbx = _('examsearch2');
							if (seracbx == null) { return; obj.StopLoading(); }
							var serxctb = seracbx.SelectedDataID().ToNumber();
							if (!isNaN(serxctb) && serxctb > 0) {
								//Load the exam details
								Cbt.CbtSchedule.Ajax.Post({
									PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&EID=" + serxctb,
									Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/schexamdetails.php",
									OnProgress: function (delta) { },
									OnComplete: (exmmk) => {
										_('schexmdetbx').innerHTML = exmmk;
										//obj.StopLoading();
									}
								});
							} else {
								MessageBox.Show("No Exam/Text Selected");
								//obj.StopLoading();
							}
						}
					}]

				});
			})

		},
		TotalAllocatedQ: cell => {
			setTimeout(() => {
				if (cell.Data('column') == '2') {
					//console.log(cell);
					var availq = _('loadtotquestion').value.ToNumber();
					if (availq < 1) { cell.innerHTML = 0; cell.Data('value', '0'); return }
					var numal = cell.Data('value').ToNumber();
					if (numal < 0) numal = 0;
					cell.Data('value', numal);
					cell.innerHTML = numal;
					var total = 0;
					var indtotstr = _('indtotquestion').textContent;
					var indtot = JSON.parse(indtotstr);
					//console.log(indtot);
					//calculate all
					var col = _('indallcell');
					for (var c = 0, clen = col.length; c < clen; c++) {
						var celidarr = col[c].id.split("_");
						celidarr[3] = 'CBTQType';
						var selectedqtype = _(celidarr.join("_")).textContent.Trim();
						var maxq = 0;
						if (selectedqtype != "") {
							//console.log(selectedqtype);
							maxq = indtot[selectedqtype].ToNumber();
						}
						var curval = col[c].ToNumber();

						if (curval > maxq) { col[c].innerHTML = maxq; col[c].Data('value', maxq); curval = maxq }
						total += curval;
					}
					if (total > availq) {
						total -= numal;
						cell.innerHTML = 0;
						cell.Data('value', '0');
					}
					_('cbtschtotquest').SetText(total);
				}

			}, 1)
		},

		//Load Candidate
		AddCandidate: () => {
			OptionBox.Show({
				Title: "Add Candidate",
				TitleHTML: "Select Candidate Source",
				Options: [
					{
						Logo: "users",
						Title: "Class List",
						Info: "Load Candidate from a Class",
						Function: function () {
							Cbt.CbtSchedule.AddCandidateFromClass();
						}
					},
					{
						Logo: "user",
						Title: "Individual Student",
						Info: "Search and Add a Particular Student",
						Function: function () {

						}
					},
					{
						Logo: "user-secret",
						Title: "Anonymous",
						Info: "Add an anonymous Candidate",
						Function: function () {

						}
					}
				]

			});
		},

		AddCandidateFromClass: () => {
			OptionBox.Show({
				Title: "Add New Exam",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Utility/loadfields.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
				Options: [{
					Logo: "plus",
					Title: "Add Class",
					Info: "Add all student in Selected Class",
					Function: function () {
						//get the classid and mode of enterng
						var ClassID = _('mpreloadclass').ValueContent();
						var MOE = _('mpreloadmoe').ValueContent();
						var StudyID = _('mpreloadstudy').ValueContent();
						var ProgID = _('mpreloadprog').ValueContent();
						var StartSes = _('mpreloadstartses').ValueContent();
						if (ClassID == "") {
							MessageBox.Show("#Invalid Class Selected"); return;
						}
						CardList.Loading('schcandidate');
						Cbt.CbtSchedule.Ajax.Post({
							Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/addcand.php",
							PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&ClassID=" + ClassID + "&MOE=" + MOE + "&StudyID=" + StudyID + "&ProgID=" + ProgID + "&StartSes=" + StartSes + "&Data=" + encodeURIComponent(CardList.Data('schcandidate')),
							OnProgress: function (delta) {

							},
							OnComplete: function (res, url, param) {
								if (!Login.Authenticate(res)) return;
								if (res.substr(0, 1) == "#") { //if error message sent
									MessageBox.Show(res); return;
								}
								_('candidatesbx').innerHTML = res;
							},
							OnError: (res) => {

							}
						});
					}
				}]

			});
		},
		SearchBox: null,
		SelectedScheduleID: () => {
			var SchID = parseInt(_('ScheduleID').value);
			if (isNaN(SchID) || SchID < 1) {
				if (Cbt.CbtSchedule.SearchBox == null) Cbt.CbtSchedule.SearchBox = _('cbtschedulesearch');
				SchID = Cbt.CbtSchedule.SearchBox == null ? 0 : Cbt.CbtSchedule.SearchBox.SelectedDataID().ToNumber();
				/*  if(SchID == 0){
					 MessageBox.Show("#No Schedule Selected");
				 return false;
				 } */
			}
			return SchID;
		},
		SetScheduleID: id => {
			_('ScheduleID').value = id;

		},

		//Add Predefined Method
		Save: function () {
			_('cbtschfrm').submit()
			//Save code
		},
		PSave: () => {
			//alert('saving');
			//Validate Schedule Code and Name
			if (_('newschcode').TextContent().trim() == "" || _('newschname').TextContent().trim() == "") {
				MessageBox.Show("Schedule Code and Name are Compulsary"); return;
			}
			//Validate Assigned Exam
			var loadexamid = parseInt(_('loadexmid').value);
			if (isNaN(loadexamid) || loadexamid < 1) {
				MessageBox.Show("No Exam Assigned"); return;
			}

			//Validate Exam duration Set
			if ((_('cbtschtimehr').TextContent().ToNumber() + _('cbtschtimemin').TextContent().ToNumber() + _('cbtschtimesec').TextContent().ToNumber()) == 0) {
				MessageBox.Show("Invalid Duration Set"); return;
			}



			var allocstr = _('sprcbttype').GetDataString().ToDataArray();
			var allocabj = [];
			var totaloc = 0;
			for (var fd = 1; fd <= 5; fd++) {
				var setAlloc = (typeof allocstr[fd + "_2"] != "undefined" ? parseInt(allocstr[fd + "_2"]) : 0);
				if (isNaN(setAlloc) || setAlloc == null) setAlloc = 0;
				totaloc += setAlloc;
				allocabj.push(setAlloc);
			}

			//validate allocation
			if (totaloc < 1) {
				MessageBox.Show("No Question allocated for this schedule"); return;
			}

			var textstr = Page.DataString("CbtScheduleelem");

			//get the candidate
			var candstr = CardList.Data('schcandidate').trim();
			if (candstr == "" || candstr == "[]" || candstr == "{}") {
				MessageBox.Show('No Candidate Added'); return;
			}

			//select schedule
			var SelSchID = Cbt.CbtSchedule.SelectedScheduleID();

			var userdet = Login.User();
			if (userdet == null) { MessageBox.Show('User Identification Failed'); return; }
			var userID = userdet[0];

			//console.log(allocstr);
			textstr += "&asignExmID=" + loadexamid + "&aloc=" + encodeURIComponent(JSON.stringify(allocabj)) + "&canddatestr=" + encodeURIComponent(candstr) + "&SchID=" + SelSchID + "&UID=" + userID;
			//console.log(textstr);return;
			Cbt.CbtSchedule.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/saveschedule.php",
				PostData: textstr + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {
					// alert('sdd');
					Tabs.Tab("Cbt").ProgressGet(1).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res, url, param) {

					if (!Login.Authenticate(res)) return;
					if (res.substr(0, 1) == "#") { //if error message sent
						MessageBox.Show(res);
					} else {
						resnum = parseInt(res);
						if (isNaN(resnum)) {
							MessageBox.Show("#Unknown Error - " + res);
						} else {
							Cbt.CbtSchedule.SetScheduleID(res);
							MessageBox.Show("*Schedule Saved");
						}
					}


					Tabs.Tab("Cbt").ProgressGet(1).ProgressTo(100);
				},
				OnError: (res) => {

				}
			});

			//console.log(textstr);
		},
		LoadSchedule: id => {
			id = id || 0;
			var id = typeof id == "number" ? id : id.Data("id");
			//console.log(id);
			Cbt.CbtSchedule.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadschedule.php",
				PostData: "SubDir=" + encodeURIComponent(configdata['SubDir']) + "&SchID=" + id,
				OnProgress: function (delta) {
					//alert('ddd');
					Tabs.Tab("Cbt").ProgressGet(1).ProgressTo(Math.floor(delta * 95));
				},
				OnComplete: function (res, url, param) {

					if (!Login.Authenticate(res)) return;
					if (res.substr(0, 1) == "#") { //if error message sent
						MessageBox.Show(res);
					} else {
						_('cbtschedulebx').innerHTML = res;
					}


					Tabs.Tab("Cbt").ProgressGet(1).ProgressTo(100);
					Tabs.HideSideBar("Cbt", 1);
				},
				OnError: (res) => {

				}
			});
		},
		Clear: function () {
			//clear code
		},
		Print: function () {
			//print code
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	},
	Mark: {
		LoadMarkBases: function () {
			var sw = _('cbtschmarkbasis').GetStatus();
			console.log()
			Cbt.Manage.Ajax.Post({
				Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadmarklist.php",
				PostData: "type=" + sw + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
				OnProgress: function (delta) {

				},
				OnComplete: function (res, url, param) {
					_('cbtmarkbasisbx').innerHTML = res;

				}
			});
			//method code
		},
		LoadQuestions:async (selectCand)=>{
			(new Promise((resolve, reject) => {
				var stid = typeof selectCand == "number" ? selectCand : selectCand.Data("id");
				//load all exam questions
				Cbt.Manage.Ajax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadquestionRsts.php",
					Data: { SubDir: encodeURIComponent(configdata['SubDir']), RSTID: stid,type:1},
					OnProgress: function (delta) {
						//alert(Tabs.Tab("Cbt").ProgressGet(0));
						Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {

						if (res.Trim().substr(0, 1) == "#") {
							reject(res); return;
						}
						//alert(res);
						try {
							_('markrsyBx').innerHTML = res;
						} catch (err) {
							reject("Invalid Response: " + err);
							//MessageBox.Show("Invalid Question: "+err)
						}
						Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
						_('marrkcbthome').Hide();
			             _('markdet').Show();
			Tabs.HideSideBar('Cbt', 2);
					},
					OnError: function (res) {
						reject(res);
						//MessageBox.Show(res)
					},
					OnAbort: function (res) {
						reject("Operation Aborted");
						//MessageBox.Show("Operation Aborted");
					}
				})
			})).then(res => {
				// MessageBox("*Question Loaded");
				Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
			}).catch(err => {
				// Cbt.Manage.ClearBoard();
				MessageBox.Show(err);
				Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
			})
		},
		LoadStudent: async (selectedexam) => {
			(new Promise((resolve, reject) => {
				var stid = typeof selectedexam == "number" ? selectedexam : selectedexam.Data("id");
				//load all exam questions
				Cbt.Manage.Ajax.Post({
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/cbt/loadmarklist.php",
					Data: { SubDir: encodeURIComponent(configdata['SubDir']), SchID: stid,type:1},
					OnProgress: function (delta) {
						//alert(Tabs.Tab("Cbt").ProgressGet(0));
						Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {

						if (res.Trim().substr(0, 1) == "#") {
							reject(res); return;
						}
						//alert(res);
						try {
							_('cbtmarkbasisbx').innerHTML = res;
						} catch (err) {
							reject("Invalid Response: " + err);
							//MessageBox.Show("Invalid Question: "+err)
						}
						Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
						_('marrkcbthome').Hide();
			             _('markdet').Show();
			Tabs.HideSideBar('Cbt', 2);
					},
					OnError: function (res) {
						reject(res);
						//MessageBox.Show(res)
					},
					OnAbort: function (res) {
						reject("Operation Aborted");
						//MessageBox.Show("Operation Aborted");
					}
				})
			})).then(res => {
				// MessageBox("*Question Loaded");
				Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
			}).catch(err => {
				// Cbt.Manage.ClearBoard();
				MessageBox.Show(err);
				Tabs.Tab("Cbt").ProgressGet(2).ProgressTo(100);
			})
			
		}
	}

}


//*Entrance Module
/************************************************************************************************** */
var Entrance = {
	Screening: {
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		Ajax: new Ajax,
		Working: false,
		GenLoader: new GenLoading({ StudyID: "apprstudstudy", FacID: "apprstudfac", DeptID: "apprstuddept", ProgID: "apprstudprog", LevelID: "apprstudlvl", SemID: "appsemest" }),
		Objects: {},
		//Load Applicant
		LoadApplicant: function () {

			if (typeof Entrance.Screening.Objects['ApplCont'] == _UND) Entrance.Screening.Objects['ApplCont'] = _('applcontdiv');
			var Data = { SubDir: encodeURIComponent(configdata['SubDir']) };
			var filterbxsw = _('disfilterbox');
			if (filterbxsw.GetStatus() == 1) {
				var fields = [['StudyID', 'apprstudstudy'], ['FacID', 'apprstudfac'], ['DeptID', 'apprstuddept'], ['ProgID', 'apprstudprog'], ["Filter", 'loadfilter'], ["DisplayLimit", "displlimit"]];
			} else {
				var fields = [["Filter", 'loadfilter'], ["DisplayLimit", "displlimit"]];
			}

			for (var [objid, fieldid] of fields) {
				//Cache the elements - Issue after app reload - still holding the old vertion of the elements
				//Propose solution is to use a global cach system that will be cleard after an app reload
				if (typeof Entrance.Screening.Objects[objid] == _UND) Entrance.Screening.Objects[objid] = _(fieldid);
				var sesid = Entrance.Screening.Objects[objid].ValueContent().ToNumber();
				if (sesid < 1) { MessageBox.Show('#Wrong Selection, Kindly Select all Required Fields'); return; }
				Data[objid] = sesid;
			}



			/* var studyid = Entrance.Screening.Objects['StudyID'].ValueContent().ToNumber();
			if(studyid < 1){MessageBox.Show('#Select a Study');return;}
			var progid = Entrance.Screening.Objects['ProgID'].ValueContent().ToNumber();
			if(progid < 1){MessageBox.Show('#Select the Department/Programme');return;} *///applcontdiv
			Entrance.Screening.Objects['ApplCont'].innerHTML = Markups.GroupBoxPlaceholder("download ep-animate-fading", "Please Wait !!!! </br><small>While we Load Registered Applicants</small>");

			window.setTimeout(
				() => {
					Entrance.Screening.LoadApplicantReal(Data).then(res => {
						Entrance.Screening.Working = false;
						_('screeninghome').Hide();
						_('applrgrp').Show();
					}).catch(res => {
						Entrance.Screening.Objects['ApplCont'].innerHTML = Markups.GroupBoxPlaceholder("exclamation-triangle appcolor", "Loading Failed </br><small>" + res + "</small>"); Entrance.Screening.Working = false;
						_('screeninghome').Hide();
						_('applrgrp').Show();
					})
				}, 1
			)

		},
		LoadApplicantReal: function (Data) {

			return new Promise((resolve, reject) => {
				//if working abort and reload
				if (Entrance.Screening.Working) { Entrance.Screening.Ajax.Abort() }
				Entrance.Screening.Working = true;
				Tabs.HideSideBar("Entrance", 5);
				Entrance.Screening.Ajax.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Entrance/loadapplicant.php",
					Data: Data,
					OnProgress: delta => {
						//Entrance.Screening.Objects['LoadingPage'].ProgressTo(Math.floor(delta * 80));
					},
					OnComplete: res => {
						if (res.substr(0, 1) == "#") {
							reject(res.substr(1)); return;
						}
						// console.log(res);
						Entrance.Screening.Objects['ApplCont'].innerHTML = res;

						resolve('done');
					},
					OnError: err => {
						reject(err);
					},
					OnAbort: err => {
						resolve('');
					}
				})
			});
		},
		FilterBox: function (sw) {
			var st = sw.GetStatus();
			var filterbx = _('filterboxscr');
			if (st == 1) {
				filterbx.Show();
			} else {
				filterbx.Hide();
			}
		},
		SaveAjax: new Ajax,
		//Add Predefined Method
		Save: function () {//.GetDataString();

			var sprshett = _('sprstscreen');
			if (sprshett == null) { MessageBox.Show('#No Applicant Loaded'); return; }
			var Data = sprshett.GetDataString() + "&SubDir=" + encodeURIComponent(configdata['SubDir']);
			(new Promise((resolve, reject) => {
				Entrance.Screening.SaveAjax.Post({
					Action: configdata['Core'] + "cportal/Pages/Scripts/Entrance/saveapplicant.php",
					Data: Data,
					OnProgress: delta => {
						Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(Math.floor(delta * 60));
					},
					OnComplete: res => {
						if (!Login.Authenticate(res)) return;
						if (res.substr(0, 1) == "#") {
							reject(res.substr(1)); return;
						}
						//console.log(res);
						resolve(res);
						//resolve(res+ "Apllicants Admission Status Updated Successfully");
					},
					OnError: res => {
						reject(res)
					},
					OnAbort: res => {
						reject("Admission Status Update Aborted");
					}
				});
			})).then(res => { MessageBox.Show("*" + res); Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(100) }).catch(err => { MessageBox.Show("#" + err); Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(0) })

		},
		ViewApplicant: regno => {

			PDFPrinter.Print(configdata.Core + "general/Slip.php", "folder=Candidate&regno=" + escape(regno) + "&paper=A4&orientation=P&MT=4&MB=30" + "&SubDir=" + encodeURIComponent(configdata.SubDir), "Applicant_" + regno.Replace("/", "_") + ".pdf");
		},
		ManageApplicant: (RegNo, id) => {
			OptionBox.Show({
				Logo: "cogs",
				Title: "Manage Applicant (" + RegNo + ")",
				Options: [{
					Logo: " mbri-left-right",
					Title: "Update",
					Info: "Update Applicant Academic Details",
					Function: function (StudID) {
						Entrance.Screening.Migrate(StudID);
					},
					Parameter: id
				},
				{
					Logo: "print",
					Title: "View/Print",
					Info: "Preview an print students academic details",
					Function: function (RegNo) {
						//set to globally update reg no setting 1
						Entrance.Screening.ViewApplicant(RegNo);
					},
					Parameter: RegNo
				},
				{
					Logo: "times",
					Title: "Cancel Process",
					Info: "Cancel the current Process",
					Function: function () {

					}
				}]

			});
		},
		Migrate: StudID => {
			OptionBox.Show({
				Title: "Manage applicant Details",
				TitleHTML: { Action: configdata['Core'] + "cportal/Pages/Scripts/Entrance/loadfields.php", Data: "SubDir=" + encodeURIComponent(configdata['SubDir']) },
				Options: [{
					Logo: "share-square",
					Title: "Update Applicant",
					Info: "Update Applicant Details to the Selected",
					Function: function (StudID) {
						Entrance.Screening.PerformMigrate(StudID);
					},
					Parameter: StudID
				},

				{
					Logo: "times",
					Title: "Cancel Process",
					Info: "Cancel the current Process",
					Function: function () {
						MessageBox.Show("Process Canceled");
					}
				}]

			});
		},
		GenLoaderMigrate: new GenLoading({ StudyID: "scrpreloadstudy", FacID: "scrpreloadfac", DeptID: "scrpreloaddept", ProgID: "scrpreloadprog", LevelID: "scrpreloadlvl", SemID: "scrpreloadsemest", ClassID: "scrpreloadclass", DisplayLevelID: "scrDisplayLvl", StartSesID: "scrpreloadstartses" }),
		MigrateAjax: new Ajax(),
		PerformMigrate: StudID => {
			/* var biodataPreload = _('biodataPreload');
			if(biodataPreload == null || Student.PreLoad.CurLoaded.length == 0){
				MessageBox.Show("List not loaded");
				return;
			}
			var datas = Student.PreLoad.CurLoaded[0]; */
			//get the migratte details
			//{ StudyID: "mpreloadstudy", FacID: "mpreloadfac", DeptID: "mpreloaddept", ProgID: "mpreloadprog", LevelID: "mpreloadlvl", SemID: "mpreloadsemest", ClassID:"mpreloadclass",DisplayLevelID:"mDisplayLvl", StartSesID:"mpreloadstartses" }
			var scrpreloadstudy = _('scrpreloadstudy').ValueContent();
			var scrpreloadprog = _('scrpreloadprog').ValueContent();
			var scrpreloadclass = _('scrpreloadclass').ValueContent();
			var scrpreloadstartses = _('scrpreloadstartses').ValueContent();
			if (scrpreloadstudy == "" || scrpreloadprog == "" || scrpreloadstartses == "") {
				MessageBox.Show("Invalid Migration Class Selected"); return;
			}
			datas = "scrpreloadstudy=" + scrpreloadstudy + "&scrpreloadprog=" + scrpreloadprog + "&scrpreloadclass=" + scrpreloadclass + "&scrpreloadstartses=" + scrpreloadstartses;
			if (StudID < 1) {
				MessageBox.Show("No Applicant Selected");
				return;
			} else {
				pdata = datas + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&StudID=" + StudID;
			}

			// alert(pdata);
			//return;
			//MessageBox.Show("Module not Available");
			Entrance.Screening.MigrateAjax.Post(
				{
					Action: configdata['Core'] + "cportal/" + "Pages/Scripts/Entrance/migratepreload.php",
					PostData: pdata,
					OnProgress: function (delta) {
						Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(Math.floor(delta * 90));
					},
					OnComplete: function (res) {
						//if(!Login.Authenticate(res))return;
						//"Loaded".__();
						//_('preloadsheetbox').innerHTML = res;
						Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(100);

						rtn = JSON.parse(res);
						//console.log(rtn.Errors);

						if (rtn.Success == true) {//if loaded successfully
							//reload the lis
							Entrance.Screening.LoadApplicant();

						}
						MessageBox.Show(rtn.Message)
						// MessageBox.Show(res);
						//"Populated".__();

					},
					OnAbort: function (res) {

						Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("Operation Aborted");');

					},
					OnError: function (res) {
						//MessageBox.Show("" + res);
						Tabs.Tab("Entrance").ProgressGet(5).ProgressTo(-1, 'MessageBox.Show("#INTERNAL ERROR: ' + res.Replace('"', '\"') + '");');
					}
				}
			);
		}
		,
		Clear: function () {
			//clear code
		},
		Print: function () {
			//print code
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	},
	MonitorReg: {
		SearchAjax: new Ajax(),
		SearchDelayTimer: null,
		Search: function () {
			//alert(obj);
			if (Entrance.MonitorReg.SearchDelayTimer != null) {
				clearTimeout(Entrance.MonitorReg.SearchDelayTimer);
				Entrance.MonitorReg.SearchDelayTimer = null;
				Entrance.MonitorReg.SearchAjax.abort();
			}
			Entrance.MonitorReg.SearchDelayTimer = setTimeout(function () {
				var rstemonregbx = _('rstemonregbx');
				rstemonregbx.FadeOut(300);
				var emonregstsloadin = _('emonregstsloadin');
				emonregstsloadin.Animate({ CSSRule: "opacity:1;visibility:visible", Time: 300 });
				var UID = Login.User();
				UID = UID[0]
				var limit = _('emonregmaxrec').RangeValue();
				var val = _("emonregsearch").TextContent();
				var filter = _("nonregfilter").TextContent();
				Entrance.MonitorReg.SearchAjax.Post(
					{
						Action: configdata['Core'] + "cportal/Pages/Scripts/Entrance/loadapplicantmonitor.php",
						PostData: "UID=" + UID + "&limit=" + limit + "&val=" + escape(val) + "&filter=" + filter + "&SubDir=" + encodeURIComponent(configdata['SubDir']),
						OnComplete: function (res) {
							// if(!Login.Authenticate(res))return;

							rstemonregbx.innerHTML = res;
							rstemonregbx.FadeIn(300);
							emonregstsloadin.Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 300 });
							Entrance.MonitorReg.SearchDelayTimer = null;
							// alert(res);
						},
						OnError: function (res) {
							MessageBox.Show("#Internal Error: " + res);
							Entrance.MonitorReg.SearchDelayTimer = null;
						}
					}
				)
			}, 300);
		}
	}

}

// ******************************************************************
// Utility Application (Module)
//********************************************************* */
var Utilities = {
	PinMgt: {
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		//Add custom methods
		Method1: function () {
			//method code
		},
		Method2: function () {
			//method code
		},

		//Add Predefined Method
		Save: function () {
			//Save code
		},
		Clear: function () {
			//clear code
		},
		Print: function () {
			//print code
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	}

}

/* **************************************************************** */
//Keyboard Manager
/****************************************************************** */
var KeyManager = {
	Init: () => {
		document.addEventListener('keydown', KeyManager.Perform);
	},
	Perform: e => {
		var keystr = "";
		if (e.ctrlKey || e.metaKey) {
			keystr += "ctr_";
			/* switch (String.fromCharCode(event.which).toLowerCase()) {
			case 's':
				event.preventDefault();
				alert('ctrl-s');
				break;
			case 'f':
				event.preventDefault();
				alert('ctrl-f');
				break;
			case 'g':
				event.preventDefault();
				alert('ctrl-g');
				break;
			} */
		}
		keystr += String.fromCharCode(e.keyCode).toLowerCase();
		if (typeof KeyManager.KeyMap[keystr] != 'undefined') {
			KeyManager.KeyMap[keystr](e);
			return false;
		}
	},
	KeyMap: {
		'ctr_s': param => {
			if (KeyManager.RunToolbox('Save')) { param.preventDefault(); }
		},
		'ctr_p': param => {
			if (KeyManager.RunToolbox('Print')) { param.preventDefault(); }

		}
	},
	RunToolbox: type => {
		//get the current display module
		var activepage = document.querySelector('.pgmain.display');

		if (activepage != null) {
			//get the page id

			var fenderbar = activepage.querySelector('.toolboxL');
			if (fenderbar != null) {
				fenderbar.classList.remove('toolboxOpen');
				/* this.parentElement.classList.remove('toolboxOpen');Tabs.Toolbox.Perform('Course','Save') */
			}
			Tabs.Toolbox.Perform(activepage.id, type);
			return true;
			//alert(activepage.id);
		}
		return false;
	}
}


KeyManager.Init();

/************************************************************************************************** */
//*Template
/************************************************************************************************** */
var TempPage = {
	TempTab: {
		//loading progress bar methos
		/*if(Tabs.Tab("PageName").ProgressGet(4).ProgressState() == 0){
		Tabs.Tab("PageName").ProgressGet(tabindex).ProgressTo(progress end);
		  }*/

		//cover page loading
		/* CoverScreen.Show("new coverscreen id","Display Title ...",function(obj){
			   //code in here
			CoverScreen.Close(_('new coverscreen id'));
			}); */
		//Add custom methods
		Method1: function () {
			//method code
		},
		Method2: function () {
			//method code
		},

		//Add Predefined Method
		Save: function () {
			//Save code
		},
		Clear: function () {
			//clear code
		},
		Print: function () {
			//print code
		},
		Copy: function () {
			//Copy code
		},
		Paste: function () {
			//Paste code
		},
		Export: function () {
			//export code
		},
		Import: function () {
			//import code
		},
		Delete: function () {
			//delete code
		}
	}

}

