// Element Javascript

//Loading 
var CoverScreen = {
	Create: function (id) {
		var objdiv = document.createElement("div");
		objdiv.className = "coverpopup";
		objdiv.id = id;
		objdiv.SetStyle("opacity:0");
		return objdiv;
	},
	Show: function (id, text, func) {
		var objn = CoverScreen.Create(id);
		document.body.appendChild(objn);
		objn.Animate({ CSSRule: "opacity:1", Time: 500, DoAt: 1, EndAction: func });
		objn.innerHTML = '<div class="inner "> ' + text + ' </div>';
	},
	Close: function (objdiv, cancelfunc) {
		//alert(objdiv.id)
		if (objdiv != null && typeof objdiv == "object") {
			var inner = objdiv.getElementsByClassName('lbox');

			if (inner.length > 0) {
				//alert(inner[0].className);
				inner[0].className = inner[0].className.replace("zoomInShort2", "zoomOutShort2");
				//alert(inner[0].className);
			}
			objdiv.Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 600, DoAt: 1, EndAction: "var cobj = _('" + objdiv.id + "'); if(cobj != null && typeof cobj == 'object')document.body.removeChild(cobj)" });
		}



		if (typeof cancelfunc == 'function') {
			//cancelfunc();
			setTimeout(cancelfunc, 1);
		} else if (typeof cancelfunc == 'string') {
			//eval(cancelfunc);
			setTimeout(cancelfunc, 1);
		}
	},
	ShowLoading: function (id, title, cancelFunc) {
		cancelFunc = typeof cancelFunc == _UND ? "" : cancelFunc;
		//	alert('ssss');
		var objn = CoverScreen.Create(id);
		//	alert();
		document.body.appendChild(objn);
		objn.Animate({ CSSRule: "opacity:1", Time: 500, DoAt: 1 });
		var clstr = cancelFunc != "" ? '<div class="cls" onclick="CoverScreen.Close(_(\'' + id + '\'),' + cancelFunc.toString() + ')">&times</div>' : '';
		objn.innerHTML = '<div class="lbox  zoomInShort2 animated faster"> ' + clstr + '<div class="txt" id="' + id + '_title">' + title + ' </div><div class="loadingbar"><div class="innermove-l">&nbsp</div></div></div>';
	},

	SetTitle: function (id, title) {
		var titobj = _(id + "_title");
		if (titobj != null) {
			titobj.innerHTML = title;
		}
	}

}

//radio button
var radio = new function () {
	this.RadioArray = new Array();
	this.Click = function (obj, check, uncheck) {
		//alert(obj.ClassNameIs("normal"));
		//alert(check);
		if (_("contradio_" + obj.id).classList.contains("disable")) return;
		var id = _(obj).id;
		var hid = "radio_" + id;
		var allhid = _(_(hid).name + "~" + hid);
		//alert(allhid)
		var grouped = false;
		if (IsArray(allhid)) {
			grouped = true;
			for (var y = 0, leny = allhid.length; y < leny; y++) {
				var hiddenobj = allhid[y];
				var indhid = hiddenobj.id;
				var mainid = indhid.substr(6);
				//alert(mainid);
				_(mainid).className = obj.className.Replace("check", "normal");
				_("radio_" + mainid).value = "false";
			}
		} else if (IsObject(allhid)) {
			grouped = true;
			var indhid = allhid.id;
			var mainid = indhid.substr(6);
			//alert(mainid);
			_(mainid).className = obj.className.Replace("check", "normal");
			_("radio_" + mainid).value = "false";
		}
		// var allhid = 
		if (obj.ClassNameIs("normal")) {
			obj.className = obj.className.Replace("normal", "check");
			radio.RadioArray["radio_" + _(hid).name] = obj.id;
			_("radio_" + obj.id).value = "true";
			if (check != null) check(obj);

			// alert(radio.RadioArray["Radio_"+_(hid).name]);
			//alert("normal");
		} else {
			if (grouped == false) { //if no group radio exist for the object oncheck it
				obj.className = obj.className.Replace("check", "normal");
				radio.RadioArray["radio_" + _(hid).name] = "";
				_("radio_" + obj.id).value = "false";
				if (uncheck != null) uncheck(obj);
			}
			//alert("check"); 
		}
	}



}

//check box
var check = new function () {
	this.Click = function (obj, check, uncheck) {
		// alert();
		if (_("contcheck_" + obj.id).classList.contains("disable")) return;
		var id = _(obj).id;
		var hid = "check_" + id;
		//alert("enter check");
		if (obj.ClassNameIs("normal")) {
			obj.className = obj.className.Replace(" normal", " check");
			radio.RadioArray["check_" + _(hid).name] = obj.id;
			_("check_" + obj.id).value = "true";
			if (check != null) check(obj);

			// alert(radio.RadioArray["Radio_"+_(hid).name]);
			//alert("normal");
		} else {
			obj.className = obj.className.Replace(" check", " normal");
			radio.RadioArray["check_" + _(hid).name] = "";
			_("check_" + obj.id).value = "false";
			if (uncheck != null) uncheck(obj);
			//alert("check"); 
		}
	}

	this.Check = (obj, check) => {
		if (_("contcheck_" + obj.id).classList.contains("disable")) return;
		var id = _(obj).id;
		var hid = "check_" + id;
		if (obj.classList.contains("normal")) {
			obj.className = obj.className.Replace(" normal", " check");
			radio.RadioArray["check_" + _(hid).name] = obj.id;
			_("check_" + obj.id).value = "true";
			if (check != null) check(obj);
		}
	}

	this.UnCheck = (obj, uncheck) => {
		if (_("contcheck_" + obj.id).classList.contains("disable")) return;
		var id = _(obj).id;
		var hid = "check_" + id;
		if (!obj.classList.contains("normal")) {
			obj.className = obj.className.Replace(" check", " normal");
			radio.RadioArray["check_" + _(hid).name] = "";
			_("check_" + obj.id).value = "false";
			if (uncheck != null) uncheck(obj);
		}
	}


}

Object.prototype.Checked = function () {
	if (this.classList.contains("checkbx")) {
		//alert(_("check_"+this.id).value);
		return _("check_" + this.id).value == "true" ? true : false;
	} else if (this.classList.contains("radiobx")) {
		return _("radio_" + this.id).value == "true" ? true : false;
	} else {
		return false;
	}
}

Object.prototype.CheckDisable = function () {
	if (this.ClassNameIs("checkbx")) {
		//alert("contcheck_"+this.id);
		_("contcheck_" + this.id).className = _("contcheck_" + this.id).className.Replace(" enable", " disable");
		//alert(_("check_"+this.id).value);
		//return _("check_"+this.id).value == "true"?true:false;
	}
}
Object.prototype.CheckEnable = function () {
	if (this.ClassNameIs("checkbx")) {
		_("contcheck_" + this.id).className = _("contcheck_" + this.id).className.Replace(" disable", " enable");
		//alert(_("check_"+this.id).value);
		//return _("check_"+this.id).value == "true"?true:false;
	}
}

//tables
var Table = new function () {
	this.Select = function (obj, rwbased, selfunc, unselfunc) {

		rwbased = rwbased || false;
		if (typeof obj == "undefined") return;
		if (obj == null) return;
		var id = obj.id;
		var idarr = id.split("_");
		//check if object sent is a row
		/* if(idarr.length == 3){ //row sent
			//get the total number of cells in the row
			//var totobj = _("totcol_"+id);
			if(obj != null){
				var totcol = obj.cells.length;
				//
				//loop throgh all cells and perform a the select module on it
				for(var f=0; f<totcol; f++){
					//var colid = id + "_"+(f+1);
					//alert(colid);
					//var coll = _(colid);
					var coll = obj.cells[f];
					if(coll != null){//if cell exist
					if(typeof selfunc != "undefined" && f==0){
						if(typeof unselfunc == "undefined"){
						Table.Select(coll,true,selfunc); //perform the select operation on it
						}else{
						Table.Select(coll,true,selfunc,unselfunc); //perform the select operation on it	
						}
					}else{
						Table.Select(coll,true); //perform the select operation on it
					}
					}
				}
			}
			return;
		} */

		var Tid = idarr[0];
		//console.log("Current Click:"+obj.id)
		//Tracer.Tag(Tid);
		var TableData = _("data_" + Tid); if (TableData == null) return;
		//var multiselect = _("multi_"+Tid);

		var lastselect = _("lastsel_" + Tid);
		var lastselectVal = TableData.Data("lastselect");
		//console.log("Last Click:"+lastselectVal)
		//var multi = false;
		//Tracer.Tag(Tid);
		//Tracer.Tag(TableObj);
		//set the multi varaiable to true or false for multiple and single selection respectively
		//if(multiselect != null){
		//console.log(Tid+" = "+TableData.Data("multiselect").Trim())
		var multi = (TableData.Data("multiselect").Trim() == "true") ? true : false;

		var selinput = _("sel_" + Tid);//get the input hidden that will hold selected elements id, (selection string)
		//alert("inpsel_"+id);
		var selStateObj = _("inpsel_" + id); //the selection 
		//check if currently not selected
		if (selStateObj.value.Trim() == "") {
			obj.classList.add("sel"); //select the cell

			if (lastselectVal.Trim() != "" && multi == false) {
				//if there exist last selection and multi 

				//selection is not allowed
				//console.log("not multi");
				if (!rwbased) { //if the cell is not one of the row based selection cell, i.e selection type is cell based
					//console.log(lastselectVal+" = "+(multi?"true":"false"));
					//document.getElementById().classList.remove()
					_(lastselectVal).classList.remove("sel"); //deselect the last selected cell by clearing the selection class
					//alert(lastselect.value);
					//set its status to deselet
					var selstatusobj = _("inpsel_" + lastselectVal);
					if (selstatusobj != null) {
						selstatusobj.value = "";
					}

					Table.RemoveID(selinput, lastselectVal); //romeve last selected cell id from seletions string

				} else { //if it is a row based selection

					//console.log("inp_"+lastselectVal);
					//console.log("inp_"+idarr[0]+"_"+idarr[1]+"_"+idarr[2]);
					//if(lastselectVal != _("inp_"+idarr[0]+"_"+idarr[1]+"_"+idarr[2]).value){ //if the last selected cell is not the current select cell// click it to deselect it
					if (lastselectVal != id) { //if the last selected cell is not the current select cell// click it to deselect it
						//_(lastselectVal).click();
						//Table.Select(_(lastselectVal),true,selfunc,unselfunc); 
						Table.Deselect(_(lastselectVal), rwbased, selfunc, unselfunc);
					}
				}
			}

			if (multi || rwbased) { //if multiple selection is enabled
				// function to handle surounding cells
				//Table.SetSuroundCell(obj,idarr,"sel");
			}

			//set the selection string
			if (selinput != null) {
				var curselval = selinput.value;
				//alert(obj.id);
				if (!rwbased) {
					curselval += "~" + _("inp_" + id).value; //add to selected string
					selinput.value = curselval.TrimLeft("~");
				} else {
					var vallu = _("inp_" + idarr[0] + "_" + idarr[1] + "_" + idarr[2]).value;
					var selinputarrch = curselval.split("~");
					//alert(selinputarrch) 
					var inarr = selinputarrch.InArray(vallu);
					//alert(inarr.Exist);
					if (!inarr.Exist) {
						curselval += "~" + vallu; //add to selected string
						selinput.value = curselval.TrimLeft("~");
					}
				}
			}

			//set the last selected cell of the table
			var useid = "";
			/* if(!rwbased){
				
			 //lastselect.value = obj.id;
			 TableData.Data("lastselect",id);
			 useid = obj.id;
			}else{ */
			//alert("sss");
			// lastselect.value = idarr[0]+"_"+idarr[1]+"_"+idarr[2];
			TableData.Data("lastselect", id);
			/* useid = id;
		   } */
			//set the cell selection state
			selStateObj.value = "sel";
			//alert(selfunc)
			//	if(typeof selfunc != "undefined")selfunc(_(id));
			if (typeof selfunc != "undefined") setTimeout(selfunc, 1, _(id));
		} else {//if currently selected, then deselect it
			if (multi == false) { //if is single selection, dont deselect
				//	if(typeof selfunc != "undefined")selfunc(_(id));
				if (typeof selfunc != "undefined") setTimeout(selfunc, 1, _(id));
				return;
			}
			Table.Deselect(obj, rwbased, selfunc, unselfunc);
			//unselect the cell by clearing the select class
			//if no unselect function set, return without doing sometin
			//if(typeof unselfunc == "undefined")return;
			/* var vallu = (!rwbased)?obj.id:idarr[0]+"_"+idarr[1]+"_"+idarr[2];
			if(typeof unselfunc != "undefined"){
				if(unselfunc == null)return;
				 var rtnval = unselfunc(_(vallu));
				 if(typeof rtnval != _UND && rtnval == false){
					  return;
				 }
				} //run the unselect function if exist
			obj.className = obj.className.Replace("sel","");
			selStateObj.value = ""; //update the state
			if(multi){ //if multiple selection is enabled
				// function to handle surounding cells
				//Table.SetSuroundCell(obj,idarr,"");
			}
			//check if the last selected cell is the current cell to deselect, then set the lastselection to nothing
			
			if(lastselectVal == vallu){
				//lastselect.value = "";
				TableData.Data("lastselect","");
			}
			Table.RemoveID(selinput,vallu); */
			//remove the cell id from the set of selected cell ids
			//alert(selinput.value + " ; " + vallu);
			/*selinput.value = selinput.value.Replace(vallu,"");
			 var selarrs = selinput.value.split("~");
			selarrs = selarrs.Exact();
			selinput.value = selarrs.join("~");*/


		}

		return;
	},

		//function to click
		this.Deselect = function (obj, rwbased, selfunc, unselfunc) {
			var idarr = obj.id.split("_");
			var vallu = (!rwbased) ? obj.id : idarr[0] + "_" + idarr[1] + "_" + idarr[2];
			var id = obj.id;
			if (typeof unselfunc != "undefined") {
				if (unselfunc == null) return;
				var rtnval = unselfunc(_(vallu));
				if (typeof rtnval != _UND && rtnval == false) {
					return;
				}
			} //run the unselect function if exist

			obj.classList.remove("sel");
			var selStateObj = _("inpsel_" + id); //the selection state object
			selStateObj.value = ""; //update the state
			/* if(multi){ //if multiple selection is enabled
				// function to handle surounding cells
				//Table.SetSuroundCell(obj,idarr,"");
			} */
			var Tid = idarr[0];
			//Tracer.Tag(Tid);
			var TableData = _("data_" + Tid); if (TableData == null) return;
			//var multiselect = _("multi_"+Tid);

			//var lastselect = _("lastsel_"+Tid);
			var lastselectVal = TableData.Data("lastselect");
			//check if the last selected cell is the current cell to deselect, then set the lastselection to nothing

			if (lastselectVal == vallu) {
				//lastselect.value = "";
				TableData.Data("lastselect", "");
			}

			var selinput = _("sel_" + Tid);//get the input hidden that will hold selected elements id, (selection string)

			//remove the cell id from the set of selected cell ids
			//alert(selinput.value + " ; " + vallu);
			/*selinput.value = selinput.value.Replace(vallu,"");
			 var selarrs = selinput.value.split("~");
			selarrs = selarrs.Exact();
			selinput.value = selarrs.join("~");*/
			Table.RemoveID(selinput, vallu);
		},

		//function to remove cell id from set
		this.RemoveID = function (selinput, vallu) {
			vallu = _("inp_" + vallu).value
			//console.log("Remove Val="+vallu);
			var curval = selinput.value;
			//console.log("Current Val="+curval);
			var selarrs = ":" + curval.split("~").join("::") + ":";
			//console.log("Current Val(F)="+selarrs);
			selarrs = selarrs.Replace(":" + vallu + ":", "");
			//console.log("Removed(F)="+selarrs);
			//console.log("Trimed="+selarrs.TrimLeft(":").TrimRight(":"))
			selarrs = selarrs.TrimLeft(":").TrimRight(":").split("::");
			// console.log("Removed(F) Array="+selarrs);
			selarrs = selarrs.Exact();
			selinput.value = selarrs.join("~");
			//console.log("Removed="+selinput.value);
			//return selinput;
		}

	//function that handles surounding cells
	this.SetSuroundCell = function (obj, idarr, setState) {
		//get cell row
		var rwnum = idarr[2].ToNumber();
		//get cell column
		var colnum = idarr[3].ToNumber();
		var DirArr = [["Left", "Right", -1, 0], ["Right", "Left", 1, 0], ["Top", "Bottom", 0, -1], ["Bottom", "Top", 0, 1]];
		for (var s = 0, lens = DirArr.length; s < lens; s++) {
			var dir = DirArr[s][0];
			var oppdir = DirArr[s][1];
			var coladd = DirArr[s][2];
			var rowadd = DirArr[s][3];
			var newcelrw = rwnum + rowadd;
			var newcelcol = colnum + coladd;
			var newcellid = idarr[0] + "_rw_" + newcelrw + "_" + newcelcol;
			var newcell = _(newcellid);
			if (!IsNull(newcell)) { //if cell exist
				if (newcell.ClassIs("sel")) { //if cell is currently selected
					if (setState.Trim() == "sel") { //if operation is cell selection
						newcell.className += " Nosel" + oppdir;
						obj.className += " Nosel" + dir;
					} else { //if operation is cell deselection
						newcell.className = newcell.className.Replace(" Nosel" + oppdir, "");
						obj.className = obj.className.Replace(" Nosel" + dir, "");
					}
				}
			}
		}
		return;

	}

	//function to determin if a cell is celected
	this._CellSelected = function (cell) {
		return cell.ClassIs("sel") ? true : false;
	}



	/*this.SetSuround = function(obj){
		
		var id = obj.id;
		var idarr = id.split("_");
		var dir = ["Left","Top","Right","Bottom"];
		var Tid = idarr[0];
		//alert(id);
		if(idarr.length == 3){//i.e object is a row
			var rwnum = idarr[2].ToNumber();
			var toprw = rwnum - 1;
			var botrw = rwnum + 1;
			
			//Table.CheckSet(obj,toprw,0,"Top","Bottom");
			//Table.CheckSet(obj,botrw,0,"Bottom","Top");
			//check if row have more than one column
			var totcol = _("totcol_"+id);
			if(!IsNull(totcol)){
				totcol = totcol.value.ToNumber();
				
				for(var dd=1; dd<=totcol; dd++){
					
					var col = _(id+"_"+dd);
					//alert(col);
					if(!IsNull(col)){
						 var cid = id+"_"+dd;
						// alert(cid);
						if(dd == 1){//first cell
							Table.CheckSetLR(cid,"Right");
						}else if(dd == totcol){
							Table.CheckSetLR(cid,"Left");
						}else{
							Table.CheckSetLR(cid,"Both");
						}
					}
				}
			}
		}else if(idarr.length == 4){
			var rwnum = idarr[2].ToNumber();
			var toprw = rwnum - 1;
			var botrw = rwnum + 1;
			var clnum = idarr[3].ToNumber();
			var leftcol = clnum - 1;
			var rightcol = clnum + 1;
			Table.CheckSet(obj,toprw,clnum,"Top","Bottom");
			Table.CheckSet(obj,botrw,clnum,"Bottom","Top");
			Table.CheckSet(obj,rwnum,leftcol,"Left","Right");
			Table.CheckSet(obj,rwnum,rightcol,"Right","Left");
		}
	}
	
	this.CheckSetLR = function(cid,type){
	 // if(type != "Both"){
		  var col = _(cid);
		  var cidarr = cid.split("_");
		  var Tid = cidarr[0];
		  var rwid = cidarr[2].ToNumber();
		  var clid = cidarr[3].ToNumber();
		  if(!IsNull(col)){
			var typearr = (type == "Both")?["Left","Right"]:[type];
			 if(col.ClassIs("sel")){
				  col.className = col.className.Replace("sel ","");
				   var topcolid = Tid + "_rw_" + (rwid - 1) + "_" + clid;
				  var topcol = _(topcolid);
				  if(!IsNull(topcol)){
						 topcol.className = topcol.className.Replace("NoselBottom","");
						 col.className = col.className.Replace("NoselTop","");
				  }
				  
				  //check for buttom column
				   var bottomcolid = Tid + "_rw_" + (rwid + 1) + "_" + clid;
				  var bottomcol = _(bottomcolid);
				  if(!IsNull(bottomcol)){
					
						 //deselect its top and real column bottom
						 bottomcol.className = bottomcol.className.Replace("NoselTop","");
						 col.className = col.className.Replace("NoselBottom","");
					
				  }
			  }else{
				  col.className += "sel ";
				  //check if top column is selected, deselect the to border
				  var topcolid = Tid + "_rw_" + (rwid - 1) + "_" + clid;
				  var topcol = _(topcolid);
				  if(!IsNull(topcol)){
					 if(topcol.ClassIs("sel")){
						 //deselect its buttom and real column top
						 topcol.className += " NoselBottom";
						 col.className += " NoselTop ";
					 }
				  }
				  
				  //check for buttom column
				   var bottomcolid = Tid + "_rw_" + (rwid + 1) + "_" + clid;
				  var bottomcol = _(bottomcolid);
				  if(!IsNull(bottomcol)){
					 if(bottomcol.ClassIs("sel")){
						 //deselect its top and real column bottom
						 bottomcol.className += " NoselTop";
						 col.className += " NoselBottom";
					 }
				  }
			  }
		   for(var ss=0; ss<typearr.length; ss++){
			  
			  if(col.ClassIs("Nosel"+typearr[ss])){
				  col.className = col.className.Replace("Nosel"+typearr[ss],"");
			  }else{
				  col.className += " Nosel"+typearr[ss];
				  
			  }
			  
		   }
		  }
		  
	 // }
	}
	
	this.CheckSet = function(mobj,rw,cl,mborder,border){
		var mid = mobj.id;
		var midarr = mid.split("_");
		var Tid = midarr[0];
		if(cl == 0){//i.e no row value
			var obj = _(Tid+"_rw_"+rw);
		}else{
			var obj = _(Tid+"_rw_"+rw+"_"+cl);
		}
			if(obj == null)return;
			//if(obj.className.Trim() == "")return;
			//alert(Tid+"_rw_"+rw+" => " + _(Tid+"_rw_"+rw).className);
			var clsarr = obj.className.split(" ");
			clsarr = clsarr.Exact();
			var exist = clsarr.InArray("sel");
			//alert(exist.Exist);
			if(exist.Exist == true){ //if suround row is currently selected
				 nosel = clsarr.InArray("Nosel"+border); //check if the border is already deselected
				 if(nosel.Exist){//if no selection done for the border, select it else viseversa
				  if(mobj.ClassIs("sel")){ //if main object is selected
					//obj.className = obj.className.Replace("Nosel"+border,"");
					 mobj.className += " " + "Nosel"+mborder; //deselect the main common border
					//mobj.className = mobj.className.Replace("Nosel"+mborder,""); 
				  }else{
					  //alert('unselect = ' + obj.className);
					 // alert("Nosel"+border);
					  //obj.className += " " + "Nosel"+border;
					 // alert(obj.className);
					  obj.className = obj.className.Replace("Nosel"+border,""); //just select the other common border only
					 // alert(obj.className);
				  }
				 }else{ //if the other common border is selected
					 if(mobj.ClassIs("sel")){ //if main object is selected
					  
						obj.className += " " + "Nosel"+border;
					 mobj.className += " " + "Nosel"+mborder;
					 }else{
						obj.className += " " + "Nosel"+border; 
					 }
					 
					// mobj.className += " " + "Nosel"+mborder;
				 }
				
			}
			//_("rw_"+rw).className += " NoSel"+border; 
		}*/

}
Object.prototype.CellSelected = function () { return Table._CellSelected(this) }
Object.prototype.TotalRows = function () {
	if (this == null) return 0;
	var totorwinp = this.rows;
	if (IsNull(totorwinp)) return 0;
	return totorwinp.length;
	//"totrw_olevelrst"
};

Object.prototype.Selected = function () {
	if (this == null) return null;
	var tblid = this.id;
	var TableData = _("data_" + tblid);
	if (Null(TableData)) return null;
	var selid = TableData.Data("lastselect").Trim();
	if (selid == "") return null;
	var selected = _(selid);
	return selected;
}

/* Object.prototype.DeselectAll = function(){
	var selectedobj = this.Selected();
	if(selectedobj != null){
		Table.Deselect(selectedobj)
	}
} */

Object.prototype.Cell = function (celnum) {
	var selectedrw = this;
	if (typeof selectedrw.id == _UND) return null;
	return _(selectedrw.id + "_" + celnum);

}

Object.prototype.Selection = function () {
	if (this == null) return null;
	var tblid = this.id;
	var sel = _("sel_" + tblid);
	if (Null(sel)) return null;
	var selids = sel.value.Trim();
	if (selids == "") return null;
	var selidsarr = selids.split("~");
	if (selidsarr.length < 1) return null;
	return _(selidsarr);
}

//object to handle all the elements 
var Elements = new function () {
	this.Data = function (frm) {
		var dt = Elements.FormDataStr(frm, "radio,check");
		alert(Elements.FormDataStr(frm, "radio,check") + "&" + Elements.GetTabledata(frm) + "&" + Switcher.GetData(frm) + "&" + Range.getVal(frm));
	}

	//function to get all table datas
	this.GetTabledata = function (frm) {
		var alltabls = _("table");
		if (IsNull(alltabls)) return "";
		var Getstrval = function (alltabls) {
			var tid = alltabls.id;
			if (tid.Trim() == "") return "";
			var frmname = _("frm_" + tid).value.Trim();
			if (frmname == frm) {
				return tid + "=" + _("sel_" + tid).value;
			}
		}
		if (IsObject(alltabls)) {
			return Getstrval(alltabls);
		} else {
			var rtnstr = "";
			for (var f = 0, lenf = alltabls.length; f < lenf; f++) {
				var objn = alltabls[f];
				rtnstr += "&" + Getstrval(objn);
			}
			var rr = rtnstr.TrimLeft("&");
			return rr.TrimRight("&");
		}
		return "";
	}

	//function to get selected checkboxes
	this.FormDataStr = function (frm, type) {
		// radio.RadioArray[1] = "aaa";

		if (type.Trim() == "") return ""; //if no type send return empty string
		var typearr = type.split(","); //get all types by breaking it into an array
		// alert(typearr.length);
		if (typearr.length > 1) {//if item exist

			var alldata = ""; //hold the resulting data
			for (var dd = 0, lendd = typearr.length; dd < lendd; dd++) {//loop through all types and get the data

				var tp = typearr[dd];
				//alert(tp);
				var dt = Elements.FormDataStr(frm, tp);
				// alert(dt);
				//alert(dd);
				if (!IsEmpty(dt)) {
					alldata += "&" + dt;
				}
			}
			alldata = alldata.TrimLeft("&");
			return alldata;
		} else {
			type = typearr[0];
			//alert(type +" ; 1")
		}

		frm = frm || "Default";
		var rtnstr = "";

		var allradios = _(type + "bx");
		if (IsNull(allradios)) return "";
		if (IsObject(allradios)) {
			allradios = [allradios];
		}
		if (allradios.length > 0) {

			for (var t = 0, lent = allradios.length; t < lent; t++) {
				var rad = allradios[t];
				var id = rad.id;
				var inputelem = _(type + "_" + id);//get theinput element attached to the radio object
				var frmname = _(type + "_frm_" + id).value;
				if (frmname.Trim() != "Default" && frmname.Trim() != frm.Trim()) continue;
				var val = inputelem.value.Trim();
				if (val == "true") { //if checked
					var grpnam = inputelem.name;
					if (type == "radio") { //radio button data 
						rtnstr += "&" + grpnam + "=" + rad.id;
					} else if (type == "check") { //check box data 
						//alert(rad.id);
						rtnstr += "&" + rad.id + "=true";
					}
					// radio.RadioArray["Radio_"+grpnam] = obj.id;
				} else {//if not checked
					if (type == "check") { //check box data 
						rtnstr += "&" + rad.id + "=false";
					}
				}
			}
		}
		rtnstr = rtnstr.TrimLeft("&");
		//alert(rtnstr);
		return rtnstr;
	}

}

/*Switcher*/
var Switcher = function () {
	return {
		Select: function (obj, func) { //function to handle when user select the object
			//alert(obj.Enable);
			if (obj.ClassIs("disabled") && !IsNull(func)) return; //if currently disabled dont do any return
			if (obj.ClassIs("loading") && !IsNull(func)) return;
			//alert(obj);
			Switcher.Switch(obj, func);
			//alert(obj.id);

		},
		Switch: function (obj, func) {
			/*var id = obj.id;
			var ontxt = obj.Data("ontext");
			var offtxt = obj.Data("offtext");*/
			//alert(id);
			//	if(!obj.ClassIs("threeway"))
			if (obj.ClassIs("threeway")) {
				if (obj.ClassIs("normal")) {
					Switcher._SwitchDefault(obj, func);
				} else if (obj.ClassIs("def")) {
					Switcher._SwitchOn(obj, func);
				} else {
					Switcher._SwitchOff(obj, func);
				}
			} else {
				if (obj.ClassIs("normal")) { //check if the current state is off
					Switcher._SwitchOn(obj, func);
				} else {
					Switcher._SwitchOff(obj, func);
				}
			}


		},
		_SwitchOn: function (obj, func) {
			func = func == _UND ? null : func;
			var id = obj.id;
			var ontxt = obj.Data("ontext");
			obj.className = obj.className.replace("normal", "on").replace("def", "on"); // change display to on
			//alert(id);
			//_(id+"_mover").Animate({CSSRule:"margin-left:37px",Time:500}); //animate the switch mover to move 
			//_(id+"_mover").Text(ontxt);//change the text displayed on the moving div
			//set the state hidden
			_("st_" + id).value = 1; //set the state to 1
			obj.Data("value", "1");
			var distxtobj = _(id + "_distext");
			if (distxtobj != null) {
				distxtobj.textContent = ontxt;
			}
			if (!IsNull(func)) { //if onchange function is set
				if (IsArray(func)) {
					func.forEach(element => {
						element(obj, _("st_" + id).value);
					});
				} else {
					func(obj, _("st_" + id).value); //run the function, sending the object and its current state as parameters
				}

			}
		},
		_SwitchOff: function (obj, func) {
			func = func == _UND ? null : func;
			var id = obj.id;
			var offtxt = obj.Data("offtext");
			obj.className = obj.className.replace("on", "normal").replace("def", "normal");// change display to off
			//_(id+"_mover").Animate({CSSRule:"margin-left:2px",Time:500});
			//_(id+"_mover").Text(offtxt);//change the text displayed on the moving div

			_("st_" + id).value = 0; //set the state to 0
			obj.Data("value", "0");
			var distxtobj = _(id + "_distext");
			if (distxtobj != null) {
				distxtobj.textContent = offtxt;
			}
			if (!IsNull(func)) { //if onchange function is set
				if (IsArray(func)) {
					func.forEach(element => {
						element(obj, _("st_" + id).value);
					});
				} else {
					func(obj, _("st_" + id).value); //run the function, sending the object and its current state as parameters
				}
				//alert(func);
				//func(obj,_("st_"+id).value); //run the function, sending the object and its current state as parameters
			}
		},
		_SwitchDefault: function (obj, func) {
			func = func == _UND ? null : func;
			var id = obj.id;
			var deftxt = obj.Data("deftext");
			obj.className = obj.className.replace("on", "def").replace("normal", "def");// change display to off
			//_(id+"_mover").Animate({CSSRule:"margin-left:2px",Time:500});
			//_(id+"_mover").Text(offtxt);//change the text displayed on the moving div

			_("st_" + id).value = -1; //set the state to -1
			obj.Data("value", "-1");
			var distxtobj = _(id + "_distext");
			if (distxtobj != null) {
				distxtobj.textContent = deftxt;
			}
			if (!IsNull(func)) { //if onchange function is set
				if (IsArray(func)) {
					func.forEach(element => {
						element(obj, _("st_" + id).value);
					});
				} else {
					func(obj, _("st_" + id).value); //run the function, sending the object and its current state as parameters
				}
				//func(obj,_("st_"+id).value); //run the function, sending the object and its current state as parameters
			}
		},
		GetData: function (frm) { //function to get all switcher object state of a particular form as data string 
			frm = frm.Trim() || "Default";
			//get all switchers
			var switchers = _("switchbox"); //get all switcher object loaded
			var rtnval = ""; //variable to holde the resulting data string
			if (!IsNull(switchers)) {
				if (IsArray(switchers)) { //if an array i.e more than one switcher object found
					var rtnarr = []; //initialise an array that will hold the data string of individual switcher object found
					for (var d = 0, lend = switchers.length; d < lend; d++) { //loop through all objects
						var switcher = switchers[d]; //get the object
						rtnarr[rtnarr.length] = Switcher.FormSwitcherVal(switcher, frm); //run the function to get the state of the object and return the data string (also check if it exist in the supplied form). and add it to the datastring array
					}
					rtnval = (rtnarr.length > 0) ? rtnarr.join("&") : ""; // join the array data with & symbol to form the full switcher objects data string and return it back to the caller
				} else { //if is one object found
					rtnval = Switcher.FormSwitcherVal(switchers, frm); //get the data string and return it
				}
				return rtnval.TrimRight("&"); //trim any & symbol at the right of the string
			}
		},
		FormSwitcherVal: function (switchers, frm) { //function to form the switcher object data string (id=state). state is 0 or 1

			var rtnval = ""; //will hold the resulting data string
			if (typeof switchers.id != "undefined") { //if switcher object sent has an id (which make it valid)
				//get the id
				var sid = switchers.id;
				//alert("frm_"+sid);
				//check if is for the supplied frm
				if (_("frm_" + sid) == null) return ""; //if no form name hidden input object(hold the name of the form it belongs) not found return empty string, cos we can verify the form it falls;
				if (_("frm_" + sid).value.Trim() == frm) { //verify if it is in the supplied form
					//get the current
					var stateinp = _("st_" + sid).value; //get the state

					rtnval += "&" + sid + "=" + stateinp; //form the data string
					rtnval = rtnval.TrimLeft("&"); //trim the left & symbol
				}
			}
			return rtnval; //return it
		},
		onChange: function (obj, state) { //inbuilt function that can be used to handle onchange event of the switchers, if not defined by the user
			//alert(obj.id + "=" + state);
			//obj.Disable();
			//setTimeout("_('"+obj.id+"').Undo()",3000);
		},
		enable: function (obj) { //function to enable the supplied switcher
			if (obj.ClassIs("switchbox")) {
				if (obj.classList.contains("loading")) { return false }//cannot enable if loading
				if (obj.ClassIs("disabled")) {
					obj.className = obj.className.replace("disabled", "");
					return true;
				}
			}
		},
		disable: function (obj) {//function to disable the supplied switcher
			if (obj.ClassIs("switchbox")) {
				if (!obj.ClassIs("disabled")) {
					obj.className = obj.className + " disabled";
				}
			}
		},
		undo: function (obj) { //return switch to its prevous state
			Switcher.Select(obj, null);
			obj.Enable();
			return obj.GetStatus();
		},
		GetState: function (obj) {
			if (obj.ClassIs("switchbox")) {
				return _("st_" + obj.id).value
			}
		},
		_StartLoading: function (obj) {
			if (obj.ClassIs("switchbox")) {
				//if disabled return
				//if(obj.classList.contains("disabled")){return false}
				if (!obj.classList.contains("loading")) {
					obj.classList.add("loading");
					//obj.className = obj.className + " loading";
					return true;
				}
			}
		},
		_StopLoading: function (obj) {
			if (obj.ClassIs("switchbox")) {
				//if disabled return
				//if(obj.classList.contains("disabled")){obj.classList.remove("disabled")}
				if (obj.classList.contains("loading")) {
					obj.classList.remove("loading");
					//obj.className = obj.className + " loading";
					//return true;
				}
			}
		}
	}
}();
Object.prototype.Enable = function () { Switcher.enable(this) }
Object.prototype.Disable = function () { Switcher.disable(this) }
Object.prototype.Undo = function () { Switcher.undo(this) }
Object.prototype.GetStatus = function () { return Switcher.GetState(this) }
Object.prototype.StartWork = function () { return Switcher._StartLoading(this) }
Object.prototype.StopWork = function () { Switcher._StopLoading(this) }
Object.prototype.SwitchOn = function (func) { Switcher._SwitchOn(this, func) }
Object.prototype.SwitchOff = function (func) { Switcher._SwitchOff(this, func) }
/*range object*/
var Range = function () {

	return {
		moveHandler: function (param) {
			var newval = param.OffsetX + param.MouseX - param.StartX;
			//alert(newval);
			if (newval >= 0 && newval <= 194) {
				var parentid = param.DragObject.id.split("_")[0];
				//alert(parentid)
				if (newval == 97) {
					_(parentid).className = _(parentid).className.Replace(" high", "").Replace(" low", "");
				} else if (newval < 97) {
					_(parentid).className = _(parentid).className.Replace(" high", "").Replace(" low", "") + " low";
				} else if (newval > 97) {
					_(parentid).className = _(parentid).className.Replace(" low", "").Replace(" high", "") + " high";
				}
				param.DragObject.style[param.PropX] = newval + "px";
				var mvVal = newval / 194;
				_(parentid + "_val").value = mvVal;
				//display value
				var max = _(parentid).Data("max").ToNumber();
				var min = _(parentid).Data("min").ToNumber();
				var rangez = max - min;
				var disval = mvVal * rangez;
				disval = Math.round(disval) + min;

				_(parentid + "_dis").textContent = disval;
				var onmovefunc = _(parentid + "_mvfunc").value.Trim();
				if (onmovefunc != "") {
					//eval(onmovefunc + "(_('"+parentid+"'),'"+mvVal+"')");
					setTimeout(onmovefunc + "(_('" + parentid + "'),'" + mvVal + "')", 1);
				}
			}
			// if(param.propY.Trim() != "")param.object.style[param.propY] =(param.offsetY + param.mouseY - param.startY) + "px";
		},
		movestart: function (param) {
			//var obj = param.DragObject;

			//var parentid = param.DragObject.id.split("_")[0];
			//alert(_(parentid).style.cursor);
			document.body.style.cursor = "ew-resize";
		},
		movestop: function (param) {
			//var obj = param.DragObject;
			//var parentid = param.DragObject.id.split("_")[0];
			document.body.style.cursor = "";
		},
		getVal: function (frm) {
			//get all range objects
			var ranges = _("ranges");
			if (!IsNull(ranges)) { //if range object exist
				//if one object found
				if (IsObject(ranges)) {
					if (_(ranges.id + "_frm").value.Trim() == frm) { //if a child of the frm
						//form the datastring
						return ranges.id + "=" + _(ranges.id + "_val").value

					}

				} else { //i.e is an array
					//loop trough all objects found
					var dtstr = "";
					for (var d = 0, lend = ranges.length; d < lend; d++) {
						if (_(ranges[d].id + "_frm").value.Trim() == frm) { //if a child of the frm
							//form the datastring
							dtstr += "&" + ranges[d].id + "=" + _(ranges[d].id + "_val").value

						}
					}
					return dtstr.TrimLeft("&");
				}

			}
		},
		Value: function (obj) {

			if (typeof obj == _UND) return null;
			if (!obj.classList.contains("ranges")) return null;
			var valdis = _(obj.id + "_dis").textContent.ToNumber();
			//alert('rng:'+obj.id);
			return valdis;
		}
		/*,
		registerDrag:function(obj){
			
		 Drag.register(obj,{X:"marginLeft",Y:""},Range.moveHandler);
		}*/
	}
}();
//register the range moving nod
Drag.register("#rangeMove", { X: "marginLeft", Y: "" }, { Moving: Range.moveHandler, Start: Range.movestart, Stop: Range.movestop });
Object.prototype.RangeValue = function () { return Range.Value(this) }
//Object.prototype.State = function(){return Switcher.GetState(this)}();


/*Tab objects*/
var Tabs = function () {

	return {
		CurrentSel: null,
		Select: function (tabobj) {

			//get selected
			var selid = _(tabobj.id.split("_")[0] + "_sel").value.Trim();
			var grpName = Tabs.GetGroupName(tabobj.id);
			//hide the tabbox
			Pages.HideGroupTabs();
			var tabName = Tabs.GetTabName(tabobj.id);
			var tabDisName = Tabs.GetTabDisplayName(tabobj.id);
			var userdet = Cookie.Get("UserDet");
			if (userdet.Trim() == "") { MessageBox.Show("User Identification Failed: Logout and Re-Login"); return; }
			var userdetarr = userdet.split("~");
			if (userdetarr.length < 3) { MessageBox.Show("Inavlid User: Logout and Re-Login"); return; }
			var priv = userdetarr[6].Trim();
			if (priv == "") { MessageBox.Show("User Privileges Identification Failed: Logout and Re-Login"); return; }
			var privarr = priv.split(":");
			var exist = privarr.InArray(tabName);
			if (!exist.Exist) { MessageBox.Show("#Access Denied <br /> Browser-Reload the system and Try Again"); return; }
			if (selid == tabobj.id.Trim()) return; //if the currently clicked tab is open return
			if (selid != "") { //if a tab is currently open
				if (_(selid + "_body") != null) _(selid + "_body").className = _(selid + "_body").className.Replace(" show", ""); //close the body
				//get the tab button
				//var tabid  = Tabs.CurrentSel.id.split("_")[0];
				_(selid).className = _(selid).className.Replace(" active", ""); //make the tab button deselected
			}
			var selectid = tabobj.id;
			var bodyid = selectid + "_body";
			if (_(bodyid) != null) _(bodyid).className += " show"; //display the new selected tab body
			_(tabobj.id.split("_")[0] + "_sel").value = tabobj.id; //reset the select tab
			tabobj.className += " active"; //make the tab button the active one
			var tabbox = tabobj.id.split("_")[0];
			var tabind = tabobj.id.split("_")[2];
			Page.CurrOpen = tabbox.substr(0, tabbox.length - 3);
			Page.Opened[Page.CurrOpen] = grpName + ";" + tabind + ";" + tabName + ";" + tabDisName; //the group name will be use to load the menu group in the pages window
			// alert(Page.Opened[Page.CurrOpen]);
			Pages.Add(tabName, tabind, grpName); //add the tab page to pages

			//select the menu in the explorer
			//Get the explorer menu first
			var menuinexplorer = _('explorersubmenu_' + tabName);
			if (menuinexplorer != null) Fender.SelectSub(menuinexplorer);//Fender Object is in main.js

		},//function to get the current selected tab id
		GetSelID: function (tab) {
			if (tab == null) return null; //if no tab object send return null
			var tabid = tab.id.Trim();
			if (tabid == "") return null; //if no id return null
			var selidinp = _(tabid + "_sel");
			if (selidinp == null) return null;
			return selidinp.value;
		},//function to get the tab name using the id
		GetTabName: function (tabid) {
			//var id = Tabs.GetSelID(tabid);
			var tnameinp = _(tabid + "_tabName");
			if (tnameinp != null) {
				return tnameinp.value;
			} else {
				return "";
			}
		},//function to get the tab name using the id
		GetTabDisplayName: function (tabid) {
			//var id = Tabs.GetSelID(tabid);
			var tnameinp = _(tabid + "_tabDisName");
			if (tnameinp != null) {
				return tnameinp.value;
			} else {
				return "";
			}
		},//function to get the group name using the id
		GetGroupName: function (tabid) {
			//var id = Tabs.GetSelID(tabid);
			var tnameinp = _(tabid + "_groupName");
			if (tnameinp != null) {
				return tnameinp.value;
			} else {
				return "";
			}
		}, GetGroupByTabName: function (tabName) {
			var grpinp = _('explorersubmenu_' + tabName + '_gn');
			return grpinp == null ? '' : grpinp.value;
			//explorersubmenu_exsetting_gn
		}, GetTabIndexByTabName: function (tabName) {
			//tabindex_PreLoader
			var grpinp = _('tabindex_' + tabName);
			return grpinp == null ? -1 : grpinp.value.ToNumber();
		}
		,//function to get the Tab Text using the id
		GetTabText: function (groupName, tabName) {
			//var id = Tabs.GetSelID(tabid);
			/* var tabs = _(groupName + "_tabs");
			console.log(tabs);
			if(tabs == null)return tabName;
			var tval = tabs.value;
			if(tval.Trim() == "")return tabName;
			var tarr = tval.split("&");
			for(var s=0; s < tarr.length; s++){
				var tabind = tarr[s];
				var tabinarr = tabind.split("=");
				if(tabinarr.length == 2){
					var tbname = tabinarr[0];
					if(tbname.Trim() == tabName.Trim()){
						return tabinarr[1];
					}
				}
			    
			} */
			var tabn = JSON.parse(_(tabName + "_data").textContent);
			return tabn.TDisName;
		},
		AllProgressObject: {},
		ProgressDetails: {},
		ProgressSetAbort: function (tabid, tabindex, func) {
			Tabs.ProgressDetails[tabid + "_" + tabindex] = func;
		},
		RunAbort: function (tabid, tabindex) {
			//  console.log(tabid+"_"+tabindex);
			//  console.log(Tabs.ProgressDetails);
			//  console.log(Tabs.ProgressDetails[tabid+"_"+tabindex]);
			if (typeof Tabs.ProgressDetails[tabid + "_" + tabindex] == "function") {
				func();
			} else if (typeof Tabs.ProgressDetails[tabid + "_" + tabindex] != _UND && Tabs.ProgressDetails[tabid + "_" + tabindex] != null) {
				Tabs.ProgressDetails[tabid + "_" + tabindex].Abort();
			} else {
				MessageBox.Show("#Not Allowed");
				Tabs.ProgressDetails[tabid + "_" + tabindex] = null;
				return;
			}
			Tabs.Tab(tabid).ProgressGet(tabindex).ProgressTo(-1);
			Tabs.ProgressDetails[tabid + "_" + tabindex] = null;
		},
		//function to get Tabs progress bar
		GetProgress: function (tabid, tabindex) {
			var progresbxid = tabid + "_" + tabindex + "_progressbox";
			var progresbx2id = tabid + "_" + tabindex /* + "_progress-2-bx" */;
			if (typeof Tabs.AllProgressObject[progresbxid] == _UND) {
				if (typeof ProgressBar != _UND) {
					Tabs.AllProgressObject[progresbxid] = new ProgressBar.Circle("#" + progresbx2id + "_progress-2-bx", {
						color: '#bbb',
						// This has to be the same size as the maximum width to
						// prevent clipping
						strokeWidth: 4,
						trailWidth: 1,
						trailColor: '#999',
						easing: 'easeInOut',
						duration: 800,
						text: {
							autoStyleContainer: false
						},
						from: { color: '#bbb', width: 1 },
						to: { color: '#fafafa', width: 4 },
						// Set default step function for all animate calls
						step: function (state, circle) {
							circle.path.setAttribute('stroke', state.color);
							circle.path.setAttribute('stroke-width', state.width);

							var value = Math.round(circle.value() * 100);
							if (value === 0) {
								circle.setText('');
							} else {
								circle.setText(value + '%');
							}

						}
					});
				}

			}
			return _(progresbxid);
		},
		//function to display the progressive box
		_ProgressStart: function (progreObj) {
			if (IsNull(progreObj)) return false;
			if (progreObj.style.opacity == "1") return false;
			//get the progress object id
			var progresid = progreObj.id

			//get progid component
			var progidarr = progresid.split("_");
			var tabid = progidarr[0];
			var tabindex = progidarr[1];

			if (typeof ProgressBar == _UND) {
				//get the bar - default bar
				var barid = progresid.substr(0, progresid.length - 3) + "bar";
				var barobj = _(barid); //get the bar
				if (!IsNull(barobj)) { barobj.style.width = "0%" }; //reset the bar state
			} else {
				var curtabproobj = Tabs.AllProgressObject[progresid];

				curtabproobj.set(0);
				curtabproobj.text.style.fontSize = '2rem';
			}

			//alert(barid);


			var tabBody = _(tabid + "_tb_" + tabindex + "_body");
			if (!IsNull(tabBody)) tabBody.style.overflow = "hidden";
			progreObj.Animate({ CSSRule: "opacity:1;visibility:visible", Time: 500 });

			//curtabproobj.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';

			//{$curtabid}_tb_{$tabindex}_body
			return true;
		},
		//function to set teh new level
		_ProgressTo: function (progreObj, to, endfunc) {
			// if(progreObj.ProgressState() != 0){MessageBox.Show("System Busy, Try Again Later");return}
			endfunc = typeof endfunc == _UND ? "" : endfunc;
			if (typeof Tabs.StepToArr[progreObj.id] != "undefined") {
				if (Tabs.StepToArr[progreObj.id] != null) { //check if currently steping
					clearTimeout(Tabs.StepToArr[progreObj.id]); //stop the timmer
					Tabs.StepToArr[progreObj.id] = null;
				}
			}
			to = (typeof to == "undefined") ? 100 : to;
			if (IsNull(progreObj)) return;
			//alert(progreObj.style.opacity);
			var start = (progreObj.style.opacity != "1") ? progreObj.ProgressStart() : 1;
			if (start == false) return start;
			if (typeof ProgressBar == _UND) {
				//get the bar - default 
				var barid = progreObj.id.substr(0, progreObj.id.length - 3) + "bar";
				var barobj = _(barid); //get the bar
				if (IsNull(barobj)) return;
			} else {
				var newprog = Tabs.AllProgressObject[progreObj.id];
			}

			if (to >= 100 || to < 0) {
				//alert(to);
				if (typeof ProgressBar == _UND) {
					barobj.Animate({ CSSRule: "width:" + to + "%", Time: 1000, DoAt: 1.0, EndAction: "_('" + progreObj.id + "').ProgressStop();" + endfunc });//default
				} else {
					to = to < 0 ? 0 : to;
					newprog.animate(to / 100, { duration: 1400 }, function () { eval("_('" + progreObj.id + "').ProgressStop();" + endfunc) });
				}

			} else {
				if (typeof ProgressBar == _UND) {
					barobj.Animate({ CSSRule: "width:" + to + "%", Time: 1000, DoAt: 1.0, EndAction: endfunc }); //default
				} else {
					newprog.animate(to / 100, { duration: 1400 }, function () { eval(endfunc) });
				}

			}
			return true;
		},
		_ProgressState: function (progreObj) { //get the state of the progress, on/off
			var start = (progreObj.style.opacity != "1") ? 0 : 1;
			return start;
		},
		StepToArr: Array(),//array to hold the timmer of the tab page steps
		//function to set teh new level by moving steps
		_ProgressStepTo: function (progreObj, to) {

			to = (typeof to == "undefined") ? 100 : to;
			if (IsNull(progreObj)) return;
			//alert(progreObj.style.opacity);
			if (progreObj.style.opacity != "1") { progreObj.ProgressStart() };
			//get the bar
			var barid = progreObj.id.substr(0, progreObj.id.length - 3) + "bar";
			var barobj = _(barid); //get the bar
			if (IsNull(barobj)) return;

			if (barobj.style.width.Trim() == "") barobj.style.width = "0%";
			var newmv = barobj.style.width.ToNumber() + 4;
			// barobj.style.width = (barobj.style.width.ToNumber() + 4) + "%";
			progreObj.ProgressTo(newmv); //progress to new steped level
			if (newmv < to && newmv < 100) {
				Tabs.StepToArr[progreObj.id] = setTimeout("_('" + progreObj.id + "').ProgressStepTo(" + to + ")", 1000);
			}
			/* if(to >= 100){
				barobj.Animate({CSSRule:"width:"+to+"%",Time:(to/0.1),DoAt:1.0,EndAction:"_('"+progreObj.id+"').ProgressStop()"}); 
			 }else{
			  barobj.Animate({CSSRule:"width:"+to+"%",Time:(to/0.1)});
			 }*/
		},
		//function to get the selected tab name (mainly use as the selection tab operation object name, e.g Student.Biodata...)
		_GetSelectTabName: function (tabsId) {
			if (typeof tabsId == _UND) { return "" }
			var rId = tabsId;
			if (IsObject(rId)) {
				rId = rId.id;
			}
			var selectedIndex = _(tabsId).PageSelectedIndex()
			//selectedIndex = typeof selectedIndex == _UND?0:SelectedIndex;
			var seltabNameObj = _(rId + 'tab_tb_' + selectedIndex + '_name');
			return seltabNameObj == null ? "" : seltabNameObj.value;
		},
		//function to stop/close the progression
		_ProgressStop: function (progreObj) {
			//get the progress object id
			var progresid = progreObj.id
			var progidarr = progresid.split("_");
			var tabid = progidarr[0];
			var tabindex = progidarr[1];
			//get the bar
			var barid = progreObj.id.substr(0, progreObj.id.length - 3) + "bar";
			progreObj.Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 400, DoAt: 1.0, EndAction: "_('" + barid + "').style.width='0px'" });
			var tabBody = _(tabid + "_tb_" + tabindex + "_body");
			if (!IsNull(tabBody)) tabBody.style.overflow = "auto";

		},
		Tab: function (tabname) {
			if (typeof tabname == _UND) return {};
			if (tabname.Trim() == "") return {};
			var tabobj = _(tabname + "tab");
			if (tabobj == null) return {};
			// alert(tabobj);
			return tabobj;
		},
		Toolbox: {
			GetObject: function (pgid) {
				var tabname = _(pgid).SelectedName(); //get the selected tab name 
				if (tabname == "") { return null; }
				if (typeof window[pgid] == _UND) { return null; }
				var MainObj = window[pgid];
				if (typeof MainObj[tabname] == _UND) { return null; }
				var SubObj = MainObj[tabname];
				return SubObj;

			},
			Perform: function (pgid, operation) {
				//pgid = the page id 
				var SubObj = Tabs.Toolbox.GetObject(pgid);
				if (SubObj == null || typeof SubObj[operation] == _UND) { MessageBox.Show('Not Applicable'); return null; }
				//SubObj[operation]();
				setTimeout('Tabs.Toolbox.GetObject("' + pgid + '")["' + operation + '"]()');
			}/*,
		 Print:function(pgid){
			  //pgid = the page id 
			  var SubObj = Tabs.Toolbox.GetObject(pgid);
			  if(SubObj == null || typeof SubObj.Print == _UND){MessageBox.Show('Not Applicable');return null;}
			  SubObj.Print();
		 },
		 Clear:function(pgid){
			  //pgid = the page id 
			  var SubObj = Tabs.Toolbox.GetObject(pgid);
			  if(SubObj == null || typeof SubObj.Clear == _UND){MessageBox.Show('Not Applicable');return null;}
			  SubObj.Clear();
		 },
		 Delete:function(pgid){
			  //pgid = the page id 
			  var SubObj = Tabs.Toolbox.GetObject(pgid);
			  if(SubObj == null || typeof SubObj.Delete == _UND){MessageBox.Show('Not Applicable');return null;}
			  SubObj.Delete();
		 },
		 Copy:function(pgid){
			  //pgid = the page id 
			  var SubObj = Tabs.Toolbox.GetObject(pgid);
			  if(SubObj == null || typeof SubObj.Copy == _UND){MessageBox.Show('Not Applicable');return null;}
			  SubObj.Save();
		 }*/
		},
		ShowSideBar: (tabname, tabindex) => {
			let sidebar = _(tabname + 'tab_' + tabindex + '_sidebar');
			if (sidebar != null) {
				sidebar.classList.remove('minimize');
			}
		},
		HideSideBar: (tabname, tabindex) => {
			let sidebar = _(tabname + 'tab_' + tabindex + '_sidebar');
			if (sidebar != null) {
				sidebar.classList.add('minimize');
			}
		}



	}
}();

Object.prototype.SelectedID = function () { return Tabs.GetSelID(this) }
Object.prototype.SelectedIndex = function () { return this.SelectedID().split("_")[2].ToNumber() };
Object.prototype.ProgressStart = function () { Tabs._ProgressStart(this) }
Object.prototype.ProgressTo = function (to, endfunc) { Tabs._ProgressTo(this, to, endfunc) }
Object.prototype.ProgressStepTo = function (to) { Tabs._ProgressStepTo(this, to) }
Object.prototype.ProgressStop = function () { Tabs._ProgressStop(this) }
Object.prototype.ProgressGet = function (tabindex) { return Tabs.GetProgress(this.id, tabindex) }//ProgressStepTo
Object.prototype.ProgressState = function () { return Tabs._ProgressState(this) }
Object.prototype.SelectedName = function () { return Tabs._GetSelectTabName(this) }
//_GetSelectTabName:function(tabsId,selectedIndex)
/*Textbox*/
var TextBox = function () {
	return {
		Filter: function (obj) {
			if (typeof obj.id == _UND || obj.id.Trim() == "") return;
			var filtertbid = obj.id;
			var filterstr = obj.value.Trim() == "" ? "" : obj.value;
			var idarr = filtertbid.split("_");
			var tableid = idarr[0];
			//get the table
			var table = _(tableid);
			if (table == null) return;
			table = IsArray(table) ? table[0] : table;
			tb = document.createElement('table');

			//get all table rows
			var totrows = table.rows.length;
			for (var rw = 0; rw < totrows; rw++) {
				var indrow = table.rows[rw];
				if (indrow.classList.contains('head') || indrow.className.indexOf(' deleterw') > -1) continue;
				seen = true;
				if (filterstr != "") {
					seen = false;
					//loop through alll cells
					for (var cl = 0, lencl = indrow.cells.length; cl < lencl; cl++) {
						var indcel = indrow.cells[cl];
						//alert(indcel.textContent);
						//check if indcel contains the filterstr
						var spos = indcel.textContent.toLowerCase().search(filterstr.toLowerCase());
						if (spos > -1) {
							seen = true;
							break
						}
					}
				}

				if (seen) {
					indrow.style.display = "table-row";
				} else {
					indrow.style.display = "none";
				}
			}

		},
		Toggle: function (obj) {
			//alert(document.querySelector(":focus"));

		},
		Form: function (param) {
			var id = param.id;
			var logo = typeof param.logo == _UND ? "font" : param.logo;
			var title = typeof param.title == _UND ? "" : param.title;
			var info = typeof param.info == _UND ? "" : param.info;
			var style = typeof param.style == _UND ? "" : param.style;
			return '<div class="textBx  objgrpdefaultelem" title="Position" style="' + style + '" id="' + id + '" data-chain="" data-validate="" data-form="objgrpdefaultelem" data-onchange="" data-value="">	<i class="fa fa-' + logo + '" style="font-size:1em" aria-hidden="true" id="' + id + '_icon"></i><input id="' + id + '_inp" onblur="TextBox.Validate(_(\'' + id + '\'));_(\'' + id + '_icon\').classList.remove(\'altColor2\');" value="" onkeyup="" placeholder="' + title + '" title="' + title + '" onfocus="_(\'' + id + '_icon\').classList.add(\'altColor2\');" type="text"><div id="' + id + '_drpd" class="greyShadow"></div></div><div class="texta objgrpdefaultelem" style="display:block;padding-left:10px;font-size:0.7em;width:270px;color:rgba(0,0,0,.7);visibility:visible;position:relative;font-style:italic">' + info + '</div>';
		},
		Select: function (obj, unselect) {
			//console.log('select');
			var rwid = obj.id; //the id of the selected cell
			//alert(rwid);
			var txt = obj.Text(); //the text content of the sellected cell
			//console.log('selected Text: '+txt);
			var rwarr = rwid.split("_"); //break cell id to get table, row id
			var tbid = rwarr[0]; //get the table id
			var textbid = tbid.TrimRight(2); // from the table id get the textbox id which is table id removing the last two char (tb)
			var textB = _(textbid);
			//var chain = _(textbid+"_chain"); //get the chain hidden object
			var forceOnchange = false; //force the onchange funct to trigger (needed if selection is a chain selection)
			chainValue = textB != null ? textB.Data("chain") : "";

			//if(chain != null){
			//if(chain.value.Trim() != ""){ //check if element run chain loading
			if (chainValue != "") {
				//alert(chain.value);
				TextBox.AddChain(chainValue); //register the chain loading	
				forceOnchange = true;
			}
			//}
			var inputid = textbid + "_inp"; //through the textbox id form the text input id
			var userid = "inp_" + rwid; //get the user defined id input element id
			//var selstate = _("inpsel_"+rwid).value;
			var userID = _(userid).value; //grt the user defined id for the cell
			var userID = userID.split("_")[0];
			//console.log('UserID: '+userID);
			//get the currently selected ID
			//var selID = _(textbid + "_inpVal").value;
			var selID = textB != null ? textB.Data("value") : "";
			//console.log('selected ID: '+selID);
			//alert(_(inputid));
			var disinp = _(inputid);
			var preinputval = disinp.Text(); //tempoarily holds the current text content. for confirmation if content change
			//check if selected id = current id
			if ((userID.Trim() == selID.Trim() && selID.Trim() != "") || typeof unselect != "undefined") {
				//console.log('Already Selected');
				//clear the selected id and text
				//Tracer.Tag(textbid+": Cleared, due to the current selected equall to the last selected");
				//_(textbid + "_inpVal").value = "";
				//(rwid + "->unselect: "+unselect).__();
				/*if(userID.Trim() == selID.Trim() && selID.Trim() != ""){
				  return false;
				}*/

				//textB.Data("value","");
				//disinp.Text("");
			} else {
				//console.log('Not Already Selected');
				//set the input value
				//_(textbid + "_inpVal").value = userID;
				textB.Data("value", userID);

				//set the input text
				disinp.Text(txt);

			}
			//alert(preinputval+ " / "+ _(inputid).Text());
			//alert("User ID = "+userID.Trim()+ " / Selected ID = "+selID.Trim());
			//confirm if input text has changed
			if (preinputval != disinp.Text() || forceOnchange == true) {
				//perform the onchange functio
				//var onchange = _(textbid + "_onch").value.Trim();
				var onchange = textB.Data("onchange").Trim();
				//alert(onchange);
				if (onchange != "" && typeof unselect == "undefined") setTimeout(onchange + "(_('" + textbid + "'))", 1);
			}

			//perform validation
			TextBox.Validate(_(textbid));
			//return true;
			//alert(textbid);
		},
		UnSelect: function (obj) {
			return TextBox.Select(obj, true);
		},
		Validate: function (tb) {
			//alert(tb);
			//required fields
			if (tb.ClassIs("req") || tb.ClassIs("reqs")) {
				var txt = tb.TextContent().Trim();
				//alert(txt);
				if (txt != "") {
					tb.className = (tb.ClassIs("req")) ? tb.className.Replace("req", "reqs") : tb.className;
				} else {
					tb.className = (tb.ClassIs("reqs")) ? tb.className.Replace("reqs", "req") : tb.className;
				}
			}
			//
			//get validate typoe
			//var validate = _(tb.id + "_validate").value;
			var validate = tb.Data("validate");
			//alert(validate);
			//email
			if (validate == "email") {
				var txt = tb.TextContent().Trim();
				//if(txt != ""){
				if (IsEmail(txt) || txt == "") {
					tb.className = (tb.ClassIs("err")) ? tb.className.Replace("err", "") : tb.className;
				} else {
					tb.className = (!tb.ClassIs("err")) ? tb.className + " err" : tb.className;
				}
				//}
			}

			//phone number
			if (validate == "phone") {
				var txt = tb.TextContent().Trim();

				if (IsPhoneNumber(txt) || txt == "") {
					tb.className = (tb.ClassIs("err")) ? tb.className.Replace("err", "") : tb.className;
				} else {
					tb.className = (!tb.ClassIs("err")) ? tb.className + " err" : tb.className;
				}

			}
		},
		//function to get the supplied textbox value
		GetValue: function (textb) {
			// var textbID = textb.id.Trim(); //get the textbox id
			// if(textbID == "")return ""; //if no id return null
			//get the value input element
			// var ValInp = _(textbID + "_inpVal");
			/*var selValue = textb.Data("value").split("_");
			 if(selValue.length > 1){
				 rwcolid = selValue.pop();
			 }
			 return selValue.join("_");*/
			return textb.Data("value");
			//  if(ValInp == null)return ""; //if no input element that holds the value return null
			//if(ValInp.value.Trim() == "")return "";
			//  if(ValInptxt.Trim() == "")return "";
			//return ValInp.value.split("_")[0];
			// return ValInptxt.split("_")[0];
		},//function to get the supplied textbox text
		GetText: function (textb) {
			var textbID = textb.id.Trim(); //get the textbox id
			if (textbID == "") return ""; //if no id return null
			//get the value input element
			var ValInp = _(textbID + "_inp");
			if (ValInp == null) {
				if (typeof textb.value != _UND) {
					return textb.value;
				} else {
					return ""; //if no input element that holds the text return null
				}
			}
			return ValInp.value;
		},//function to disable textbox
		_TextDisable: function (textb) {
			var textbID = textb.id.Trim(); //get the textbox id
			if (textbID == "") return; //if no id return
			//get the value input element
			var ValInp = _(textbID + "_inp");
			if (ValInp == null) return; //if no input element that holds the text return
			ValInp.disabled = "disabled";
		},//function to enable textbox
		_TextEnable: function (textb) {
			var textbID = textb.id.Trim(); //get the textbox id
			if (textbID == "") return; //if no id return
			//get the value input element
			var ValInp = _(textbID + "_inp");
			if (ValInp == null) return; //if no input element that holds the text return
			ValInp.disabled = "";
		},//function to give textbox focus
		_TextFocus: function (textb) {
			var textbID = textb.id.Trim(); //get the textbox id
			if (textbID == "") return; //if no id return
			//get the value input element
			var ValInp = _(textbID + "_inp");
			if (ValInp == null) return; //if no input element that holds the text return
			ValInp.focus();
		},//object to clear the text
		_ClearText: function (textb, only) { //only helps to determine if the text displayed is to be cleared only living the selected value
			//check if it is  an array
			if (IsArray(textb)) {
				for (var f = 0, lenf = textb.length; f < lenf; f++) {
					var newtb = textb[f];
					if (only != _UND) {
						if (newtb != null) setTimeout("TextBox._ClearText(_('" + newtb.id + "'),true)", 50);
					} else { if (newtb != null) setTimeout("TextBox._ClearText(_('" + newtb.id + "'))", 50) }

				}
			} else {
				var textbID = textb.id.Trim(); //get the textbox id
				if (textbID != "") { //if no id return
					//check if has a dropdown
					var DD = textb.GetDropDownTable();
					if (DD != null && typeof only == "undefined") {
						//get the selected cell
						var SelCell = DD.Selected();
						if (SelCell != null) {
							//SelCell.click(); //click the selected cell to unselect it
							Table.Deselect(SelCell);
						}
					}
					//get the value input element
					var ValInp = _(textbID + "_inp");
					if (ValInp != null) { //if no input element that holds the text return
						ValInp.value = "";
						TextBox.Validate(textb);
					}
					//console.log(textb);
					textb.Data("value", ""); //clear the select id as well
				}
			}
			return true;
		},//function to set the text value of the textbox
		_SetText: function (textb, txt) {
			var textbID = textb.id; //get the textbox id
			if (textbID != "") { //if no id return null
				//get the value input element
				var ValInp = _(textbID + "_inp");
				if (ValInp != null) { //if no input element that holds the text return null
					ValInp.value = txt;
					TextBox.Validate(textb);
				}
				return txt;
			}
			//return true;
		}, ChainSelect: new Array(),//function to set the text value of the textbox by the a dropdown ID
		AddChain: function (chian) {
			//load the chain selection pertern in the chain array - format = texboxID1:selectID1;texboxID2:selectID2;.....
			if (typeof chian == "undefined") return;
			var chainarr = chian.split(";");
			if (chainarr.length > 0) {
				for (var s = 0, lens = chainarr.length; s < lens; s++) {
					var chainInd = chainarr[s];
					var chainIndarr = chainInd.split(":");
					if (chainIndarr.length == 2) {
						if (typeof TextBox.ChainSelect[chainIndarr[0]] == "undefined") { //if chain element not added at all add it and set id
							TextBox.ChainSelect[chainIndarr[0]] = chainIndarr[1];
						} else if (chainIndarr[1] != "") { //if added and id is not empty reset it to new id
							TextBox.ChainSelect[chainIndarr[0]] = chainIndarr[1];
						}

					}
				}
			}
			//}
		},
		_SelectText: function (obj, id, chian) {//select the cell of the textbox table whose user id is sent as id

			//if ivaliid textbox sent return
			if (typeof obj == _UND && !obj.classList.contains('textBx')) return;
			//if textbox chain is sent
			TextBox.AddChain(chian);
			//get the input element that carries the cell id
			//=> textboxid+"tb_"+selid+"_1"


			var inpholdscellid = _(obj.id + "tb_" + id + "_1");
			//get teh tabel cell to select
			var tbcell = inpholdscellid == null ? null : _(inpholdscellid.value);
			if (tbcell == null) {
				//if id to select does not exit, deselect the currently selected id if exist
				//*************************** */
				//Get the textbox table (dropdown)
				var DDT = obj.GetDropDownTable();
				//get the selected text
				var selcell = DDT.Selected();
				//console.log("Deselectobj: "+selcell);
				if (selcell != null) { //if selected cell exist
					//console.log("Deselect: "+selcell.id);
					//deselect it and clear the texbox text
					Table.Deselect(selcell, false, TextBox.Select, TextBox.UnSelect);
				}
				obj.Data("value", ""); //clear the textbox value content
				var tbInput = _(obj.id + "_inp");
				if (!Null(tbInput)) tbInput.value = ""; //clear the display input
				//*************************** */
			} else { //if exist

				//get the dropdown table cell
				Table.Select(tbcell, false, TextBox.Select, TextBox.UnSelect);

			}

		}
		/* _SelectText:function(obj,id,chian){ 
			TextBox.AddChain(chian);
			var sid = id; //tempoaryly keep the raw id
		  id = obj.id+"tb_"+id+"_1";
		//Tracer.Tag("To Select: "+id); 
		   if(_(id) == null){ //if user id supplied does not exist
			   //Tracer.Tag("ID Not Exist: "+id); 
		              
				//alert(id);
				var DDT = obj.GetDropDownTable(); //get the DropDown Table
				if(!Null(DDT)){
					//Tracer.Tag("Drop Down Found"); 
					//get the selected cell
					var selcell = DDT.Selected();
					//alert(selcell);
					
					if(!Null(selcell)){
						//Tracer.Tag("Selected Found"); 
						selcell.click(); //click it to deselect it
						//Tracer.Tag("Deselected"); 
					}else{//
						//Tracer.Tag("Selected Not Found");
					var tbInput = _(obj.id + "_inp");
						if(!Null(tbInput))tbInput.value = "";
						//Tracer.Tag("Selected input element cleard");
					}
				}
				//return;
			}else{
				//Tracer.Tag("User sent id Exist: "+id);
			var cellid = _(id).value; //get the real (generated) cell id
			 var selid = obj.Data("value");
			
			//TextBox.Select(_(cellid));
			//Tracer.Tag("Value data: "+selid);
			//Tracer.Tag("sid_1: "+sid+"_1");
			if((selid != sid)){
				//Tracer.Tag("");
				var celll = _(cellid);
			 if(!Null(celll))celll.click();
			}else if(typeof chian != "undefined" && chian != ""){
				//Tracer.Tag(chaintbid)
				var chainarr = chian.split(";"); //get all the chains
				var imideate = chainarr[0]; //get the individual chain
				//Tracer.Tag(imideate);
				var imideatearr = imideate.split(":");
				if(imideatearr.length == 2){
					var chaintbid = imideatearr[0];
					var chaintbcellid = imideatearr[1];
					var remchaintbs = "";
					if(chainarr.length > 1){ //form the remaining chain tbs
					  for(var d=1; d < chainarr.length; d++){
						   remchaintbs += chainarr[d] + ";";
					  }
						remchaintbs = remchaintbs.TrimRight(";");
					}
					var wtb = _(chaintbid);
					if(wtb != null){
						wtb.SelectText(chaintbcellid,remchaintbs); //select the id
						TextBox.ChainSelect[chaintbid] = ""; //reset the textbox chain id to empty
					}
				    
				}
				
			}
			}
			//return true;
		} */,//function to set DateBox textboxes
		_SetDate: function (obj, DateStr) {
			//format should be Y-M-D
			if (DateStr.Trim() != "") {
				var objid = obj.id;
				var dayTB = _(obj.id + ".day");
				var monthTB = _(obj.id + ".month");
				var yearTB = _(obj.id + ".year");
				var Datearr = DateStr.split("-");
				var year = Datearr[0].ToNumber();
				var month = Datearr[1].ToNumber();
				var day = Datearr[2].ToNumber();

				//if(!IsNull(dayTB))(day > 0)?dayTB.SelectText(day):dayTB.ClearText();
				if (dayTB != null) dayTB.SelectText(day)
				//if(!IsNull(monthTB))(month > 0)?monthTB.SelectText(month):monthTB.ClearText();
				if (monthTB != null) monthTB.SelectText(month);
				//if(!IsNull(yearTB))(year > 0)?yearTB.SelectText(year):yearTB.ClearText();
				if (yearTB != null) yearTB.SelectText(year);
			}
			//return true;
		},//function to load droup down for a textbox
		Load: function (tb, key, val, cond, dbtb, onloadfunc) {
			var vurl = false; //use to determine if a constom script is to load the textbox
			//Tracer.Tag(arguments.length);
			if (arguments.length <= 3) {
				//key represent the url
				vurl = true;
				onloadfunc = val; //the third argument represent the onload function
				//Tracer.Tag("Url Textbox Loading: "+key);
			}
			if (typeof onloadfunc == "undefined") { //if the onloadfunc is not set use the default func
				onloadfunc = 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
					/*var sss = obj.innerHTML.Replace(tbid,"textin");
						_("txtbxxx").innerHTML = sss;*/

					var tb = _(tbid);
					//console.log(tb);

					if (IsNull(tb)) return;

					//alert(TextBox.ChainSelect[tbid]);//perform the onchange functio
					/*var onchange = _(textbid + "_onch").value.Trim();
						if(onchange != "")eval(onchange + "(_('"+textbid+"'))");
					}*/
					//get the textbox selection hidden input element
					//var hidelm = _(tbid + "_inpVal");

					var hidelm = tb.Data("value");
					if (!Null(hidelm)) {
						//Tracer.Tag(tbid + ": Sellected hidden value cleared, due to dropdown reload");
						hidelm.value = "";
					}
					//get the textbox table
					var txtbxtb = tb.GetDropDownTable();

					//alert(txtbxtb)
					//alert(txtbxtb);
					//check if no table exist, run it unchange event and clear it text
					if (Null(txtbxtb)) {
						//Tracer.Tag("No Dropdown found for Textbox: "+tbid);
						tb.ClearTextOnly();
						tb.RunOnChange();
						return;
					}

					//console.log(TextBox.ChainSelect[tbid]);

					if (typeof TextBox.ChainSelect[tbid] != "undefined") { //if the textbox id is set (for chain selection)
						if (TextBox.ChainSelect[tbid].Trim() != "") { //if an id set

							tb.SelectText(TextBox.ChainSelect[tbid].Trim()); //select the id
							// Tracer.Tag("Chain Selection: id " + TextBox.ChainSelect[tbid].Trim() + "Selected in " + tb.id);
							TextBox.ChainSelect[tbid] = ""; //reset the textbox chain id to empty
						} else { //if textbox chain id is empty

							var firstcell = _(tbid + "tb_rw_1"); //get the first option(cell) of the dropdown

							// var lstsell = _(tbid+"tb").Selected();
							// Tracer.Tag("Last Sellection: ");
							if (!IsNull(firstcell)) { //if exist
								//if(firstcell != lstsell){
								//var currsel = (Null(lstsell))?"none":lstsell.id;
								// Tracer.Tag("First Element found to Select: "+tbid+"tb_rw_1, Text: "+_(tbid+"tb_rw_1").Text());
								firstcell.click(); //click it to select it
								/* }else{
								   alert("selected");   
								 }*/
							} else {
								// Tracer.Tag("No First Dropdown Element found: " + tbid+"tb_rw_1");
								//_(tbid).SetText(""); //reset the text content to empty, because a new set of option is loaded  
							}
						}

					} else { //if cell does not exist
						//console.log(txtbxtb.rows.length);

						//Table.Select(this,false,TextBox.Select,TextBox.UnSelect)
						if (txtbxtb.rows.length == 1) { //if just one record in drop down select it
							//get the row
							Table.Select(txtbxtb.rows[0], false, TextBox.Select, TextBox.UnSelect)
						} else {
							_(tbid).ClearText(); //reset the text content to empty, because a new set of option is loaded 
							//_(tbid).Data("Value",""); //reset the curre
						}
						//Tracer.Tag(tbid+" not register");

					}
					//alert(tb.id);
					tb.HideLoading();
				}
			}
			tb = _(tb);
			if (IsNull(tb)) return;
			var tbid = tb.id;
			var drpdwn = _(tbid + "_drpd");
			if (IsNull(drpdwn)) return;
			//check if in silent mode
			var silent = tb.Data("silent");
			if (silent == "true" || silent == "1") {
				cond += " LIMIT 1";
			} else {
				cond += " ORDER BY " + val;
			}
			//_POST['tbid']) && isset($_POST['key']) && isset($_POST['value']) && isset($_POST['cond'])  && isset($_POST['table'])){
			tb.ShowLoading();
			//alert(TaquaLoader.lb);
			if (!vurl) {
				var src = configdata.Core + "general/TaquaLB/Elements/Script/loadtextbox.php?tbid=" + escape(tbid) + "&key=" + escape(key) + "&value=" + escape(val) + "&cond=" + escape(cond) + "&table=" + escape(dbtb) + "&def=" + escape(tb.Data("default")) + "&SubDir=" + encodeURIComponent(configdata.SubDir);
				/*if(dbtb == "course_tb"){
					alert(src);
				}*/
			} else {

				var src = key + "&tbid=" + escape(tbid) + "&def=" + escape(tb.Data("default")) + "&SubDir=" + encodeURIComponent(configdata.SubDir);
			}
			//Cleartb
			tb.ClearText();
			//alert(src);
			drpdwn.HTML(src, onloadfunc, function () { });
		},
		//Common TextboxLoad
		Template: {
			//*Student.BioData.LoadLGA *BioData.LoadLGA
			LoadLGA: function (obj) { //function to load department textbox based on selected faculty
				//Tracer.Start();
				//obj.id.__();
				var stateID = _(obj.id).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(obj.id + "lga", "LGAID", "UPPER(LGAName)", "StateID = " + stateID, "lga_tb"); //Load:function(tb,key, val, cond, dbtb)
				//Tracer.End();
			}
		},
		//function to get the drop down table
		_GetDropDownTable: function (tb) {
			tb = _(tb);
			if (Null(tb)) return null;
			var tbid = tb.id;
			var drpdwntable = _(tbid + "tb");
			if (Null(drpdwntable)) return null;
			return drpdwntable;
		},
		//function to check for dropdown
		_HasDropDown: function (tb) {
			if (Null(tb)) return false;
			return (TextBox._GetDropDownTable(tb) == null) ? false : true;
		},//function to indicate loading
		_Loading: function (tb) {
			tb = _(tb);
			if (Null(tb)) return null;
			var tbid = tb.id;
			var loadinlogo = _(tbid + "_loading");
			loadinlogo.Show();
		}
		,//function to indicate loading
		_StopLoading: function (tb) {
			tb = _(tb);
			if (Null(tb)) return null;
			var tbid = tb.id;
			var loadinlogo = _(tbid + "_loading");
			loadinlogo.Hide();
		}
	}
}();
Object.prototype.ShowLoading = function () { TextBox._Loading(this) };
Object.prototype.HideLoading = function () { TextBox._StopLoading(this) };
Object.prototype.GetDropDownTable = function () { return TextBox._GetDropDownTable(this) }
Object.prototype.TextContent = function () {
	if (this.ClassIs("textBx")) {//if a textbox
		if (this.HasDropDown()) {//if has dropdown menu
			return TextBox.GetValue(this); //get value
		} else {
			return TextBox.GetText(this); //perform set
		}
	} else {
		return TextPad._PadText(this); //if is textpad set the text
	}
}
Object.prototype.TextDisplay = function () { return TextBox.GetText(this); }
Object.prototype.RunOnChange = function () {
	//textB.Data("chain")
	//var onchange = _(this.id + "_onch").value.Trim();
	var onchange = this.Data("onchange").Trim();
	if (onchange != "") setTimeout(onchange + "(_('" + this.id + "'))", 1);
}
Object.prototype.ValueContent = function () { return TextBox.GetValue(this) }
Object.prototype.TextDisable = function () { TextBox._TextDisable(this) }
Object.prototype.TextEnable = function () { TextBox._TextEnable(this) }
Object.prototype.TextFocus = function () { TextBox._TextFocus(this) }
Object.prototype.ClearText = function () { return TextBox._ClearText(this) }
Array.prototype.ClearText = function () { return TextBox._ClearText(this) }
Object.prototype.ClearTextOnly = function () { return TextBox._ClearText(this, true) }
Object.prototype.HasDropDown = function () { return TextBox._HasDropDown(this) }
Object.prototype.SetText = function (txt, chain) {
	if (this.ClassIs("textBx")) {//if a textbox
		if (this.HasDropDown()) {//if has dropdown menu
			TextBox._SelectText(this, txt, chain); //perform select
		} else {
			return TextBox._SetText(this, txt); //perform set
		}
	} else {
		TextPad._SetPadText(this, txt); //if is textpad set the text
	}
}
Object.prototype.SelectText = function (id, chian) { return TextBox._SelectText(this, id, chian) }
Object.prototype.SetDate = function (datestr) { return TextBox._SetDate(this, datestr) }
Object.prototype.ClearTextAll = function () {
	var drpdwn = _(this.id + "_drpd");
	if (drpdwn != null) {
		drpdwn.innerHTML = "";
	}
	this.ClearText();
}

var TextPad = function () {
	return {
		_PadText: function (pad) {// function to get the pad text
			pad = _(pad); //make sure the pad object is gotten
			if (IsNull(pad)) return ""; //if not exist return
			var padid = pad.id; // get id
			var textar = _(padid + "_pad"); //get the pad textarea
			if (IsNull(textar)) return ""; //if not exist return
			return textar.Text();
		},
		_SetPadText: function (pad, txt) {
			pad = _(pad); //make sure the pad object is gotten
			if (IsNull(pad)) return; //if not exist return
			var padid = pad.id; // get id
			var textar = _(padid + "_pad"); //get the pad textarea
			if (IsNull(textar)) return; //if not exist return
			textar.Text(txt);
			//return true;
		},
		_ClearPad: function (pad) {
			if (IsArray(pad)) {
				for (var p = 0, lenp = pad.length; p < lenp; p++) {
					var curpad = pad[p];
					curpad.SetText("");
				}
			} else {
				pad.SetText("");
			}
			//return true;
		}
	}
}();
Object.prototype.PadText = function () { return TextPad._PadText(this) }
Object.prototype.ClearPad = function () { return TextPad._ClearPad(this) }
Array.prototype.ClearPad = function () { return TextPad._ClearPad(this) }

var ImageBox = function () {
	return {
		_Image: function (img) {// function to get the image box
			img = _(img); //make sure the image object is gotten
			if (IsNull(img)) return ""; //if not exist return
			var imgid = img.id; // get id
			var imgobj = _(imgid + "_img"); //get the image obj
			if (IsNull(imgobj)) return ""; //if not exist return
			return imgobj.src;
		},
		_SetImage: function (img, src, onload, onerror) {
			img = _(img); //make sure the image object is gotten
			if (IsNull(img)) return true; //if not exist return
			var imgid = img.id; // get id

			var imgobj = _(imgid + "_img"); //get the image obj

			//alert(imgobj);
			if (IsNull(imgobj)) return true; //if not exist return
			if (typeof onload != _UND) { imgobj.onload = onload }
			if (typeof onerror != _UND) { imgobj.onerror = onerror }
			imgobj.src = "gg"
			imgobj.lowsrc = "../general/TaquaLB/Elements/Images/loadingbtn2.gif";
			imgobj.src = src;
			return true;
		}
	}
}();
Object.prototype.GetImage = function () { return ImageBox._Image(this) }
Object.prototype.SetImage = function (src, onload, onerror) { return ImageBox._SetImage(this, src, onload, onerror) }

var Filer = {
	_BrowseFile: function (target, onload, onchange, maxSize, ftype) {
		onload = onload || function () { };
		maxSize = maxSize || 60000000;
		onchange = onchange || function () { };
		ftype = ftype || "*.*";
		if (target == null || !IsObject(target)) {
			MessageBox.Show("No Target Found");
			return;
		}
		//check if object id exist
		if (typeof target.id == _UND || target.id.Trim() == "") {
			var dt = new Date();
			target.id = "filer_" + dt.getTime() + "_" + (Math.random() * 100000);
		}

		target.SetFromFile({ "onload": onload, "maxSize": maxSize, "onchange": onchange, "onerror": function (err) { MessageBox.Show("#" + err) }, type: ftype });

	},
	_GetFileElement: function (target) {
		//get the file object
		return _(target.id + "_file");
	},

	_GetFileData: function (target) {
		//get the file object
		var elem = _(target.id + "_file");
		if (elem == null) return "";
		return target.id + "_file=?"
	}
}
Object.prototype.BrowseFile = function (onload, onchange, maxSize, ftype) {
	onload = onload || function () { };
	maxSize = maxSize || 60000000;
	ftype = ftype || "*.*";
	onchange = onchange || function () { };
	Filer._BrowseFile(this, onload, onchange, maxSize, ftype);
}

Object.prototype.FileDataString = function () { return Filer._GetFileData(this) }
var ImagePad = {
	_ShowLoading: function (IPad) {
		var padId = IPad.id;
		_(padId + "_load").classList.remove("off");
	},
	_HideLoading: function (IPad) {
		var padId = IPad.id;
		if (!_(padId + "_load").classList.contains("off")) {
			_(padId + "_load").classList.add("off");
		}
	},
	_SetImage: function (IPad, src) {
		var padId = IPad.id;
		var fileobj = _(padId + "_image_file");
		if (fileobj != null) {
			fileobj.value = '';
			if (fileobj.value) {
				fileobj.type = "text";
				fileobj.type = "file";
			}

		}
		var PadImg = _(padId + "_image");
		if (PadImg != null) {
			IPad.StartPadLoading();
			PadImg.onload = ImagePad._AutoFit;
			//alert(src);
			var rnd = new Date();
			PadImg.src = src + "?" + rnd.getTime();
		}
	},
	_SetImageFromFile: function (IPad, maxSize) {
		maxSize = typeof maxSize == _UND ? 0 : maxSize;
		//alert(maxSize);
		var padId = IPad.id;
		var PadImg = _(padId + "_image");
		if (PadImg != null) {

			PadImg.SetFromFile({ "onload": ImagePad._AutoFit, "maxSize": maxSize, "onchange": ImagePad._onchange, "onerror": function (err) { MessageBox.Show("#" + err) } });

		}
	},
	_onchange: function (img) {
		var imgid = img.id;
		var padId = imgid.split("_")[0];
		var pad = _(padId);
		if (pad != null) {
			pad.StartPadLoading();
		}
	}
	,
	_Clear: function (IPad) {
		var fileobj = _(IPad.id + "_image_file");
		var img = _(IPad.id + "_image");
		//alert(fileobj);
		if (fileobj != null) {
			fileobj.value = '';
			if (fileobj.value) {
				fileobj.type = "text";
				fileobj.type = "file";
			}

		}
		img.onload = ImagePad._AutoFit;
		img.src = IPad.Data("default");
	},
	_File: function (IPad) {
		var fileobj = _(IPad.id + "_image_file");

		if (fileobj == null) return null;
		var file = fileobj.files[0];
		//alert(file);
		if (typeof file == _UND) return null;
		file.PostData = IPad.id + "_image_file=?"
		return file;
	},
	_AutoFit: function () {
		var img = this;
		//alert(img);return;
		var Pad = _(img.id.split("_")[0]);
		//alert(Pad.File().Postdata);
		// alert(Pad.Data('width'));
		var $padW = Pad.Data('width').ToNumber() - 12 - 30;

		var $padH = Pad.Data('height').ToNumber() - 12 - 50;

		var $width = img.naturalWidth.ToNumber();
		var $height = img.naturalHeight.ToNumber();
		//get autofit width and height
		var newdem = AutoFit($padW, $padH, $width, $height, 10);
		$width = newdem[0]; $height = newdem[1];
		//alert(img.width); 
		//img.width = $width;
		img.Animate({ CSSRule: "width:" + $width + "px;height:" + $height + "px", Time: 150 });
		Pad.StopPadLoading();
		//alert(img.width);
		//img.height = $height;
	},
	_IsSet: function (obj) {
		//var PadFile = obj.GetPadFile();
		if (typeof obj == _UND) return false;
		var img = _(obj.id + "_image");
		if (img == null) return false;
		return (img.src.split("?")[0].Trim() == obj.Data("default").split("?")[0].Trim()) ? false : true;
	}
}
Object.prototype.IsSet = function () {
	return ImagePad._IsSet(this);
}
Object.prototype.SetPadImage = function (src) {
	if (typeof src == "string") {
		ImagePad._SetImage(this, src);
	} else {
		maxSize = (typeof src == _UND) ? 0 : src;
		ImagePad._SetImageFromFile(this, maxSize);
	}

}
Object.prototype.GetPadFile = function () { return ImagePad._File(this); }
Object.prototype.ClearImagePad = function () { ImagePad._Clear(this) }
Object.prototype.StartPadLoading = function () { ImagePad._ShowLoading(this) }
Object.prototype.StopPadLoading = function () { ImagePad._HideLoading(this) }
//Object.prototype.SetPadImage = function

var Page = {
	HideTaskBar: function () {
		var pagess = _('Pagescont');
		if (pagess != null) pagess.classList.remove('display')
		// if(pagess != null)pagess.Hide();

		//set the curpage to empty
		Page.CurrOpen = "";
		//deselect the curren explorer selected menu
		var selectedexplmenu = _('exsubitems & sel');
		if (selectedexplmenu != null) {
			selectedexplmenu.classList.remove('sel');
		}
		//hide the home menu button and display the workspace menu button
		_('genFender').classList.add("wstoolbox");
		//console.log(selectedexplmenu);
	},
	ShowTaskBar: function () {
		// _('Pagescont').Show();
		_('Pagescont').classList.add('display');
		//hide the workspace menu button and display the home menu button
		_('genFender').classList.remove("wstoolbox");
		//ToHome
	},
	OpenWorkSpace: function () {
		var ntabName = Page.LastTabName();
		//var samegrp = false;
		//alert(ntabName);
		if (ntabName != "") {
			Page.OpenByTabName(ntabName);

		} else {
			MessageBox.Show("Empty Workspace, use the Explorer to open a page on the Workspace");
		}
	},
	CurrOpen: "",
	Opened: [],
	TabOpened: '', //hold tab name as they are opened
	AddTabName: function (tabName) { //function to add tabname to opened tabname in order
		//remove tabname if exist and append
		Page.TabOpened = Page.TabOpened.replace(':' + tabName + ':', '');
		Page.TabOpened += ':' + tabName + ':';
		//console.log(Page.TabOpened);
	}, RemoveTabName: function (tabName) {
		Page.TabOpened = Page.TabOpened.replace(':' + tabName + ':', '');
		//console.log(Page.TabOpened);
	}, LastTabName: function () {
		if (Page.TabOpened.Trim() == "") return '';
		var trimed = Page.TabOpened.substr(1, Page.TabOpened.length - 2).split("::");
		//var trimed = Page.TabOpened.Trim(':').split("::");
		return trimed.length > 0 ? trimed[trimed.length - 1] : '';
	},
	HideAllFender: function () {
		var tR = _('toolboxR');
		if (tR != null) {
			tR.classList.remove('OpenExplorer'); tR.classList.remove('toolboxOpen'); tR.classList.remove('OpenSettings');
		}

		var tL = _('toolboxL');
		if (tL == null) return;
		if (IsArray(tL)) {
			tL.Walk(function (k, v) {
				v.classList.remove('toolboxOpen')

			})
		} else {
			tL.classList.remove('toolboxOpen')
		}

	},
	OpenByTabName: function (TabName, OpenExplorer) {
		OpenExplorer = OpenExplorer || false;
		//get the tab data
		var tabdata = _(TabName + "_data");
		if (_IsFound(tabdata)) {
			try {
				var dataobj = JSON.parse(tabdata.innerHTML);
				Page.Open(dataobj.Src, dataobj.ID, dataobj.GName, dataobj.TName, dataobj.TDisName)
				//console.log(dataobj);
				return;
			} catch (err) {

			}

		}
		if (typeof TabName == _UND || TabName.Trim() == "") {
			return;
		}
		//get the menu element

		//get tab index
		var tbindex = Tabs.GetTabIndexByTabName(TabName);
		var grname = Tabs.GetGroupByTabName(TabName);
		if (tbindex < 0 || grname == '') {
			var menuelem = _(TabName);
		} else {
			var menuelem = _(grname + "_" + tbindex);
		}
		//alert(TabName);
		//alert(TabName+"_"+tbindex);
		if (menuelem != null) {

			/* if(IsArray(menuelem)){
				for (var key in menuelem) {
					if (menuelem.hasOwnProperty(key)) {
						var element = menuelem[key];
						alert(element.outerHTML);
					}
				}
			} */
			menuelem = IsArray(menuelem) ? menuelem[0] : menuelem;

			Page.OpenByTabMenu(menuelem, OpenExplorer);


			//get the menu id
			/* mid = typeof menuelem.id != _UND?menuelem.id:"";
			if(mid != ""){//if menu id found
				 //get the pagename and index
				 midarr = mid.split("_");
				 if(midarr.length == 2){
					 Page.OpenByTabIndex(midarr[0],midarr[1].ToNumber());
				 }
			} */
		}
	},
	OpenByTabIndex: function (PageName, TabIndex, OpenExplorer) {
		OpenExplorer = OpenExplorer || false;
		TabIndex = TabIndex || 0;
		if (typeof PageName == _UND || PageName.Trim() == "") {
			return;
		}

		var pagemenubtn = _(PageName + "_" + TabIndex);
		Page.OpenByTabMenu(pagemenubtn, OpenExplorer);

	},
	OpenExplorer: false,
	OpenByTabMenu: function (pagemenubtn, OpenExplorer) {
		return new Promise((resolve, reject) => {
			OpenExplorer = OpenExplorer || false;
			//get the open page data
			//console.log()

			if (pagemenubtn != null && pagemenubtn.classList.contains('menuind')) {
				menuidarr = pagemenubtn.id.split("_");

				if (menuidarr[0] == Page.CurrOpen) { //if currently opened
					//click the tab
					var tabb = _(menuidarr[0] + "tab_tb_" + menuidarr[1]); //Studenttab_tb_3
					if (tabb != null) {
						Tabs.Select(tabb);
						// tabb.click();
						return;
					}
				}
				Page.OpenExplorer = OpenExplorer;
				//console.log(pagemenubtn);
				pagemenubtn.click();
			}
		})
	},
	Details: [],
	Reload: function () {
		if (typeof Page.Details[Page.CurrOpen] != _UND) {
			var det = Page.Details[Page.CurrOpen];
			var tabIndex = det[1];
			var tabName = det[3];
			var tabdisName = det[4];
			if (typeof Page.Opened[Page.CurrOpen] != _UND) {
				var curpagedet = Page.Opened[Page.CurrOpen];
				// alert(curpagedet);
				var curpagedetarr = curpagedet.split(";");
				//param["GRPNAME"]+ ";" + param["TABIND"] + ";" + param["TABNAME"]
				tabIndex = curpagedetarr[1];
				tabName = curpagedetarr[2];
				tabdisName = curpagedetarr[3];
			}
			//alert(JSON.stringify([det[0],tabIndex,det[2],tabName,tabdisName]));
			Page.Open(det[0], tabIndex, det[2], tabName, tabdisName, true);
		} else {
			MessageBox.Show("No Active Page Found")
		}
	},
	Open: function (src, tabIndex, gruopName, tabName, tabDisName, reopen) {
		var OpenE = Page.OpenExplorer = false;
		reopen = typeof reopen == _UND ? false : reopen;
		/*var tabs = _(gruopName + "_tabs").value;
		alert(escape(tabs));
		return;*/
		//return; 
		//__("#Opening Page");
		//alert(tabDisName);
		if (src.Trim() == "") {
			MessageBox.Show("Not Available");
			return;
		}
		//check priv
		var userdet = Cookie.Get("UserDet");
		if (userdet.Trim() == "") { MessageBox.Show("User Identification Failed: Logout and Re-Login"); return; }
		var userdetarr = userdet.split("~");
		if (userdetarr.length < 3) { MessageBox.Show("Inavlid User: Logout and Re-Login"); return; }
		var priv = userdetarr[6].Trim();
		if (priv == "") { MessageBox.Show("User Privileges Identification Failed: Logout and Re-Login"); return; }
		var privarr = priv.split(":");
		var exist = privarr.InArray(tabName);
		if (!exist.Exist) { MessageBox.Show("#Access Denied <br /> Browser-Reload the system and Try Again"); return; }
		//make groupname to be the id of the page
		id = gruopName;
		var logo = _(gruopName + "logo") == null ? "" : _(gruopName + "logo").value;
		if (id == null || typeof id == "undefined") {
			//var dt = new Date();
			id = "Page" + Page.Opened.length + 1;
			gruopName = id;

		}
		//__("Group Name/ Page ID is " + gruopName);
		if (tabIndex == null || typeof tabIndex == "undefined") {
			tabIndex = 0;
		}
		//__("Tab Index to open is " + tabIndex);
		/*if(gruopName == null || typeof gruopName == "undefined"){
			gruopName = "Page";
		}*/
		if (tabName == null || typeof tabName == "undefined") {
			//__("TabName set to GroupName due to no TabName sent");
			tabName = gruopName;
		}

		//__("TabName is " + tabName);

		//__("Checking if Page not Opend Before");
		if (Page.Opened[id] == null || typeof Page.Opened[id] == "undefined" || reopen == true) { //if not opened befor
			//__("Page Not Opened");
			var loadtxt = reopen ? "Reloading" : "Loading";

			CoverScreen.ShowLoading('menuload' + id, loadtxt + ' ' + gruopName + ' ' + 'angle-double-right'.Icon() + ' ' + tabDisName, "Page.Close('" + id + "')"); //diaplay the loading anim
			//return;

			if (!reopen) {
				var pg = document.createElement("div");
				pg.id = id;
				pg.className = "pgmain";
				pg.style.cssText = "z-index: 4";
				pg.onclick = Pages.HideGroupTabs;
				document.body.style.overflow = "hidden";
				//pg.style.display = "none";
				document.body.appendChild(pg);
			} else {
				var pg = _(id);
				if (pg == null) {
					if (Page.Close(id)) {
						//__("TRUE");
						//alert('e');
						//__("ReOpen it");
						Page.OpenExplorer = OpenE;
						Page.Open(src, tabIndex, gruopName, tabName, tabDisName);
					}
					return;

				}
			}

			//keep in page details
			Page.Details[id] = [src, tabIndex, gruopName, tabName, tabDisName]

			//__("Created a new page with ID: "+pg.id);
			//pg.innerHTML = '<div class="bgloading" ><span class="fa-stack fa-lg"><i class="fa fa-circle-o-notch fa-spin fa-stack-2x"></i><i class="fa fa-close fa-stack-1x"  onclick="Page.Close(\''+id+'\')" title="Close" ></i></span></div>';
			//__("Get the tabs present for the page, by accessin the tabs hidden input value for the group Id: " + gruopName + "_tabs");<div onclick="Page.Close(\''+id+'\')" class="pageclose" title="Close" ></div>
			var tabs = _(gruopName + "_tabs").value;
			/*alert(escape(tabs));
			return*/
			/*tabs = tabs.Replace("=","~");
			tabs = tabs.Replace("&","`");*/
			//__("Forming the url of the page");
			//console.log(configdata);
			var ope = OpenE ? 1 : 0;
			var data = "PGID=" + id + "&PGURL=" + escape(src) + "&TABIND=" + tabIndex + "&GRPNAME=" + gruopName + "&TABNAME=" + tabName + "&TABDISNAME=" + escape(tabDisName) + "&TABS=" + escape(tabs) + "&LOGO=" + escape(logo) + "&USER=" + escape(Login.CurrentUserDet) + "&EXPLORER=" + ope + "&CORE=" + encodeURIComponent(configdata['Core']) + "&SUBDIR=" + encodeURIComponent(configdata['SubDir']);
			//src = src;

			//__("Page URL String is " + src);
			//send the page id to page load script in server
			//alert(src);
			//__("Loading Page");
			(new Promise((resolve, reject) => {
				(new Ajax).Post({
					Action: src,
					Data: data,
					OnComplete: (res, url, param) => {

						//var det = Login.CurrentUserDet;
						var detarr = Login.CurrentUserDet.split("~");
						var userID = detarr[0];

						var passpurl = configdata['Core'] + "cportal/Files/UserImages/" + userID + ".jpg";
						//__("get the Login UserID to form the passport url: " + passpurl);
						//var dt = new Date();

						//alert(_(param["PGID"] + "_userloginboximg"));
						/* _(param["PGID"] + "_userloginboximg").src = passpurl+'?'+dt.getTime();
						_(param["PGID"] + "_userloginboximg").lowsrc = "TaquaLB/Elements/Images/loadingbtn2.gif";
						_(param["PGID"] + "_userloginbox").title = detarr[2];
						_(param["PGID"] + "_userloginboximgn").textContent = detarr[2].split(" ")[0]; */
						/* _("All_userloginboximg").src = passpurl+'?'+dt.getTime();
						_("All_userloginboximg").lowsrc = "TaquaLB/Elements/Images/loadingbtn2.gif";
						_("All_userloginbox").title = detarr[2];
						_("All_userloginboximgn").textContent = detarr[2].split(" ")[0]; */
						//minimize other opend pages
						Page.MinimizeAll();
						//__("User Passport and Title Set");
						Page.CurrOpen = pg.id;
						//__("Set the current Page to the Loaded page ID: " + Page.CurrOpen);

						var pagdet = param["GRPNAME"] + ";" + param["TABIND"] + ";" + param["TABNAME"] + ";" + param["TABDISNAME"];
						//__("Form the page details joined with ; and set it as the opened page id for the global opened page array =>" + pagdet);
						Page.Opened[pg.id] = pagdet; //the group name will be use to load the menu group in the pages 

						setTimeout(() => { Pages.Add(param["TABNAME"], param["TABIND"], param["GRPNAME"]) });
						pg.innerHTML = res;
						//__("Page opened tab added to pages opened element by running : Pages.Add("+param["TABNAME"]+","+param["TABIND"]+","+param["GRPNAME"]+") ")
						//__("Page Loaded Successfully");
						//__();

						var initscript = _(param["GRPNAME"] + "_autorun");
						//alert(initscript);
						if (initscript != null) {
							var scri = initscript.textContent.Trim();
							if (scri != "") {

								//eval(scri);
								setTimeout(scri, 1);
							}
						}
						// obj.style.display = "block";


						//console.log(obj)
						//display the right fender
						_('genFender').Show();

						//select the menu in the explorer
						//Get the explorer menu first
						var menuinexplorer = _('explorersubmenu_' + param["TABNAME"]);
						if (menuinexplorer != null) Fender.SelectSub(menuinexplorer); //Fender Object is in main.js
						resolve(res);
					}
				});
			})).then(res => {

				pg.classList.add('display');
				CoverScreen.Close(_('menuload' + id));
			}).catch(err => {
				MessageBox.Show("#Cannot Load Page: " + err);
				CoverScreen.Close(_('menuload' + id));
			});
			/* pg.HTML(src,function(obj,url,param){
				//__("Page Loaded");
			//this code is temporary option to access user deteals from the main  page
			
			
			///////////////////////////////////////////////// 
				},function(res,url,param){MessageBox.Show("#Cannot Load Page: "+res);CoverScreen.Close(_('menuload'+param["PGID"]));});*/


		} else {// if currently opened
			//__("Page Currently Opened");
			var openedpages = _("Pagescont");
			var pagesOpened = false;
			//__("Check if opened pages");
			if (openedpages != null) {
				// if(openedpages.style.visibility == "visible"){
				if (openedpages.classList.contains('display')) {
					//__("Open page exist");
					pagesOpened = true;
				}
			}
			//__("check if not currently opened i.e minimized or the opened pages window is opened");
			if (Page.CurrOpen != id || pagesOpened == true) { //
				/*if(Page.CurrOpen != id){
				//minimise current and open new
				Page.Minimize(Page.CurrOpen);
				}*/
				//__("True");
				//console.log('Before Maximize')
				setTimeout(() => {
					Page.Maximize(id, tabIndex, tabName, tabDisName);
					//console.log('Before Add')
					Pages.Add(tabName, tabIndex, gruopName);
				}, 1)

				//console.log('After Add')
				//__("Mazimize the page and add its currently opened tab to pages element : TN="+tabName+" TI="+tabIndex+" GN="+gruopName);
			} else { //if not minimize
				//__("FALSE");
				//__("Reload The page");
				//reload it
				//__("Check if closed successfully");
				if (Page.Close(id)) {
					//__("TRUE");
					//alert('e');
					//__("ReOpen it");
					setTimeout(() => { Page.Open(src, tabIndex, gruopName, tabName, tabDisName); }, 1);
				}
			}
			//select the menu in the explorer
			//Get the explorer menu first
			//var menuinexplorer = _('explorersubmenu_'+tabName);
			//if(menuinexplorer != null)Fender.SelectSub(menuinexplorer); //Fender object is in main.js

		}
		document.body.onmousemove = Lock.AutoLock;
		document.body.onkeydown = Lock.AutoLock;
		//return true;

	},

	Close: function (id) {
		//__("Clossing the page with id: "+id);
		id = (id == null || typeof id == "undefined") ? Page.CurrOpen : id;
		var pg = _(id);
		if (pg == null) return;
		//alert(Page.Opened[id]);
		//__("Removing Page");
		//perform minimize animation
		pg.parentElement.removeChild(pg);
		//__("Page Removed");


		//__("Reset the current opened variable to empty if it is the currently opend page");
		if (Page.CurrOpen == id) Page.CurrOpen = "";
		document.body.style.overflow = "auto";
		document.body.onmousemove = null;
		//__("Set the body overflow to auto, display the scroll bar and set the onmousemove to null");
		//__("get the page Details: "+det);
		if (typeof Page.Opened[id] != _UND) {
			var det = Page.Opened[id];
			//__("Page Details deleted from Opened Array");
			Page.Opened[id] = null;
			delete Page.Opened[id];

			var detarr = det.split(";");
			//__("Reform the page det to suit Pages.Remove function string : "+ detarr[2]+"_"+detarr[1]+"_"+detarr[0]);
			Pages.Remove(detarr[2] + "_" + detarr[1] + "_" + detarr[0]);
		}
		//__("Closing Completed");
		return true;
	},

	Minimize: function (id) {

		if (id == null || typeof id == "undefined") {
			id = Page.CurrOpen
		}
		if (typeof id == "string" && id.Trim() == "") return;
		var pg = _(id);
		if (pg == null) return;
		// pg.Animate({CSSRule:"opacity:0;visibility:hidden;z-index:1;display:none",Time:200});
		pg.classList.remove('display');
		if (Page.CurrOpen == id) Page.CurrOpen = ""; //if current opened page is the minimized page
		document.body.style.overflow = "auto";
		//alert(tabIndex);

		//return true;
	},

	MinimizeAll: function (pgclass) {
		/* pgclass = typeof pgclass == _UND?'pgmain':pgclass;
	 var allpg = _(pgclass);
	if(allpg != null){
	 allpg = IsArray(allpg)?allpg:[allpg];
	for(var ap=0, len =allpg.length; ap<len; ap++){
	 Page.Minimize(allpg[ap]);
	}
	} */

		//return true;
		var openedpag = document.querySelectorAll(".pgmain.display");
		//console.log(openedpag.length);
		if (openedpag.length > 0) {
			openedpag.forEach(mpg => {
				// mpg.classList.add("hide");
				window.setTimeout(
					() => {
						Page.Minimize(mpg);
					}, 1
				);
			})
		}
	},
	Remove: function (tabName) {
		tabName = typeof tabName == _UND ? Page.LastTabName() : tabName;
		//get tabindex
		var tabIndex = Tabs.GetTabIndexByTabName(tabName);
		var grpName = Tabs.GetGroupByTabName(tabName);
		/* var tabName = idarr[0];
			 var tabIndex = idarr[1];
			 var groupName = idarr[2]; */
		if (tabIndex < 0 || grpName == '') {
			MessageBox.Show("Internal Error, Cannot close current Page");
			return;
		}
		//use pages.Remove
		Pages.Remove(tabName + "_" + tabIndex + "_" + grpName);

		//alert(Page.LastTabName());
	},

	Maximize: function (id, tabIndex, tabName, tabDisName) {
		return new Promise((resolve, reject) => {
			if (id == null || typeof id == "undefined") return;
			var pg = _(id);
			if (pg == null) return;
			//console.log(pg);
			if (Page.CurrOpen != id) {
				/* var openedpag = _('pgmain ~ '+pg.id);
				if(openedpag != null){
					openedpag = IsArray(openedpag)?openedpag:[openedpag];
					for(var dd=0;dd<openedpag.length;dd++){
						Page.Minimize(openedpag[dd]);
					}
				  
				} */
				var openedpag = document.querySelectorAll(".pgmain.display");

				if (openedpag.length > 0) {
					openedpag.forEach(mpg => {
						// mpg.classList.add("hide");
						window.setTimeout(
							() => {
								Page.Minimize(mpg);
							}, 1
						);
					})
				}



				// pg.Animate({CSSRule:"opacity:1;visibility:visible ;z-index:3;display:block",Time:200});
				pg.classList.add("display");
				Page.CurrOpen = id;
				document.body.style.overflow = "hidden";

				//alert(tabIndex);

			}
			if (tabIndex != null || typeof tabIndex != "undefined") { //if new tabindex sent
				/*var det = Page.Opened[id]; //get the page group name and selected tabindex
				var detarr = det.split(";");
				var tabind = detarr[1]; //get the initial
				if(tabind.ToNumber() != tabIndex.ToNumber()){*/
				var det = Page.Opened[id];
				var detarr = det.split(";");
				//var tabind = detarr[1]; //get the initial
				//alert(_(id + "tab_tb_" + tabIndex));
				// _(id + "tab_tb_" + tabIndex).click();
				var objd = _(id + "tab_tb_" + tabIndex);
				Tabs.Select(objd);
				//console.log(objd);
				//alert(tabName);
				Page.Opened[id] = detarr[0] + ";" + tabIndex + ";" + tabName + ";" + tabDisName;
				//Pages.Add(tabName,tabIndex);
				//}
			}
			resolve('done');
		})

		//return true;
	},
	//function to validate textbox elements/data in a particular form 
	ValidateText: function (formname) {
		//if()
		var reqired = _("textBx & " + formname + " & req err"); //get 
		return reqired == null ? true : false;
	}

	,//function to form the data string of fields in a particlar tabbody of all element of a specific foemgroup
	DataString: function (groupname, returnArray) {
		var dstr = "";
		var darr = {};
		returnArray = returnArray || 0;
		var grpelem = _(groupname);
		if (!Null(grpelem)) {
			if (IsArray(grpelem)) {
				for (var l = 0, lenl = grpelem.length; l < lenl; l++) {
					var elem = grpelem[l];
					if (Null(elem)) {
						continue;
					}
					var elemID = elem.id;
					//alert(elemID);
					if (elemID.Trim() != "") {
						elemID = elemID.Replace(".", "_");
						if (elem.classList.contains("switchbox")) {
							var statusobj = _("st_" + elemID);
							var status = statusobj != null ? statusobj.value : 0;
							dstr += elemID + "=" + escape(status) + "&";
							darr[elemID] = status;
						} else if (elem.classList.contains("imagepad")) {
							var PadFile = elem.GetPadFile();
							if (PadFile != null) {
								dstr += elemID + "_image_file" + "=" + escape("?") + "&";
								darr[elemID + "_image_file"] = "?";
							}
						} else if (elem.classList.contains("ranges")) {
							var vall = elem.RangeValue();
							dstr += elemID + "=" + vall + "&";
							darr[elemID] = vall;
						} else if (elem.classList.contains("textBx")) {
							var vall = elem.TextContent();
							dstr += elemID + "=" + escape(vall) + "&";
							darr[elemID] = vall;
						} else {
							var vall = elem.Text();
							dstr += elemID + "=" + escape(vall) + "&";
							darr[elemID] = vall;
						}

					}
				}
			} else {//if group element is not an array
				var elemID = grpelem.id;
				if (elemID.Trim() != "") {
					var vall = grpelem.TextContent();
					dstr += elemID + "=" + escape(vall) + "&";
					darr[elemID] = vall;
				}
			}
		}
		if (returnArray == 1) {
			return darr;
		} else if (returnArray == 2) {
			return { "Array": darr, "String": dstr.TrimRight("&") };
		} else {
			return dstr.TrimRight("&");
		}

	},
	DataArray: function (groupname) {
		return Page.DataString(groupname, 1);
	}
	,
	DataStringArray: function (groupname) {
		return Page.DataString(groupname, 2);
	}

}

Object.prototype.PageTab = function () { return _(this.id + "tab") }
Object.prototype.PageSelectedIndex = function () { return this.PageTab().SelectedIndex(); }

/*Flat Button*/
var FlatButton = function () {
	return {
		StartLoading: function (obj, loadtxt) {
			if (typeof loadtxt != _UND) {
				_(obj.id + "_fbtntxt").textContent = loadtxt;
			}
			obj.classList.add("loading");
			//obj.className += " loading";
		},
		StopLoading: function (obj) {
			//obj.className = "flatbtn";
			obj.classList.remove("loading");
			_(obj.id + "_fbtntxt").textContent = obj.Data("caption");
		},
		_IsLoading: function (obj) {
			if (obj.ClassIs("loading")) {
				return true;
			} else {
				return false;
			}
		},
		TextContent: function (obj, txt) {
			if (typeof txt == "undefined") {
				return _(obj.id + "_fbtntxt").textContent;
			}
			_(obj.id + "_fbtntxt").textContent = txt;
			return txt;
		}

	}

}();

Object.prototype.StartLoading = function (txt) { if (this.ClassIs("flatbtn")) { FlatButton.StartLoading(this, txt) } }
Object.prototype.StopLoading = function () { if (this.ClassIs("flatbtn")) { FlatButton.StopLoading(this) } }
Object.prototype.IsLoading = function () { if (this.ClassIs("flatbtn")) { return FlatButton._IsLoading(this) } }
Object.prototype.ButtonText = function (txt) { if (this.ClassIs("flatbtn")) { return FlatButton.TextContent(this, txt) } }
/*Menu Tool Items*/
var ToolBox = function () {
	return {
		NoFunc: function () {
			MessageBox.Show("Currently Not Available");
		}
	}
}();

/*Message Box*/
var MessageBox = function () {
	return {
		CurrOpen: "",
		Show: function (txt) {
			txt = txt + "";
			txt = txt.Trim();
			if (MessageBox.CurrOpen != "") {
				MessageBox.Close(MessageBox.CurrOpen);
			}
			var dt = new Date();
			var id = "msb_" + dt.getTime();
			var msb = document.createElement("div");
			msb.className = "messagebx gen-text-shadow card-2 fadeInDown animated faster";
			var symbol = txt.substr(0, 1);
			var icon = "info-circle normal".Icon();
			msb.className += " normal";
			if (symbol == "#") { //if error
				icon = "exclamation-triangle error".Icon();
				msb.className += " error";
				txt = txt.substr(1);
			} else if (symbol == "*") {
				icon = "check-circle ok".Icon();
				msb.className += " ok";
				txt = txt.substr(1);
			}
			msb.innerHTML = icon + "<span>" + txt + "</span><div style='clear:left'></div>";
			msb.id = id;
			document.body.appendChild(msb);
			msb.Animate({ CSSRule: "opacity:1", Time: 300, EndAction: "MessageBox.Wait('" + id + "')", DoAt: 1.0 });
		},

		Close: function (id) {
			var obj = _(id)
			if (obj != null && typeof obj == "object") {
				obj.className = obj.className.replace("fadeInDown", "fadeOutUp");
				setTimeout(() => {
					if (typeof obj != _UND && obj != null) {
						document.body.removeChild(obj);
						MessageBox.CurrOpen = '';
					}
				}, 400);
				/* obj.Animate({CSSRule:"opacity:0", Time:300,EndAction:"var obji=_('"+id+"');if(obji != null){document.body.removeChild(_('"+id+"'));}MessageBox.CurrOpen = ''",DoAt:1.0}); */
			}
		},

		Wait: function (id) {
			MessageBox.CurrOpen = id;
			setTimeout("MessageBox.Close('" + id + "')", 4000);
		}


	}
}();

/*Lock Screen*/
Lock = {
	KeyPress: function (obj) {
		if (Lock.Working == 1) return;
		numb = obj.textContent.ToNumber();
		Login.Unlock2(_("screen").SetText(_("screen").TextContent() + numb));
	},
	//*Lock.Pin.Retry *Pin.Retry
	Retry: function () {
		var retry = _("retryfield").textContent.ToNumber();
		var maxretry = _("maxretryfield").textContent.ToNumber();
		retry += 1;
		if (retry > maxretry) {
			Login.Logout();
			MessageBox.Show("Maximum Pin Retry Reached: System Logout");
		} else {
			_("retryfield").textContent = retry;
		}

	},
	KeyBack: function () {
		if (Lock.Working == 1) return;
		//_("screen").value = _("screen").value.substr(0,_("screen").value.length - 1);
		if (_("screen").TextContent() != "") {
			var curstr = _("screen").TextContent();
			_("screen").SetText(curstr.substr(0, curstr.length - 1));
			if (_("screen").TextContent() == "") {
				Lock.Retry();
			}
		}
	},
	KeyCancel: function () {
		if (Lock.Working == 1) return;
		if (_("screen").TextContent() != "") {
			_("screen").SetText("");
			Lock.Retry();
		}

	},
	Enter: function (func) {
		if (Lock.Working == 1) return;
		Lock.Loading();
		func(_("screen").value);
	},
	Working: 0,
	Loading: function () {
		Lock.Working = 1;
		_("enterbtn").className += " loading";
	},
	Done: function () {
		Lock.Working = 0;
		_("screen").Clear();
		_("enterbtn").className = "button";
	},
	Show: function () {
		//var dt = new Date();
		//loading anim from main.js
		//alert('show');
		if (Login.CurrentUserDet.Trim() == "") return;
		if (_("lockscreen") == null) {
			Loading.Display(function (obj) { obj.style.color = "#FFF" });
			document.body.onmousemove = null;
			var id = "lockscreen";
			var lockdiv = document.createElement("div");
			//msb.textContent = txt;
			lockdiv.id = id;
			document.body.appendChild(lockdiv);
			//cportal Login object in main.js
			var detarr = Login.CurrentUserDet.split("~"); //get the login user details
			var UID = detarr[0];
			lockdiv.HTML(configdata['Core'] + "cportal/Pages/Login/lockScreen.php?UID=" + UID + "&SubDir=" + encodeURIComponent(configdata['SubDir']), function () {
				var idleTime = _('idletime_h').value.ToNumber();
				Lock.IdleTime = idleTime * 1000; //set the idletime from hidden file set from server script
				//MessageBox.Show("Idle Time: "+Lock.IdleTime);
				Cookie.Set("ScreenLock", "1", 1000 * 60 * 60 * 24 * 364);
				Loading.Close(function (obj) { obj.style.color = "#666" });
			}, function () { Loading.Close(function (obj) { obj.style.color = "#666" }); Lock.Close() });
			lockdiv.Animate({ CSSRule: "opacity:1", Time: 1000 });

		}
	},
	Close: function () {
		var locks = _("lockscreen");
		if (locks != null && typeof locks == "object") {
			Cookie.Set("ScreenLock", "", -1000); //unset indicating lock screen is close, for refresh
			locks.Animate({ CSSRule: "opacity:0", Time: 600, EndAction: "document.body.removeChild(_('lockscreen'));document.body.onmousemove = Lock.AutoLock;Lock.AutoLock();", DoAt: 1.0 });
		}
	},
	CloseLogout: function () {
		var locks = _("lockscreen");
		if (locks != null && typeof locks == "object") {
			Cookie.Set("ScreenLock", "", -1000);
			locks.Animate({ CSSRule: "opacity:0", Time: 600, EndAction: "document.body.removeChild(_('lockscreen'));document.body.onmousemove = null;Lock.StopAutoLock();", DoAt: 1.0 });
		}
	},
	AutoLockTimmer: null,
	IdleTime: 5000, //idle time
	Status: 1,//the lock status
	MaxRetry: 8,
	LockAjax: new Ajax(),
	AutoLock: function () {
		/*if(typeof idlet != _UND){
			Lock.IdleTime = idlet;
		}*/
		//	alert(Lock.IdleTime);
		Lock.StopAutoLock();
		if (Lock.Status == 1) { //if screen lock is enabled
			// MessageBox.Show("perform lock");
			Lock.AutoLockTimmer = setTimeout("Lock.Show()", Lock.IdleTime); //every one minite
		} else {
			// MessageBox.Show("no perform lock");   
		}


	},
	StopAutoLock: function () {
		if (Lock.AutoLockTimmer != null) {
			clearTimeout(Lock.AutoLockTimmer);
			Lock.AutoLockTimmer = null;
		}
	}

}

/*Pages*/
var Pages = function () {
	return {//grptabmenus_Exams
		GetGroupTabName: function () {
			var grname = _('grname');
			if (grname != null) {
				return grname.textContent;
			}
			return '';
		},
		GetGroupTab: function () {
			//get the curent display group
			var grpname = Pages.GetGroupTabName();
			if (grpname == '') return null;
			//get the group tabs container
			var grptabcont = _('grptabmenus_' + grpname);
			if (grptabcont != null) {
				return grptabcont;
			}

			return null
		},
		ToggleGroupTabs: function () {
			var grptabcont = Pages.GetGroupTab();
			if (grptabcont != null) grptabcont.classList.toggle('active');
		}
		,
		HideGroupTabs: function () {
			var grptabcont = Pages.GetGroupTab();
			if (grptabcont != null) grptabcont.classList.remove('active');

		},
		ShowGroupTabs: function () {
			var grptabcont = Pages.GetGroupTab();
			if (grptabcont != null) grptabcont.classList.add('active');
		}, ShowGroupTabs2: function () {
			var grpname = Pages.GetGroupTabName();
			if (grpname == '') return;

			var focusinput = _(grpname + '_grptabmenus');
			//alert(focusinput)
			if (focusinput != null) focusinput.focus();
			//_grptabmenus
		},
		Create: function () {
			var pg = _("Pagescont");
			if (pg == null) { //if not exist
				var id = "Pagescont";
				var pgcont = document.createElement("div");
				//msb.textContent = txt;
				pgcont.id = id;
				//pgcont.onclick = Pages.HideGroupTabs;
				pgcont.innerHTML = `<button type="button" onclick="document.querySelector('.toolboxR.toolbox').classList.add('toolboxOpen')" class="menubtn-main showExplorer">
			<i class="mbri-menu showExplorer"></i>
		</button><div id="openmenutitle"><a class="gnamedis" onclick="Pages.ToggleGroupTabs()"><span id="grname">Student</span> <i class="fa fa-chevron-down"></i></a><div class="tnamedis" onclick="Pages.HideGroupTabs()"><img id="tabimg" src="'+configdata['Core']+'cportal/Files/MenuImages/mngcourse.png" /><span id="trname">Manage</span></div></div><div id="openmenubx" onclick="Pages.HideGroupTabs()"><div class="innerbxtb"></div></div><button type="button" onclick="document.querySelector('.toolboxL.toolbox').classList.add('toolboxOpen')" class="menubtn-main showExplorer">
		<i class="mbri-features showExplorer"></i>
	</button><div style="clear:both"></div>`;
				//pgcont.innerHTML = '<div id="pagescontclose" width="40" height="40" title="Close" onclick="Pages.Close()"  >'+"times".Icon()+'</div><div style="clear:both"></div><div class="indbox" style="background-color:#0E0C2C;color:#FFF" onclick="Pages.ToHome()"><img class="mlogo" title="Home" src="../epconfig/TaquaLB/Elements/Images/home.png" alt="Home" /><div class="title">Home</div></div>';
				document.body.appendChild(pgcont);
				return true;
			}
		},
		Show: function () {
			//create it
			Pages.Create();
			//   _("Pagescont").Animate({CSSRule:"opacity:1;visibility:visible",Time:400});
			_("Pagescont").classList.add('display');
		},
		Close: function () {
			_("Pagescont").classList.remove('display');
			//  _("Pagescont").Animate({CSSRule:"opacity:0;visibility:hidden",Time:300}); 
		},
		PagesObject: Array(),
		LastSelect: "", //hold the last selected item on the pages box
		colors: ["#3F8B25", "#AA4311", "#452F9F", "#8F922E"],
		Add: function (tabName, tabIndex, groupName) {
			Pages.Create();
			var tabText = Tabs.GetTabText(groupName, tabName);
			//alert(tabText + " ; " + groupName);
			//set the group name in the pages bars
			var grname = _('grname');
			if (typeof grname != null) grname.innerHTML = groupName;

			//set the tab image
			var tabimg = _('tabimg');
			if (typeof tabimg != null) tabimg.src = configdata['Core'] + 'cportal/Files/MenuImages/' + tabName.toLowerCase() + '.png';

			//set the tab name in the pages bars
			var trname = _('trname');
			if (typeof trname != null) trname.innerHTML = tabText;
			var id = tabName + "_" + tabIndex + "_" + groupName;
			if (typeof Pages.PagesObject[id] == "undefined" || Pages.PagesObject[id] == null) {
				var it = document.createElement("div");
				it.id = id;
				it.className = "indbox animate-marginleft";
				var rand = Math.floor(Math.random() * 5);
				var cc = Pages.colors[rand];
				it.title = groupName + " > " + tabText;
				//it.style.backgroundColor = "#FFF";
				//it.onclick = "_('"+pgid+"_"+tabIndex+"').click()";
				//  it.onclick = function(){alert('aaa')};
				it.innerHTML = '<div class="detcont" onclick= "Page.OpenByTabName(\'' + tabName + '\')"><img class="mlogo"  src="' + configdata['Core'] + 'cportal/Files/MenuImages/' + tabName.toLowerCase() + '.png" alt="' + tabText + '" /></div><div class="cnclbtn" id="' + id + '_close" onclick="Pages.Remove(\'' + id + '\')" >' + "times".Icon() + '</div>';

				//   it.innerHTML = '<div id="'+id+'_close" class="cnclbtn" title="Close" onclick="Pages.Remove(\''+id+'\')" > '+"times".Icon()+' </div><div class="detcont" onclick= "_(\''+groupName+'_'+tabIndex+'\').click();Pages.Close()"><img class="mlogo" title="'+tabText+'" src="Files/MenuImages/'+tabName.toLowerCase()+'.png" alt="'+tabText+'" /><div class="title">'+tabText+'</div></div>';
				_("innerbxtb").appendChild(it);
				it.scrollIntoView();
				Pages.PagesObject[id] = id;

			}
			/*if(Pages.LastSelect != "" && Pages.LastSelect != id){
				var lastSelObject = _(Pages.LastSelect);
				if(lastSelObject != null){
					lastSelObject.className = "indbox";
				}
			}
			Pages.LastSelect = id;*/
			var lstsel = _("indboxsel");
			if (lstsel != null) {
				lstsel.className = "indbox animate-marginleft";
			}
			var curobj = _(id);
			curobj.className = "indboxsel animate-marginleft";
			curobj.scrollIntoView();
			Page.AddTabName(tabName);
			Page.ShowTaskBar();
		},
		Remove: function (id) {
			//__("Removing the page element from pages");
			var idarr = id.split("_");
			//__("Break down the page details");
			var tabName = idarr[0];
			var tabIndex = idarr[1];
			var groupName = idarr[2];
			//remove from OpenedPage String
			Page.RemoveTabName(tabName);
			//__("Tabname : "+tabName);
			//__("TabIndex : "+tabIndex);
			//__("GroupName : "+groupName);
			//get the current open page and tab
			//__("Check if a Page is Currently opened");
			if (Page.CurrOpen.Trim() != "") { //if currently opened
				//__("TRUE. PageID: "+Page.CurrOpen.Trim());
				//__("Get the currently opend pages Details fome Page.Opened array");
				var currop = Page.Opened[Page.CurrOpen];
				// alert(currop)
				//__("Break down the currently opened page details");
				var curroparr = currop.split(";");
				var groupNameop = curroparr[0];
				var tabIndexop = curroparr[1];
				var tabNameop = curroparr[2];
				//__("Opened Tabname : "+tabNameop);
				//__("Opened TabIndex : "+tabIndexop);
				//__("Opened GroupName : "+groupNameop);
				//alert(id);
				//alert(tabNameop + "_" + tabIndexop + "_" + groupNameop);
				//__("check if the to closed page is the current opend page");
				if (id == tabNameop + "_" + tabIndexop + "_" + groupNameop) {
					//__("TRUE");
					//__("check if there exit other page of the same group opened");

					var otherexist = false;
					var pgkeys = Object.keys(Pages.PagesObject);
					for (const s of pgkeys) {
						if (s != id) {
							var v = Pages.PagesObject[s];
							if (IsString(v)) {
								var varr = v.split("_");
								if (varr.length == 3) {
									grpN = varr[2];
									if (groupNameop == grpN) {
										otherexist = true;
									}
								}
							}
						}
						//alert(s);
					}
					var cobj = Page.CurrOpen;
					//get the next tabName
					var ntabName = Page.LastTabName();
					var samegrp = false;
					//alert(ntabName);
					if (ntabName != "") {
						Page.OpenByTabName(ntabName);
						var grpn = Tabs.GetGroupByTabName(ntabName);
						samegrp = groupNameop == grpn;
					} else {
						//close all (display home)
						Page.HideTaskBar();
						//home
					}
					//alert(Page.CurrOpen);
					if (!samegrp) { //if different tab not same group minimize or close
						if (otherexist) {//yes - minimize page
							//__("EXIST");
							//__("Just Minimize It");
							Page.Minimize(cobj);
							//console.log('Minimized - '+tabNameop)
							//__("Minimized");
						} else {
							//no - close page
							//__("Close IT");
							//console.log('Closed - '+tabNameop)
							Page.Close(cobj);
							//__("Closed");
						}
					}


				}
			}
			//__("If Page id loading close exist, Hide it and if page still exist hide it(visibility)");
			var clsbtn = _(id + "_close");
			if (clsbtn != null) clsbtn.Hide();
			var xbtn = _(id);
			if (xbtn != null) xbtn.Disappear();
			//__("Try Animate out the page, then remove it from the body for id: "+id);
			if (xbtn != null) {
				xbtn.Animate({ CSSRule: "width:0px;margin-left:0px", Time: 600, EndAction: "var cpage = _('" + id + "');if(cpage != null){cpage.parentElement.removeChild(cpage);}Pages.PagesObject['" + id + "'] = null;", DoAt: 1.5 });
			}
			return false;


		},
		ToHome: function () {
			Page.Minimize();
			Pages.Close();

		}

	}
}();

var Tracer = function () {
	return {
		Counter: 1,
		CurrentGrup: null,
		GrpTime: null,
		Start: function (grptit) {
			var tracer = _("sTraceBox");
			if (Null(tracer)) {
				tracer = Tracer.Create();
			}
			if (!Null(Tracer.CurrentGrup)) Tracer.End(); //if a group exist end it before starting a new one
			var newgrup = document.createElement("div");
			var dt = new Date();
			newgrup.id = "tracer" + dt.getTime();
			newgrup.className = "sTraceBoxBodyGrp";
			Tracer.CurrentGrup = newgrup;//grptit
			if (typeof grptit != "undefined") {
				//if(grptit.Trim() != ""){
				var sty = '';
				if (grptit.Trim() == "") {
					sty = 'style=border-top:none';
				}
				newgrup.innerHTML = '<div class = "grptit" ' + sty + ' >' + grptit + '</div>';
				//}

			}
			_("sTraceBoxBody").appendChild(newgrup);
			var dt = new Date();
			Tracer.GrpTime = dt.getTime();
			return newgrup;

		},
		offsetx: 60, offsety: 80,
		Create: function () {
			//alert("create");
			var tracer = document.createElement("div");
			tracer.id = "sTraceBox";
			tracer.style.left = "60px";
			tracer.style.top = "80px";
			tracer.className = "sTraceBoxc";
			var header = document.createElement("div");
			header.className = "sTraceBoxHeader";
			header.innerHTML = '<div class="sTraceBoxHeaderTitle">Script Tracer</div><div class="sTraceBoxHeaderClose" onclick="Tracer.Close()"><img  src="../epconfig/TaquaLB/Elements/Images/close.png" width="20" height="20" /></div><div style="clear:both"></div>';
			tracer.appendChild(header);
			var tbody = document.createElement("div");
			tbody.id = "sTraceBoxBody";
			//Tracer.offsetx = 60;
			//Tracer.offsety = 80;
			tracer.appendChild(tbody);
			document.body.appendChild(tracer);
			Drag.register("sTraceBoxHeader", { X: "left", Y: "top" }, {
				Moving: function (param) {
					_("sTraceBox").style[param.PropX] = (Tracer.offsetx + param.MouseX - param.StartX) + "px";
					_("sTraceBox").style[param.PropY] = (Tracer.offsety + param.MouseY - param.StartY) + "px";
				}, Start: function (param) {
					//DragObject:Drag.Current.object,OffsetX:Drag.Current.offsetX,OffsetY:Drag.Current.offsetY,StartX:Drag.StartX,StartY:Drag.StartY,PropX:Drag.ObjectPropFunc[refid].Prop.X.Trim(),PropY:Drag.ObjectPropFunc[refid].Prop.Y.Trim()
					Tracer.offsetx = _("sTraceBox").style[param.PropX].ToNumber();
					Tracer.offsety = _("sTraceBox").style[param.PropY].ToNumber();
				}, Stop: null
			});
			return tracer;
			//DragObject:Drag.Current.object,OffsetX:Drag.Current.offsetX,OffsetY:Drag.Current.offsetY,StartX:Drag.StartX,StartY:Drag.StartY,MouseX:e.clientX,MouseY:e.clientY,PropX:Drag.ObjectPropFunc[refid].Prop.X.Trim(),PropY:Drag.ObjectPropFunc[refid].Prop.Y.Trim()

			//if(Drag.ObjectPropFunc[refid].Prop.X.Trim() != "")Drag.Current.object.style[Drag.ObjectPropFunc[refid].Prop.X.Trim()] = (Drag.Current.offsetX + e.clientX - Drag.StartX) + "px";
		},
		Close: function () {
			Tracer.Counter = 1;
			var stb = _("sTraceBox");
			if (stb != null && typeof stb == "object") {
				stb.Animate({ CSSRule: "opacity:0", Time: 800, DoAt: 1.0, EndAction: "document.body.removeChild(_('sTraceBox'))" });
			}

		},
		Tag: function (tag) {

			if (typeof tag == "undefined") { Tracer.End(); return }; //if tag not sent end the group
			//if(tag.Trim() == "")
			tag = tag.toString();
			if (tag.substr(0, 1) == "#") { Tracer.Start(tag.TrimLeft("#")); return; } //if string start with # start a new group
			if (Null(Tracer.CurrentGrup)) Tracer.Start(" "); //if no group strat one
			var tg = document.createElement("div");
			tg.className = "sTraceBoxBodyCont";
			if (Tracer.GrpTime != null) {
				var dt = new Date();
				var currt = dt.getTime();
				var diff = currt - Tracer.GrpTime;
				Tracer.GrpTime = currt;
			}
			tg.innerHTML = ' <div class="sTraceBoxBodyLogo"><img id="' + Tracer.CurrentGrup.id + "_" + Tracer.Counter + '" src="../epconfig/TaquaLB/Elements/Script/Tracer/Images/clear.png" width="20" height="20" /></div><div class="sTraceBoxBodyNum">' + Tracer.Counter + ':=> </div><div class="sTraceBoxBodyInfo">' + tag + '</div><div class="sTraceBoxBodyTime">' + diff + 'ms</div>';
			var prev = _(Tracer.CurrentGrup.id + "_" + (Tracer.Counter - 1));
			if (!Null(prev)) {
				prev.src = "../epconfig/TaquaLB/Elements/Script/Tracer/Images/check.png";
			}
			Tracer.Counter++;
			Tracer.CurrentGrup.appendChild(tg);
			tg.scrollIntoView();
		},
		End: function () {
			Tracer.GrpTime = null;
			if (Tracer.CurrentGrup == null) return;
			var prev = _(Tracer.CurrentGrup.id + "_" + (Tracer.Counter - 1));
			if (!Null(prev)) {
				prev.src = "../epconfig/TaquaLB/Elements/Script/Tracer/Images/check.png";
			}
			//Tracer.Counter = 1;
			Tracer.CurrentGrup = null;

		}

	}
}();
//__ = Tracer.Tag;
String.prototype.__ = function () { Tracer.Tag(this.toString()) }
var OptionBox = function () {
	return {
		eventlistiners: new Array(),
		AddEventListiner: function (func, param) {
			OptionBox.eventlistiners[OptionBox.eventlistiners.length] = { Function: func, Parameter: param }
			return "OptionBox.Run(" + (OptionBox.eventlistiners.length - 1) + ")";
		},
		TextBox: function (param) {
			if (!IsArray(param)) param = [param];
			var rtnhtml = '';
			for (var d = 0, len = param.length; d < len; d++) {
				param[d].id = param[d].id || "optionbxtb";
				param[d].logo = param[d].logo || "text";
				param[d].title = param[d].title || "";
				param[d].style = param[d].style || "";
				param[d].type = param[d].type || "";
				//get the default textbox
				objmkid = param[d].type == "multiline" ? "OptionBxSampleTextArea" : "OptionBxSampleObjects";
				var dtextbx = _(objmkid).innerHTML;
				rtnhtml += dtextbx.Replace("{{id}}", param[d].id).Replace("{{logo}}", param[d].logo).Replace("{{title}}", param[d].title).Replace("{{style}}", param[d].style).Replace("{{type}}", param[d].type);
			}
			return rtnhtml
		},
		Note: (text) => {
			return '<div class="gennote">' + text + '</div>'
		},
		Switcher: param => {
			if (!IsArray(param)) param = [param];
			var rtnhtml = '';
			for (var d = 0, len = param.length; d < len; d++) {
				param[d].id = param[d].id || "optionbxsw";
				param[d].title = param[d].title || "";
				param[d].info = param[d].info || "";
				param[d].state = param[d].state || 1;
				//get the default textbox
				objmkid = "OptionBxSampleSwitch";
				var dtextbx = _(objmkid).innerHTML;
				rtnhtml += dtextbx.Replace("{{id}}", param[d].id).Replace("{{title}}", param[d].title).Replace("{{info}}", param[d].info).Replace("{{state}}", param[d].state);
			}
			return rtnhtml
		},
		//CloseFunc:null,
		Run: function (ind) {
			if (typeof ind == _UND) return;
			if (typeof OptionBox.eventlistiners[ind] == _UND) return
			var listiner = OptionBox.eventlistiners[ind];
			//alert(JSON.stringify(listiner));
			//__(listiner.Parameter);
			var tot = OptionBox.eventlistiners.length
			if (OptionBox.Close()) {
				listiner.Function(listiner.Parameter);
				//_('OptionTitleHTML').innerHTML='';
			}
			//if(ind < tot - 1){

			//}


		},
		CloseTimmer: null,
		Close: function () {

			OptionBox.eventlistiners = new Array();
			//perform othe close operation
			// _("OptionBx").FadeOut(400,"_('OptionTitle').textContent='';_('OptionBxBody').innerHTML = '';_('OptionTitleHTML').innerHTML='';_('OptionBx').SetStyle('z-index:-1')");

			//_('OptionTitleHTML').innerHTML='';
			opbx = _('OptionBx');
			opbx.FadeOut(500);
			_("OptionBxMain").className = "zoomOutShort animated faster";
			OptionBox.CloseTimmer = setTimeout(() => {
				opbx.SetStyle('z-index:-1;opacity:0');
				_('OptionTitle').textContent = '';
				_('OptionBxBody').innerHTML = '';
				OptionBox.CloseTimmer = null;
			}, 600);
			return true;
		},
		Ajax: new Ajax(),
		Show: function (Param) {
			//alert('show');
			//__("function to show the Option box");
			/*<div id="OptionTitleCont"><div id="OptionTitle">Registration Number Mismatch</div></div>
   <div class="indOption">
	  <div class="indlogo"><img src="TaquaLB/Elements/Images/defaultpassport.png" alt="Add New" /></div>
	  <div class="indDet">
	   <div class="indDetTitle">Add New</div>
	   <div class="indDetCont">Add as a new Student or Update if Entered Registration Number Exist</div>
	  </div>
	  <div class="clear"></div>
   </div>*/
			if (typeof Param == _UND) return;
			if (OptionBox.CloseTimmer != null) clearTimeout(OptionBox.CloseTimmer);
			var opbxHTML = _('OptionTitleHTML');
			//_('OptionTitleHTML').innerHTML='';
			opbxHTML.innerHTML = Widget.Loading();
			//console.log(Widget.Loading());
			//console.log(opbxHTML);
			var opbxBody = _('OptionBxBody');
			opbxBody.innerHTML = "";
			if (IsObject(Param)) {
				if (typeof Param.Options == _UND) {
					Param.Options = [];
				} else if (!IsArray(Param.Options)) {
					Param.Options = [Param.Options];
				}
				//__("Create OptionBx");
				//var opbx = document.createElement("div");
				opbx = _("OptionBx");
				opbxmainbody = _("OptionBxMain");
				//document.body.appendChild(opbx);
				opbx.SetStyle("opacity:0;z-index:11");


				//__("Create OptionBxMain");
				//var opbxmain = document.createElement("div");
				//opbxmain.id = "OptionBxMain";
				//__("Append OptionBxMain to OptionBx");
				//opbx.appendChild(opbxmain);
				//opbxmain.SetStyle("opacity:0;top:10px");
				//__("Create OptionTitleCont");
				//var OptionTitleCont = document.createElement("div");
				OptionTitle = _("OptionTitle");
				Param.Logo = typeof Param.Logo == _UND ? "exclamation-triangle" : Param.Logo;
				if (typeof Param.ShowClose != _UND && Boolean(Param.ShowClose) == false) {
					_('OptionClose').Hide();
				} else {
					_('OptionClose').Show();
				}
				OptionTitle.innerHTML = Param.Logo.Icon() + ' ' + '<span>' + Param.Title + '</span>';
				if (typeof Param.TitleHTML != _UND) {
					if (typeof Param.TitleHTML == "string") {
						opbxHTML.innerHTML = Param.TitleHTML;
					} else {
						if (typeof Param.TitleHTML.Action != _UND) {
							OptionBox.Ajax.Post({
								Action: Param.TitleHTML.Action,
								Data: (typeof Param.TitleHTML.Data != _UND) ? Param.TitleHTML.Data : {},
								OnComplete: res => {
									opbxHTML.innerHTML = res;
								},
								OnAbort: res => {
									opbxHTML.innerHTML = "";
								},
								OnError: res => {
									opbxHTML.innerHTML = "";
								}
							});
						} else {
							opbxHTML.innerHTML = "";
						}
					}

				} else {
					opbxHTML.innerHTML = "";
				}
				//__("Append OptionTitleCont to OptionBxMain");
				//opbxmain.appendChild(OptionTitleCont);


				if (IsArray(Param.Options)) {
					//Param.Options.push({Logo:"TaquaLB/Elements/Images/closebig.png",Title:"Cancel Operation",Info:"Cancel the Operation",Function:"OptionBox.Close()"});
					for (var op = 0, lenop = Param.Options.length; op < lenop; op++) {
						var indOption = Param.Options[op];
						var logo = indOption.Logo;
						var Tit = indOption.Title;
						var info = indOption.Info;
						var func = typeof indOption.Function == _UND ? null : indOption.Function;
						if (IsString(func)) {
							//__('If function is string');
							//__('Trim the function brackets if exist');
							func = func.Trim().TrimRight(")").Trim().TrimRight("(");
							// __('Form the string function with parameter if exist and set to the Options parameter :'+func);
							if (typeof indOption.Parameter != _UND) {
								indOption.Parameter = func + "(" + (IsNumber(indOption.Parameter) ? indOption.Parameter : "'" + indOption.Parameter.toString() + "'") + ")";
							} else {
								indOption.Parameter = func + "()";
							}

							//__('Reset the function to function that runs the string which is sent as parameter');
							func = function (para) {
								//eval(para);  
								setTimeout(para, 1);
							}

						} else {
							indOption.Parameter = typeof indOption.Parameter == _UND ? null : indOption.Parameter;
						}
						//form option html
						var res = '<div class="indOption" onclick="' + OptionBox.AddEventListiner(func, indOption.Parameter) + '"><div class="indlogo altColor2"><div class="logobx">' + (logo.Icon()) + '</div></div><div class="indDet"><div class="indDetTitle">' + Tit + '</div><div class="indDetCont">' + info + '</div></div><div class="clear"></div></div>';
						//add options
						//opbxmain.insertAdjacentHTML('beforeend',res)
						opbxBody.innerHTML += res;
					}


				}
				opbx.FadeIn(500);
				opbxmainbody.className = "zoomInShort animated faster";
				//_('OptionBxMain').Animate({CSSRule:"opacity:1;top:100px", Time:300, Delay:2});
			}

		}
	}
}();

//object to perform print
var SendPrint = function () {
	return {
		Start: function (url) {
			OptionBox.Show({
				Title: "Print to",
				Options: [{
					Logo: "TaquaLB/Elements/Images/defaultpassport.png",
					Title: "Printer",
					Info: "Print by allowing Printer Selection",
					Function: function () { },
					Parameter: null
				},
				{
					Logo: "TaquaLB/Elements/Images/closebig.png",
					Title: "PDF",
					Info: "Print document as PDF file",
					Function: function () { _("Studenttab").ProgressGet(0).ProgressTo(100, 'MessageBox.Show("Process Canceled")'); }
				}]

			});

		}
	}
}();

//Local ClipBoard //uses cookie
var ClipBoard = function () {
	return {
		//types:image,text,regno,etc
		Copy: function (value, type) {
			Cookie.Set(type, value, _Day);
		},
		Paste: function (type) {
			var val = Cookie.Get(type);
			//Cookie.Set(type,"",-1000);
			return val;
		},
		CopyText: (container_id, as_html) => {

			isEmpty = function (val) {
				return (val === undefined || val == null || val.length <= 0) ? true : false;
			};

			as_html = isEmpty(as_html) ? false : true;

			//console.log('copyToClipboard: ' + container_id);
			var isPlainString = false;
			var elem = null;
			if (container_id.trim().substr(0, 1) == "*") {
				isPlainString = true;
				container_id = container_id.trim().substr(1);
			} else {
				elem = _(container_id);
			}

			// create hidden text element, if it doesn't already exist
			var targetId = "_hiddenCopyText_";
			var isInput = elem != null && (elem.tagName === "INPUT" || elem.tagName === "TEXTAREA");
			var origSelectionStart, origSelectionEnd;
			if (isInput) {
				// can just use the original source element for the selection and copy
				target = elem;
				origSelectionStart = elem.selectionStart;
				origSelectionEnd = elem.selectionEnd;
				//console.log ('_is_input = true');
			} else {
				// must use a temporary form element for the selection and copy
				//console.log ('_is_input = false, creating a textarea = ' + targetId);
				target = _(targetId);
				if (!target) {
					var target = document.createElement("textarea");
					target.style.position = "absolute";
					target.style.left = "-9999px";
					target.style.top = "0";
					target.id = targetId;
					document.body.appendChild(target);
				}
				var content;
				if (elem != null) {
					content = as_html ? _(elem).innerHTML : _(elem).textContent;
				} else {
					content = container_id;
				}

				target.value = content;
				//console.log ('text_content', content);
			}
			// select the content
			var currentFocus = document.activeElement;
			target.focus();
			target.setSelectionRange(0, content.length);

			// copy the selection
			var succeed;
			try {
				succeed = document.execCommand("copy");
			} catch (e) {
				succeed = false;
			}
			// restore original focus
			if (currentFocus && typeof currentFocus.focus === "function") {
				currentFocus.focus();
			}

			if (isInput) {
				// restore prior selection
				elem.setSelectionRange(origSelectionStart, origSelectionEnd);
			} else {
				// clear temporary content
				target.value = '';
			}

			return succeed;
		}


	}

}();

//Spread Sheet Object
var SpreadSheet = function () {
	return {
		UpdateFlag: {},
		WaitingLog: {},
		DisplayButtomColumn: function (ssbid) {
			if (_('shownm_' + ssbid).Data("status") == "0") {
				_('ssheaderdwn_' + ssbid).FadeIn(300);
				_('shownm_' + ssbid).Data("status", 1);
			} else {
				_('ssheaderdwn_' + ssbid).FadeOut(300);
				_('shownm_' + ssbid).Data("status", 0);
			}

		},
		AddColumn: function (ssobj, colunmHeader, newcellid, cid) {
			//document.getElementById().he
			//addCln_{$tid}
			var innerpop = _(newcellid + "_innerpop");
			var columnNum = innerpop != null ? innerpop.Data("column").ToNumber() : 0;
			var addClnbtn = _("addCln_" + ssobj.id); //get the add button of the spreed sheet
			if (addClnbtn.innerHTML != "circle-o-notch fa-spin".Icon()) { //if add buttons logo is not loading logo spining
				addClnbtn.innerHTML = "circle-o-notch fa-spin".Icon(); //set it to loading logo
				var totrw = ssobj.rows.length; //get the total rows of the table
				if (totrw > 0) { //if row exist
					var totcol = ssobj.rows[0].cells.length; //use the first row to get the total column
					var insertind = totcol - 1; //declear the index of the new cell to add (second to the last, which is currently the index of the last)
					newcellid = newcellid == null ? insertind + 1 : newcellid;
					var drpdwn = "";
					var celheader = "";
					var inner = _(newcellid + "_innerpop");
					disablec = "false";
					if (inner != null) {
						//cellheader
						var drpdwn = inner.Data("dropdown");
						var celheader = inner.Data("cellheader");
						var editable = inner.Data("editable");
						var disablec = inner.Data("disable");
						var multi = inner.Data("multi");
					}
					var bgco = "";
					if (disablec == "true") {
						bgco = ";background-color:#F5F5F5"
						editable = "false";
					}
					// disablec == "true"?"":"";
					//if columnNumber not exixt asign new
					if (columnNum < 1) {
						columnNum = ssobj.Data("maxdiscolumn").ToNumber() + 1; //get the lastnum and increment
						innerpop.Data("column", columnNum); //update the popup list cell column attr
						ssobj.Data("maxdiscolumn", columnNum);//update the max column number of the spreadsheet
					}
					//update the datastring of the spreadsheet to read the new added column name and number
					// var datstrobj = _(ssobj.id+"_datastring");
					var datstr = ssobj.Data("displaycolumn");
					ssobj.Data("displaycolumn", datstr + "&" + newcellid + "=" + columnNum);
					// datstrobj.value = datstr;
					for (var ri = 0; ri < totrw; ri++) { //loop through all rows to add the cell
						var cellid = ssobj.id + "_rw_" + (ri + 1) + "_" + newcellid;
						//form the inserted cell id
						colunmHeaderd = colunmHeader;
						if (ri == 0 || ri == totrw - 1) { //if first row (header)
							if (typeof cid != _UND) {
								cid = '<input type="hidden" id="h_' + cid + '" value="' + cellid + '" />';

								//cid = '<input type="hidden" id="h_'+cid+'" value="'+insertind+'" /><input type="hidden" id="u_'+cellid+'" value="'+cid+'" />';
							} else {
								cid = "";
							}
							if (ri == totrw - 1) {
								cellid += ".";
								//shownm_{$tblid}
								var op = _('shownm_' + ssobj.id).Data('status');
								//'ssheaderdwn_'+ssbid
								colunmHeaderd = '<span class = "ssheaderdwn_' + ssobj.id + '" style="opacity:' + op + '" >' + colunmHeader + '</span>'; //buttom header text
							}
							//add as a th cell and move to next row <div id="FirstName_inner" data-dropdown="" data-cellheader="FIRSTNAME">FIRSTNAME<input id="h_FirstName" value="biodataPreload_rw_1_6" type="hidden"></div>
							ssobj.rows[ri].insertCell(insertind).outerHTML = "<th id=\"" + cellid + "\"><div id=\"" + newcellid + "_inner\" data-dropdown=\"" + drpdwn + "\" data-cellheader=\"" + colunmHeader + "\" data-multi=\"" + multi + "\"  data-editable=\"" + editable + "\" data-disable=\"" + disablec + "\" data-column=\"" + columnNum + "\" >" + colunmHeaderd + cid + "</div></th>";
							cid = ""
							continue;
						}

						var insertcell = ssobj.rows[ri].insertCell(insertind); //insert the cell
						var selfuncobj = _("selfunc_" + ssobj.id); //get the table cell selection function object
						var unselfuncobj = _("unselfunc_" + ssobj.id); //get the table cell de-selection function object
						var selfunc = !Null(selfuncobj) ? "," + selfuncobj.value : ""; //form the function string
						if (selfunc != "") {
							selfunc += !Null(unselfuncobj) ? "," + unselfuncobj.value : "";
						}

						//(ssobj.id + "_cellfocus").__();
						var cellfocus = _(ssobj.id + "_cellfocus").value;
						var cellblur = _(ssobj.id + "_cellblur").value;
						var cellkeypress = _(ssobj.id + "_cellkeypress").value;
						var lcase = ssobj.Data("case");
						//redeclear the inserted cell outer html to carry required properties, and set the included hidden elements
						insertcell.outerHTML = '<td onclick="Table.Select(this,false' + selfunc + ')" id="' + cellid + '" style="z-index:1' + bgco + '"><div style="width:calc(100% - 8px); min-height:15px;text-transform:' + lcase + ';padding:4px' + bgco + '" contenteditable="' + editable + '" id="' + cellid + '_edit" onkeyup="SpreadSheet.KeyPress(this,event);' + cellkeypress + '"  onfocus="this.spellcheck = true;SpreadSheet.CellSelect(this);' + cellfocus + '" onblur= "this.spellcheck = false;SpreadSheet.CellUuSelect(this);' + cellblur + '" data-column="' + columnNum + '" data-value=""></div></td><input type="hidden" id="inpsel_' + cellid + '" value="" /><input type="hidden" id="inp_' + cellid + '" value="' + cellid + '" /><input type="hidden" id="' + ssobj.id + '_' + cellid + '" value="' + cellid + '" />';

						// insertcell.innerHTML = '<div style="width:100%; min-height:15px" contenteditable="true" id="'+cellid+'_edit" ></div> ';
					}
				}
				addClnbtn.innerHTML = "columns".Icon(); //return the add button logo to plus logo
			}
		}, ResetRowCellsIndex: function (row) {
			var totcol = row.cells.length;
			var rowind = row.rowIndex;
			var tabl = _(row.id.split("_")[0]);
			var totrw = tabl.rows.length;
			//(rowind+"").__();
			if (totcol > 0) {
				//(totcol+" Columns").__();
				for (var f = 0; f < totcol; f++) {
					/*var currcell = row[f];
					var currcellidarr = currcell.id.split("_");
					var newcellid = currcellidarr[0] + "_rw_" + currcellidarr[2] + "_"+(f + 1);
					if(rowind == 0 || rowind == totrw-1){
						var uid = _("u_"+currcell.id).value;
						_("u_"+currcell.id).id = "u_"+newcellid;
						_("h_"+uid).value = f;
					}else{
					_(currcell.id + "_edit").id = newcellid+"_edit";
					_('inpsel_'+currcell.id).id = 'inpsel_'+newcellid;
					_('inp_'+currcell.id).id = 'inp_'+newcellid;
					_(currcellidarr[0]+'_'+currcell.id).id = currcellidarr[0]+'_'+newcellid;
					}
					currcell.id = newcellid;*/
					var currcell = row.cells[f];
					/*if(Null(currcell)){
						("Null found for: "+f).__();
					}*/
					if (rowind == 0) {
						var tp = typeof currcell;
						//("Type of current cell: "+tp).__();
						//("Current cell index: "+f).__();
						//("Current Cell ID: "+currcell.id).__()
						var uobj = _("u_" + currcell.id);
						//("Type of current cell userid object: "+ typeof uobj).__();
						//("user id object: "+uobj).__();
						if (!Null(uobj)) {
							//("user id object tag name: "+uobj.tagName).__();
							//uobj.id.__();

							var uid = uobj.value;

							//("uid = "+uid).__();

							//_("u_"+currcell.id).id = "u_"+newcellid;
							_("h_" + uid).value = f;
							//("set cell index = "+f).__();

						}
					}
				}
			}
		},
		RemoveColumn: function (ssobj, columind, columnName) {
			var totrw = ssobj.rows.length;
			var columnNum = _(columnName + "_inner").Data("column"); //get the columun number trough the header inner div attr column
			if (totrw > 1) {
				var totcol = ssobj.rows[0].cells.length;
				if (columind == 0 || columind == totcol - 1) { return }
				for (var d = 0; d < totrw; d++) {
					var currow = ssobj.rows[d];
					if (!Null(currow)) {
						currow.deleteCell(columind);
						//<input type="hidden" id="inpsel_'+cellid+'" value="" /><input type="hidden" id="inp_'+cellid+'" value="'+cellid+'" /><input type="hidden" id="'+ssobj.id+'_'+cellid+'" value="'+cellid+'" />
						var celinpsel = _("inpsel_" + ssobj.id + "_rw_" + (d + 1) + "_" + (columind + 1));
						if (!Null(celinpsel)) { currow.removeChild(celinpsel) }
						var celinp = _("inp_" + ssobj.id + "_rw_" + (d + 1) + "_" + (columind + 1));
						if (!Null(celinp)) { currow.removeChild(celinp) }
						var celobjj = _(ssobj.id + "_" + ssobj.id + "_rw_" + (d + 1) + "_" + (columind + 1));
						if (!Null(celobjj)) { currow.removeChild(celobjj) }
						//document.getElementById().removeChild();
						//SpreadSheet.ResetRowCellsIndex(currow);
					}
				}
				//delete from spreadsheet datastring 

				var dispcols = ssobj.Data("displaycolumn");
				dispcols = DataString.Remove(dispcols, columnName).TrimRight("&"); //remove the column det from the spreadsheet datastring
				//remove the column data from the datastring
				ssobj.Data("displaycolumn", dispcols);
				var datastrobj = _(ssobj.id + "_datastring");
				if (datastrobj != null) {
					var datastr = datastrobj.value;

					var columnsearch = new RegExp("\\d+_" + columnNum + "=[\\w~`!@#\\$%\\^\\*\\(\\)-_\\+\\=\\{\\}\\[\\]\\|\\\:;\"'<,>.?/]*&*", "g");
					datastrobj.value = DataString.Remove(datastr, columnsearch).TrimRight("&");
					// datastrobj.value = DataString.Remove(datastr,columnsearch);
					//alert('var datastr = _("'+ssobj.id+'_datastring").value;_("'+ssobj.id+'_datastring").value = DataString.Remove(datastr,"'+columnName+'");'); 
					// eval('var datastr = _("'+ssobj.id+'_datastring").value;datastr = DataString.Remove(datastr,"'+columnName+'");_("'+ssobj.id+'_datastring").value = DataString.Remove(datastr,/^_'+columnNum+'=.+&$/g);');  
					// eval('var datastr = _("'+ssobj.id+'_datastring").value;_("'+ssobj.id+'_datastring").value = DataString.Remove(datastr,/^_'+columnNum+'=.+&$/);alert(_("'+ssobj.id+'_datastring").value)');
					// alert(datastr.replace(columnsearch,""));
					// alert(datastr.replace(/\d+_6=[\w~`!@#\$%\^\*\(\)-_\+\=\{\}\[\]\|\\:;"'<,>.?/]*&/g,""));
				}
			}
		},
		ColumnDataExist: function (ssid, elemid) {
			var datastrobj = _(ssid + "_datastring");
			if (datastrobj != null) {
				var datastr = datastrobj.value;
				var columnNum = _(elemid + "_inner").Data("column");
				//var columnNum = 6;
				var columnsearch = new RegExp("\\d+_" + columnNum + "=[\\w~`!@#\\$%\\^\\*\\(\\)-_\\+\\=\\{\\}\\[\\]\\|\\\:;\"'<,>.?/]+&*", "g");
				var seen = datastr.search(columnsearch);
				return seen > -1 ? true : false;
			}
			return false;
		},
		RemoveColumnFromListPre: function (cell) {
			var cellid = _("inp_" + cell.id).value;
			//alert(cellid);
			var elemid = cellid.split("_")[0];
			var sscellid = _("h_" + elemid).value; //get the tables cell id
			var ssid = sscellid.split("_")[0]; //get spreadsheet id
			var datastrobj = _(ssid + "_datastring");
			if (datastrobj != null) {
				var datastr = datastrobj.value;

				var columnNum = _(elemid + "_inner").Data("column");
				//var columnNum = 6;
				var columnsearch = new RegExp("\\d+_" + columnNum + "=[\\w~`!@#\\$%\\^\\*\\(\\)-_\\+\\=\\{\\}\\[\\]\\|\\\:;\"'<,>.?/]+&*", "g");
				var seen = datastr.search(columnsearch);
			}
			if (seen > -1) {
				OptionBox.Show({
					Title: "Warming!: Data Loss",
					Options: [{
						Logo: "trash",
						Title: "Continue",
						Info: "Remove Column; All Column Data will be Lost",
						Function: function (param) {
							//  alert(param[0]+";"+param[1]);
							SpreadSheet.RemoveColumnFromList(param[0], param[1]);
						},
						Parameter: [ssid, elemid]
					},
					{
						Logo: "times",
						Title: "Cancel",
						Info: "Cancel Operation",
						Function: function (cell) {
							SpreadSheet.NoAdd = true;
							cell.click();
						},
						Parameter: cell
					}]
				});
			} else {
				SpreadSheet.RemoveColumnFromList(ssid, elemid);
			}

		},
		RemoveColumnFromList: function (ssid, elemid) {
			/*var cellid = _("inp_"+cellrid).value;
			//alert(cellid);
			var elemid = cellid.split("_")[0];
			var sscellid = _("h_"+elemid).value; //get the tables cell id
			var ssid = sscellid.split("_")[0]; //get spreadsheet id
			//alert(ssid);*/
			var sscellid = ssid + "_rw_1_" + elemid; //form the spreadsheet cell id ()
			//alert(sscellid);
			//sscellid.__();
			var maincell = _(sscellid);

			//var edita = _(sscellid+"_")
			columind = maincell.cellIndex; //get the cell index of the cell in the dom table object
			//	alert(columind);
			//alert();
			//var poptableid = cell.id.split("_")[0];
			//var spreadsheetid = poptableid.substr(6);
			SpreadSheet.RemoveColumn(_(ssid), columind, elemid);
		},
		NoAdd: false,//help to control if column to be added or not (incase user select cancel for column removal operation)
		AddColumnFromList: function (cell) {
			if (SpreadSheet.NoAdd == true) {
				SpreadSheet.NoAdd = false;
				return;
			}
			//alert(cell.outerHTML);
			var txt = cell.textContent;
			var listcellidarr = cell.id.split("_");
			var newcellid = listcellidarr[3];
			var cellid = _("inp_" + cell.id).value;
			var elemid = cellid.split("_")[0];
			var poptableid = listcellidarr[0];
			var spreadsheetid = poptableid.substr(6);
			//var columnID = listcellidarr[3];


			//alert(cell.id);
			SpreadSheet.AddColumn(_(spreadsheetid), txt, newcellid, elemid);
			//alert(txt + " ; " + elemid + " ; " + spreadsheetid);
		},
		AddRow: function (ssobj) {
			var dynrow = ssobj.Data("dynamicrow");
			if (dynrow != "" && dynrow != "true") return;
			var totrw = ssobj.rows.length;

			//if(totrw > 0){
			//get the total column from the first row
			var frw = ssobj.rows[0];
			var totcl = frw.cells.length;
			var lstrw = ssobj.rows[totrw - 2];
			var altcls = "alt";

			if (lstrw.classList.contains("alt")) {
				altcls = "";
			}


			var nwrw = ssobj.insertRow(totrw - 1);
			nwrw.id = ssobj.id + "_rw_" + (totrw);
			nwrw.className = "class_" + ssobj.id + " " + altcls;
			ssobj.Data("maxdatarow", totrw - 1); //update the maxdatarow attribute of the spreadsheet element
			var allowclear = ssobj.Data("allowclear");
			for (var j = 0; j < totcl; j++) {
				var tpdisplay = "";
				//get the id of the header cell
				var headercellid = frw.cells[j].id;
				var headercellidarr = headercellid.split("_");
				var columnid = headercellidarr[3];
				var newcl = nwrw.insertCell(j);
				var celltype = "td";
				var content = "";
				var cellid = ssobj.id + "_rw_" + (totrw) + "_" + columnid; //form the inserted cell id

				if (j == 0 || j == totcl - 1) {
					var inss = ''; var delll = ""; var hidd = '';
					if (j == 0) {
						//get the last valid row serial number div
						var looprw = totrw - 1;
						inss = totrw - 1;
						while (_(ssobj.id + '_rw_' + looprw + '_0_sn') != null) {
							var snobj = _(ssobj.id + '_rw_' + looprw + '_0_sn');
							//console.log(snobj.parentElement.parentElement);
							var trobj = snobj.parentElement.parentElement.parentElement;
							if (trobj.className.indexOf(' deleterw') == -1) {
								inss = snobj.textContent.ToNumber() + 1; break;
							}
							looprw--;
						}
						delll += "<div class=\"clearcell greyShadow altColor2\" title=\"Add Banner\" onclick=\"SpreadSheet.ToggleBanner(" + totrw + ",'" + ssobj.id + "','" + allowclear + "')\">" + 'tags'.Icon() + "</div><div class=\"deletecell greyShadow altColor\" title=\"Delete Row\" onclick=\"SpreadSheet.DeleteRow(" + totrw + ",'" + ssobj.id + "')\">" + 'trash'.Icon() + "</div>";
						hidd = 'id="' + ssobj.id + '_rw_' + totrw + '_0_sn"';
					}

					//	var delll = (j==0)?"<div style=\"position:relative\"><div class=\"clearcell greyShadow altColor2\" title=\"Clear Row\" onclick=\"SpreadSheet.ClearRow("+totrw+",'"+ssobj.id+"')\">"+'square-o'.Icon()+"</div><div class=\"deletecell greyShadow altColor\" title=\"Delete Row\" onclick=\"SpreadSheet.DeleteRow("+totrw+",'"+ssobj.id+"')\">"+'trash'.Icon()+"</div>":"";
					celltype = "th";
					content = "<div style=\"position:relative\">" + delll + '<div style="padding:0px" ' + hidd + ' >' + inss + '</div></div>';
					var bgco = "";
					//newcl.outerHTML = "<th>"+totrw+"</th>";
				} else {
					var cellfocus = _(ssobj.id + "_cellfocus").value;
					var cellblur = _(ssobj.id + "_cellblur").value;
					var cellkeypress = _(ssobj.id + "_cellkeypress").value;
					var headeriner = _(columnid + "_inner");
					//get the lastrw cell
					//payitems_lstrw_PID.
					var lstcell = _(ssobj.id + "_lstrw_" + columnid + ".");
					tpdisplay = "padding:0px;";
					lstvalue = "";
					lstinner = "";
					if (lstcell.style.display == "none") {
						tpdisplay = "display:none;padding:0px;";
						var editdiv = lstrw.cells[j].firstElementChild;
						if (headeriner != null) {
							drpdown = headeriner.Data("dropdown").Trim();
							if (drpdown != "") {
								var lstvalue = editdiv.hasAttribute('data-value') ? editdiv.getAttribute('data-value') : "";
								var lstinner = editdiv.innerHTML;
							}

						}
					}

					// alert(tpdisplay)
					var editable = "true";
					var disablec = "false";
					var bgco = "";
					var drpdown = "";
					var isSwitch = false;
					var genclass = "";
					if (headeriner != null) {
						editable = headeriner.Data("editable");
						disablec = headeriner.Data("disable");
						drpdown = headeriner.Data("dropdown");

						genclass = headeriner.Data("class");
						calendar = headeriner.Data("calendar") == "true" ? "Calendar" : "";
						calendarRange = headeriner.Data("calender-range");//
						// console.log(j+"-"+columnid+":"+drpdown);
						var swtxt = drpdown.split("|");
						if (swtxt.length == 2) {
							if (swtxt[0] == "YES" && swtxt[1] == "NO") isSwitch = true;

						}
						bgco = disablec == "true" ? ";background-color:#F5F5F5" : "";
					}
					//insertcell.outerHTML = '<td onclick="Table.Select(this,false'+selfunc+')" id="'+cellid+'" style="padding:0px"><div style="width:calc(100% - 8px); min-height:15px;padding:4px'+bgco+'" contenteditable="'+editable+'" id="'+cellid+'_edit" onkeyup="SpreadSheet.KeyPress(this,event);'+cellkeypress+'"  onfocus="this.spellcheck = true;SpreadSheet.CellSelect(this);'+cellfocus+'" onblur= "this.spellcheck = false;SpreadSheet.CellUuSelect(this);'+cellblur+'"></div></td><input type="hidden" id="inpsel_'+cellid+'" value="" /><input type="hidden" id="inp_'+cellid+'" value="'+cellid+'" /><input type="hidden" id="'+ssobj.id+'_'+cellid+'" value="'+cellid+'" />';
					if (isSwitch) {
						//console.log(j+columnid+':Switcher');
						//var stxt = drpdown.split("|");
						content = '<div style="width:auto;margin:2px"><div class="switchbox normal Default ' + genclass + '" onclick="Switcher.Select(this,SpreadSheet.SwicthChange)" id="' + cellid + '_sw" data-value="0" data-column="' + j + '" style="float:left;margin-top:3px" data-ontext="' + swtxt[0] + '" data-offtext="' + swtxt[1] + '"><div class="cover"><i class="fa fa-cog fa-spin" aria-hidden="true" style=""></i></div><div id="' + cellid + '_sw_mover" class="move"></div><input type="hidden" id="st_' + cellid + '_sw" value="0"><input type="hidden" id="frm_' + cellid + '_sw" value="Default"></div><div class="clearer"></div> </div>';
						//update the delete status
						//var ssobdata = ssobj.GetDataObject();
						//ssobdata.value = DataString.Set(ssobdata.value,(totrw - 1)+"_"+j,'0');
						/*  */
					} else {
						var lcase = ssobj.Data("case");
						//console.log('Not Switcher');
						content = '<div style="width:calc(100% - 8px); min-height:15px;text-transform:' + lcase + ';padding:4px' + bgco + '" contenteditable="' + editable + '" class="' + calendar + ' ' + genclass + '" data-range="' + calendarRange + '" id="' + cellid + '_edit" onkeyup="SpreadSheet.KeyPress(this,event);' + cellkeypress + '"  onfocus="this.spellcheck = true;SpreadSheet.CellSelect(this);' + cellfocus + '" onblur= "this.spellcheck = false;SpreadSheet.CellUuSelect(this);' + cellblur + '" data-column="' + j + '" data-value="' + lstvalue + '"  >' + lstinner + '</div>';
					}

				}
				//document.getElementById().spellcheck = f

				//var insertcell = ssobj.rows[totrw].insertCell(insertind); //insert the cell
				var selfuncobj = _("selfunc_" + ssobj.id); //get the table cell selection function object
				var unselfuncobj = _("unselfunc_" + ssobj.id); //get the table cell de-selection function object
				var selfunc = !Null(selfuncobj) ? "," + selfuncobj.value : ""; //form the function string
				if (selfunc != "") {
					selfunc += !Null(unselfuncobj) ? "," + unselfuncobj.value : "";
				}
				//alert('<'+celltype+' onclick="Table.Select(this,false'+selfunc+')" id="'+cellid+'"  style="'+tpdisplay+'z-index:1'+bgco+';padding:0px">'+content+'</'+celltype+'><input type="hidden" id="inpsel_'+cellid+'" value="" /><input type="hidden" id="inp_'+cellid+'" value="'+cellid+'" /><input type="hidden" id="'+ssobj.id+'_'+cellid+'" value="'+cellid+'" />');
				//redeclear the inserted cell outer html to carry required properties, and set the included hidden elements
				newcl.outerHTML = '<' + celltype + ' onclick="Table.Select(this,false' + selfunc + ')" id="' + cellid + '"  style="' + tpdisplay + 'z-index:1' + bgco + '" class="">' + content + '</' + celltype + '><input type="hidden" id="inpsel_' + cellid + '" value="" /><input type="hidden" id="inp_' + cellid + '" value="' + cellid + '" /><input type="hidden" id="' + ssobj.id + '_' + cellid + '" value="' + cellid + '" />';

				//console.log();
				var editcell = _(cellid + "_edit");
				if (editcell != null) {
					var upd = SpreadSheet.UpdateDataString(editcell);
				}




			}
			return nwrw;
			//}
		},
		DeleteRow: function (rwnum, tbid, force) {
			force = typeof force == _UND ? false : force;
			var sstb = _(tbid);
			if (sstb != null) {
				if (sstb.Data("rowdelete") != "true" && force == false) { MessageBox.Show("NOT ALLOWED"); return };
				//get the row
				var rw = _(tbid + "_rw_" + rwnum);
				if (rw != null) {
					//hide the row
					rw.className += ' deleterw';
					rw.Hide();
					//alert(rwnum+"_deleted")
					//update the delete status
					var ssobdata = sstb.GetDataObject();
					ssobdata.value = DataString.Set(ssobdata.value, (rwnum - 1) + "_deleted", 'true');

					//update other visible row sn
					while (_(tbid + "_rw_" + (rwnum + 1)) != null) {
						setTimeout("SpreadSheet.DeductRowsSN(" + (rwnum + 1) + ",'" + tbid + "')", 1);
						rwnum++;
					}

				}
			}
		},
		DeductRowsSN: function (rwnum, tbid) {
			//get the row
			var rwobj = _(tbid + "_rw_" + rwnum);
			if (rwobj.className.indexOf(' deleterw') > -1) return;
			//get the sn div 
			var snrwdiv = _(tbid + "_rw_" + rwnum + "_0_sn");
			if (snrwdiv == null) return;
			var nval = snrwdiv.textContent.ToNumber() - 1;
			if (nval < 1) return;
			snrwdiv.textContent = nval;
		},

		SwitchAll: function (tbid, btn, starter) {
			starter = typeof starter == _UND ? 2 : starter;
			var order = btn.Data('toggle').ToNumber();
			//console.log(order)
			var btnlogo = _(btn.id + '_i');
			if (starter == 2) { //if the first entering perform toggle set
				if (order < 1) {
					btn.Data('toggle', "1");
					if (btnlogo != null) btnlogo.className = btnlogo.className.replace("toggle-off", "toggle-on");
					btn.title = "Turn All On";
				} else {
					btn.Data('toggle', "0");
					if (btnlogo != null) btnlogo.className = btnlogo.className.replace("toggle-on", "toggle-off");
					btn.title = "Turn All Off";
				}
			}


			//console.log("Start : "+ order);
			//console.log("*************************");
			btn.disabled = true;
			//SpreadSheet.Sortings[tbid] = true;
			var cellind = btn.id.split("_")[0];
			table = _(tbid);
			var ssobdata = table.GetDataObject();
			var ssobdatastr = ssobdata.value;
			if (ssobdatastr.Trim() == "") return;
			var maxrow = DataString.Get(ssobdatastr, "MaxDataRow").ToNumber();
			SpreadSheet.IndSwitching(tbid, cellind, maxrow, 2, order, btn);
			//get the colonm index
			// alert(btn.id.split("_")[0]);
		},

		IndSwitching: function (tbid, cellind, maxrow, starter, order, btn) {
			var cnt = 1;
			//var multi = false;
			//for(var d=starter; d <= maxrow + 1; d++){
			if (starter > maxrow + 1) { //manage many row sheet from crashing the browser
				btn.disabled = false;
				return;
			}
			var innersw = 5;
			for (var ss = 1; ss <= innersw; ss++) {

				var sw = _(tbid + "_rw_" + starter + "_" + cellind + "_sw");
				if (sw != null) {
					if (order > 0) {
						sw.SwitchOn(SpreadSheet.SwicthChange);
					} else {
						sw.SwitchOff(SpreadSheet.SwicthChange);
					}
				}
				starter++;
			}



			setTimeout("SpreadSheet.IndSwitching('" + tbid + "','" + cellind + "'," + maxrow + "," + starter + "," + order + ",_('" + btn.id + "'))");
			// multi = true;
			// break;
			// }
			// }
			// if(multi == false)
		},
		//Switcher.Select(this,SpreadSheet.SwicthChange)
		IndSorting: function (tbid, rwind, cellind, maxrw, order, switching, btnid) {
			if (switching) {
				//var d = document.createDocumentFragment();

				switching = false;
				if (typeof tbl == "undefined" || tbl == null) {
					var tbl = _(tbid);
				}


				//d.appendChild(tbl);
				rows = _(tbid).rows;
				//rows = d.childNodes[0].rows;

				/* Loop through all table rows (except the
				first, which contains table headers): */
				for (rwind = 1; rwind < maxrw; rwind++) {
					//for (i = 1; i < (rows.length - 2); i++) {
					// Start by saying there should be no switching:
					shouldSwitch = false;
					var nrwind = rwind
					/* Get the two elements you want to compare,
					one from current row and one from the next: */
					//console.log(rows[i].cells.length)
					x = rows[rwind].cells[cellind];
					y = rows[rwind + 1].cells[cellind];
					xfirst = x.firstElementChild
					if (xfirst.id == x.id + "_edit") { //normal edit box
						xval = xfirst.textContent.toLowerCase();
						yfirst = y.firstElementChild;
						yval = yfirst.textContent.toLowerCase();
					} else {
						//checking for a switch cell
						xfirst = x.firstElementChild.firstElementChild;
						if (xfirst.id == x.id + "_sw") {
							xval = xfirst.Data('value');
							yfirst = y.firstElementChild.firstElementChild;
							yval = yfirst.Data('value');
						} else {
							xval = x.textContent;
							yval = y.textContent;
						}
					}


					// Check if the two rows should switch place:
					//console.log("Order = "+ order);
					//console.log("Xval = "+ xval);
					//console.log("Yval = "+ yval);


					//console.log(x.innerHTML.toLowerCase() +" ; "+ y.innerHTML.toLowerCase());
					if ((order == 0 && xval > yval) || (order == 1 && xval < yval)) {
						//console.log("Switchable");
						// If so, mark as a switch and break the loop:
						shouldSwitch = true;
						nrwind = 1; //reset rowind to start again
						break;
					}


				}
				if (shouldSwitch) {
					/* If a switch has been marked, make the switch
					and mark that a switch has been done: */
					var tempsn = null;
					var xsnobj = null; ysnobj = null;
					if (typeof rows[rwind] != _UND) {
						rows[rwind].classList.toggle('alt');
						xsnobj = _(rows[rwind].id + "_0_sn");
						//xsnobj = d.querySelector("#"+rows[rwind].id+"_0_sn");
						tempsn = xsnobj.textContent;
					}
					if (typeof rows[rwind + 1] != _UND) {
						rows[rwind + 1].classList.toggle('alt');
						if (xsnobj != null) {
							ysnobj = _(rows[rwind + 1].id + "_0_sn");
							//ysnobj = d.querySelector("#"+rows[rwind + 1].id+"_0_sn");
							xsnobj.textContent = ysnobj.textContent;
							ysnobj.textContent = tempsn;
						}
					}
					rows[rwind].parentNode.insertBefore(rows[rwind + 1], rows[rwind]);
					/*  if(order == 0){
								 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
								 //console.log("Move Up");
							 }else{
								 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
								 //console.log("Move Down");
							 } */

					switching = true;

				}
				//tbl = tbl.parentNode.replaceChild(d.childNodes[0], tbl);
				//alert(tbl.id);
				switching = switching ? 'true' : 'false';
				setTimeout("SpreadSheet.IndSorting('" + tbid + "'," + 1 + "," + cellind + "," + maxrw + "," + order + "," + switching + ",'" + btnid + "')");
			} else {
				switching = false;
				_(btnid).disabled = false;
				SpreadSheet.Sortings[tbid] = false;
				if (maxrw > 20) {
					//alert(tbid);
					CoverScreen.Close(_(tbid + "_cover"));
				}
			}

		},
		Sortings: [],

		SortTable: function (tbid, colum, btn) {
			if (typeof SpreadSheet.Sortings[tbid] != _UND && SpreadSheet.Sortings[tbid] == true) { MessageBox.Show("Sheet is Busy"); return; }
			order = btn.Data('order').ToNumber();
			//console.log(order)
			if (order > 0) {
				btn.Data('order', "0");
			} else {
				btn.Data('order', "1");
			}

			//console.log("Start : "+ order);
			//console.log("*************************");
			btn.disabled = true;
			SpreadSheet.Sortings[tbid] = true;
			var cellind = colum.cellIndex;
			//d = document.createDocumentFragment();
			table = _(tbid);
			//d.appendChild(table);

			var ssobdata = table.GetDataObject();
			var ssobdatastr = ssobdata.value;
			if (ssobdatastr.Trim() == "") return;
			var maxrow = DataString.Get(ssobdatastr, "MaxDataRow").ToNumber();
			if (maxrow > 20) {
				CoverScreen.Show(tbid + "_cover", '<div>Please Wait !!!</div><div>While we sort the sheet data</div>');
			}
			//table.parentNode.removeChild(table)
			var switching = true;
			SpreadSheet.IndSorting(tbid, 1, cellind, maxrow, order, switching, btn.id);

			//alert(colum)
			//console.log(cellind + " cell - "+colum.id);
			//From w3school
			/* var table, rows, switching, i, x, y, shouldSwitch,xval,yval;
			table = _(tbid);
			//table = document.getElementById("myTable");
			switching = true;
			var ssobdata = table.GetDataObject();
		  var ssobdatastr = ssobdata.value;
		  if(ssobdatastr.Trim() == "")return;
		  var maxrow = DataString.Get(ssobdatastr,"MaxDataRow").ToNumber();
			var txtcnt = 0;
			while (switching) {
				txtcnt++;
				//if(txtcnt > 10)break;
				// Start by saying: no switching is done:
				switching = false;
				rows = table.rows;
				for (i = 1; i < maxrow; i++) {
					//for (i = 1; i < (rows.length - 2); i++) {
					// Start by saying there should be no switching:
					shouldSwitch = false;
					//console.log(rows[i].cells.length)
					x = rows[i].cells[cellind];
					y = rows[i + 1].cells[cellind];
					xfirst = x.firstElementChild
					if(xfirst.id == x.id+"_edit"){ //normal edit box
						xval = xfirst.textContent.toLowerCase();
						yfirst = y.firstElementChild;
						yval = yfirst.textContent.toLowerCase();
					}else{
						//checking for a switch cell
						xfirst = x.firstElementChild.firstElementChild;
						if(xfirst.id == x.id+"_sw"){
							xval = xfirst.Data('value');
							yfirst = y.firstElementChild.firstElementChild;
						  yval = yfirst.Data('value');
						}else{
							xval = x.textContent;
							yval = y.textContent;
						}
			}
					
					
					// Check if the two rows should switch place:
					//console.log("Order = "+ order);
					//console.log("Xval = "+ xval);
					//console.log("Yval = "+ yval);
					
	
					//console.log(x.innerHTML.toLowerCase() +" ; "+ y.innerHTML.toLowerCase());
					if ((order == 0 && xval > yval) || (order == 1 && xval < yval)) {
						//console.log("Switchable");
						// If so, mark as a switch and break the loop:
						shouldSwitch = true;
						break;
					}
				}
				if (shouldSwitch) {
					if(typeof rows[i] != _UND)rows[i].classList.toggle('alt');
		   if(typeof rows[i + 1] != _UND)rows[i + 1].classList.toggle('alt');
				 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
		   
		    
					switching = true;
				}
				//console.log("*************************");
			}
			btn.disabled = false; */
		},
		MoveRow: (row, dif) => {
			rwind = row.rowIndex;
			//alert(row.outerHTML);
			nxtrwind = rwind + dif;

			//alert(nxtrwind);
			rows = row.parentElement.parentElement.rows;
			if (typeof rows[nxtrwind] == _UND) return;
			var tempsn = null;
			var xsnobj = null; ysnobj = null;
			if (typeof rows[rwind] != _UND) {

				xsnobj = _(rows[rwind].id + "_0_sn");
				if (xsnobj == null) return;
				tempsn = xsnobj.textContent;
			}
			if (typeof rows[nxtrwind] != _UND) {

				if (xsnobj != null) {
					ysnobj = _(rows[nxtrwind].id + "_0_sn");
					if (ysnobj == null) return;
					xsnobj.textContent = ysnobj.textContent;
					ysnobj.textContent = tempsn;
				}
			}

			rows[rwind].classList.toggle('alt');
			rows[nxtrwind].classList.toggle('alt');

			var rwidarr = rows[rwind].id.split("_");
			var rwcolnum = Number(rwidarr[2]) - 1;

			var nxtrwidarr = rows[nxtrwind].id.split("_");
			var nxtrwcolnum = Number(nxtrwidarr[2]) - 1;

			//sheet  data
			var spdatastrObj = _(rwidarr[0] + "_datastring")
			//var spdatastrObj = _(sheetid+"_datastring");
			if (spdatastrObj != null) {
				//swap position
				var rwpos = DataString.Get(spdatastrObj.value, rwcolnum + "_position");
				var nxtrwpos = DataString.Get(spdatastrObj.value, nxtrwcolnum + "_position");
				SpreadSheet.SetDataString(rwcolnum + "_position", nxtrwpos, rwidarr[0]);
				SpreadSheet.SetDataString(nxtrwcolnum + "_position", rwpos, rwidarr[0]);
				if (nxtrwind > rwind) { //move down
					rows[rwind].parentNode.insertBefore(rows[nxtrwind], rows[rwind]);
				} else { //move up
					rows[rwind].parentNode.insertBefore(rows[rwind], rows[nxtrwind]);
				}
			} else {
				MessageBox.Show("Moving Row Failed");
			}

			//SpreadSheet.SetDataString(key,newval,spshetid);

		},
		//togglebanner display
		ToggleBanner: (rwnum, tbid) => {
			rwobj = _(tbid + "_rw_" + rwnum);
			if (rwobj != null) {
				if (rwobj.classList.contains('isbanner')) {
					//remove banner
					rwobj.classList.remove('isbanner');
					SpreadSheet.SetDataString((rwnum - 1) + "_banner", "#", tbid);
				} else {
					//set banner
					OptionBox.Show({
						Title: "Set Banner",
						TitleHTML: OptionBox.TextBox({ id: 'sprsheetbanner', logo: 'info-circle', title: 'Set Banner', type: 'text' }),
						Logo: "tags",
						Options: [{
							Logo: "thumbs-up",
							Title: "Continue",
							Info: "Set Banner on Row",
							Function: function (rwobj) {
								rwobj[0].title = _('sprsheetbanner_inp').value;
								rwobj[0].classList.add('isbanner');
								SpreadSheet.SetDataString((rwobj[1] - 1) + "_banner", rwobj[0].title, rwobj[2]);
							},
							Parameter: [rwobj, rwnum, tbid]
						}]
					});
				}
			}
		},
		//clear Row data
		ClearRow: function (rwnum, tbid, allow) {
			allow = typeof allow == _UND ? "" : allow;
			if (allow == "false") { MessageBox.Show("CLEARING SPREADSHEET DATA NOT ALLOWED"); return; }
			//get spreadsheet table
			var sstb = _(tbid);
			if (sstb != null) { //if exist
				//get the display columns 
				var discolstr = sstb.Data("displaycolumn");
				if (discolstr.Trim() != "") { //if display columns exist
					//break strin to get individual column 
					var columns = discolstr.split("&");
					if (columns.length > 0) {
						var allrow = true;
						//loop throug all coluums
						for (var ss = 0, lenss = columns.length; ss < lenss; ss++) {
							var indcol = columns[ss];
							//break column string to get ID and Number
							var indcolarr = indcol.split("=");
							if (indcolarr.length == 2) { //if valid
								var ID = indcolarr[0];
								var num = indcolarr[1];
								//form cell id 
								var celid = tbid + "_rw_" + rwnum + "_" + ID;
								setTimeout("SpreadSheet.ClearCell(_('" + celid + "'),true)", 1);
								/* var clll = SpreadSheet.ClearCell(_(celid),true);
								if(allrow == true){
									allrow = clll;
								} */
								//celid.__();
							}


						}
						//alert(allrow)
						if (allrow) {

							//update maxdatarow
							/* var ssobdata = sstb.GetDataObject();
								var curmaxdatarw = DataString.Get(ssobdata.value,"MaxDataRow").ToNumber();
								if(curmaxdatarw > 0){
								  ssobdata.value = DataString.Set(ssobdata.value,"MaxDataRow",curmaxdatarw - 1);
								} */
						}
					}
				}
			}
			return true;
		},
		_ClearAll: function (ssobj, allow) {
			if (allow == "false") { MessageBox.Show("CLEARING SPREADSHEET DATA NOT ALLOWED"); return; }
			if (ssobj == null || typeof ssobj == _UND) { return; }
			CoverScreen.Show("clallcs", "Working ...", "SpreadSheet._ClearAllReal(_('" + ssobj.id + "'))");

		},
		_ClearAllReal: function (ssobj) {
			//get the datastring 
			var ssobdata = ssobj.GetDataObject();
			var ssobdatastr = ssobdata.value;
			if (ssobdatastr.Trim() == "") return;
			var maxrow = DataString.Get(ssobdatastr, "MaxDataRow").ToNumber();
			if (maxrow > 0) {
				for (var dr = 1; dr <= maxrow; dr++) {
					var clear = SpreadSheet.ClearRow(dr + 1, ssobj.id);
				}
			}

			CoverScreen.Close(_("clallcs"));
		},
		//get column ID
		ColumnID: function (cellobj) {
			var celleditidarr = cellobj.id.split("_");
			if (celleditidarr[celleditidarr.length - 1].Trim() == "edit") {//if edidable cell div sent
				return celleditidarr[celleditidarr.length - 2];
			} else {
				return celleditidarr[celleditidarr.length - 1];
			}
		},
		//get table id
		TableID: function (cellobj) {
			var celleditidarr = cellobj.id.split("_");
			return celleditidarr[0];
		},
		//ceck if supplied cell is dropdown
		IsDropDown: function (obj) {
			var columnid = SpreadSheet.ColumnID(obj);
			//var columnid = celleditidarr[celleditidarr.length - 2];
			var drpdowndata = _(columnid + "_inner").Data("dropdown").Trim();
			if (drpdowndata == "") { //if not dropdown cell
				return false;
			}
			return true;
		},
		KeyPress: function (obj, e) {
			if (window.event) { // IE                 
				keynum = e.keyCode;
			} else if (e.which) {
				// Netscape/Firefox/Opera                   
				keynum = e.which;
			}
			//alert(keynum);
			//var celleditid = obj.id;
			/*var celleditidarr = obj.id.split("_");
			var columnid = celleditidarr[celleditidarr.length - 2];
			var drpdowndata = _(columnid+"_inner").Data("dropdown").Trim();*/
			if (!SpreadSheet.IsDropDown(obj)) { //if not dropdown cell
				if (obj.Text() != obj.Data("value")) {
					obj.Data("value", obj.Text());
					//SpreadSheet.ClearRequired(obj);
				}
			} else {
				//if a dropdown cell and contain text and the key press is enter
				if (obj.Text().Trim() != "" && keynum == 13) {
					//alert(keynum);
					//set the value
					//get the next cell
					//var objnxt = SpreadSheet.GetNextCell(obj);
					//objnxt.focus();
					//return;
				}
				//alert(obj.Text());
			}
			/*keynum = (typeof keynum != "undefined")?keynum:0;
			var char = String.fromCharCode(keynum);
			var unicode=e.keyCode? e.keyCode : e.charCode;
			if(unicode == 9){//tab button clicked
			//Tracer.Start("Tab Pressed");
			//("Tab Pressed in: " + obj.id).__();
				 if(!e.shiftKey){
				var nxtcell = SpreadSheet.GetNextCell(obj);
				 }else{
					var nxtcell = SpreadSheet.GetPrevCell(obj); 
				 }
				//("Next Available Cells is: " + nxtcell.id).__();
				if(!Null(nxtcell)){
					if(!nxtcell.CellSelected()){
						nxtcell.click();
						//("New Cell Clicked to select cos is currently not selected: " + nxtcell.id).__();
					}
				}
			}*/
			//e.shiftKey.toString().__();
			//(char+" = " + unicode + " ; cell = " + obj.id).__();
			return false;
		}, GetNextCell: function (currentcell) {// make use of cell index to determin nexet
			var cellid = currentcell.id; //the current element id(supose to be the editable div in the cell)
			if (cellid == _UND) return null; //if no id set return null
			var celldet = cellid.split("_"); //split id to get the various comp-onent of the id
			if (celldet.length < 4) return null; //if total component is less thean 4, meaning the id is invalid return null
			var tbid = celldet[0]; //the table id
			var rwnum = celldet[2]; //the initial creation row number
			var clnum = celldet[3]; // the initial column number
			var editdiv = typeof celldet[4] != _UND ? "_edit" : ""; //the edit string identifier, to show that is the editable div of the cell
			var currcell = typeof celldet[4] != _UND ? currentcell.parentElement : currentcell;
			//var editable = typeof celldet[4] != _UND?currentcell:currentcell.firstElementChild;

			//var currcell = _(tbid + "_rw_" + rwnum + "_" + clnum); //form the cell id proper, and get the cell
			if (Null(currcell)) return null; //if the cell does not exist return null
			var currRow = currcell.parentNode;
			if (Null(currRow)) return null;


			var totcells = currRow.cells.length;
			var currcelIndex = currcell.cellIndex; //get the current cell index of the cell

			var nextcolIndex = currcelIndex + 1;
			var totAvailableCells = totcells - 1; //subtracting the left and right header cell
			if (nextcolIndex < totAvailableCells) {//if cells still available
				if (currRow.cells[nextcolIndex].firstElementChild.contentEditable == false) {
					return SpreadSheet.GetNextCell(currRow.cells[nextcolIndex]);
				} else {
					return currRow.cells[nextcolIndex];
				}

			} else {
				var tb = _(tbid);
				//currRow.id.__();
				if (Null(tb)) return null;
				var currrowIndex = currRow.rowIndex; //get the cells row index
				var totrows = tb.rows.length;
				var totAvailableRows = totrows - 1//subtract the up and down header
				var nextRowInd = currrowIndex + 1;
				if (nextRowInd < totAvailableRows) {//if next row exist
					if (tb.rows[nextRowInd].cells[1].firstElementChild.contentEditable == false) {
						return SpreadSheet.GetNextCell(tb.rows[nextRowInd].cells[1]);
					} else {
						return tb.rows[nextRowInd].cells[1]; //return the first editable cell of the next row
					}

				} else { //if no more row
					//create new row
					//("Table id: "+tb.id).__();
					var nwrw = SpreadSheet.AddRow(tb);
					//("New Row id: "+nwrw.id).__();
					var firstcell = nwrw.cells[1];
					//document.getElementById().firstChild
					//var firstcellid = firstcell.id;
					//("New Row first cell id: "+firstcellid).__();
					//firstcellid.__();
					/*var fchild = firstcell.firstChild;
					if(!Null(fchild)){fchild.focus()}*/
					firstcell.focus();
					return firstcell;
				}
			}
			/*var td = _(tbid);
			var totrw = td.rows.length;
			var totcol = td.rows[0].cells.length;
			if(currcelIndex + 1 < totcol - 1){ //if not last cell of the row
				return td.rows[rwnum - 1].cells[currcelIndex + 1];
			}else{ //if last editable cell of the row
				if(rwnum + 1 > totrw - 1){ //add a new row and return the first cell
					var nwrw = SpreadSheet.AddRow(td);
					if(editdiv != ""){
						nwrw.focus()
					}else{
						_(nwrw.id+"_edit").focus();
					}
					return nwrw.cells[1];
					//return nwrw.cells[1]; //retuen the first editable cell
				}
				return td.rows[rwnum].cells[1];
			}*/


		}, GetPrevCell: function (currentcell) { //work on get prev cell to use thesame logic as get next
			var cellid = currentcell.id; //the current element id(supose to be the editable div in the cell)
			if (cellid == _UND) return null; //if no id set return null
			var celldet = cellid.split("_"); //split id to get the various comp-onent of the id
			if (celldet.length < 4) return null; //if total component is less thean 4, meaning the id is invalid return null
			var tbid = celldet[0]; //the table id
			var rwnum = celldet[2]; //the initial creation row number
			var clnum = celldet[3]; // the initial column number
			var editdiv = typeof celldet[4] != _UND ? "_edit" : ""; //the edit string identifier, to show that is the editable div of the cell
			var currcell = _(tbid + "_rw_" + rwnum + "_" + clnum); //form the cell id proper, and get the cell
			if (Null(currcell)) return null; //if the cell does not exist return null
			var currRow = currcell.parentNode;
			if (Null(currRow)) return null;


			var totcells = currRow.cells.length;
			var currcelIndex = currcell.cellIndex; //get the current cell index of the cell

			var nextcolIndex = currcelIndex - 1;
			//var totAvailableCells = totcells - 1; //subtracting the left and right header cell
			if (nextcolIndex > 0) {//if cells still available
				return currRow.cells[nextcolIndex]
			} else {
				var tb = _(tbid);
				//currRow.id.__();
				if (Null(tb)) return null;
				var currrowIndex = currRow.rowIndex; //get the cells row index
				//var totrows = tb.rows.length;
				//var totAvailableRows = totrows - 1//subtract the up and down header
				var nextRowInd = currrowIndex - 1;
				if (nextRowInd > 0) {//if next row exist
					return tb.rows[nextRowInd].cells[totcells - 2]; //return the first editable cell of the next row
				} else { //if no more row
					return null;
				}
			}

		}, GetCellEditable: function (cell) {

			//("Gotten Editable Div: " + cell.id+"_edit").__();
			return _(cell.id + "_edit");
		}, CellFocus: function (cell) {
			/*Tracer.Start("Focus Issue");
			("Current Focus Cell: " + cell.id).__();
			SpreadSheet.GetCellEditable(cell).focus();
			("Focus set for: " + cell.id+"_edit").__();*/
		}, CellSelect: function (cell) { //spreadsheet cell onselect handler
			//console.log('select');
			// (cell.id+": Focus").__();
			var cellid = cell.id;
			//("Cell id: "+cellid).__();
			var cellidarr = cellid.split("_");
			//get the table object
			var sprtb = _(cellidarr[0]);
			if (sprtb == null) return; //invalid eduporta spreadsheet
			var columnid = cellidarr[3];
			var rcell = _(cellidarr[0] + "_rw_" + cellidarr[2] + "_" + cellidarr[3]);
			var colinner = _(columnid + "_inner");
			var isdrpdwn = false;
			var drpdwnData = "";
			var cellHeader = "OPTIONS";
			var multi = 'false';
			if (colinner != null) {
				// alert(colinner.outerHTML);
				drpdwnData = colinner.Data("dropdown");//cellheader
				cellHeader = colinner.Data("cellheader").Trim();

				multi = colinner.Data("multi").Trim();
				if (drpdwnData != "") {
					isdrpdwn = true;
				}
			}

			// ("Column id: "+columnid).__();
			//if current columnid == faculty or dept or dob or state or programe or moe or gender or studytype
			// if(columnid == "Fac" || columnid == "Dept" || columnid == "DOB" || columnid == "StateId" || columnid == "ProgID" || columnid == "ModeOfEntry" || columnid == "Gender" || columnid == "StudyID" ){

			//Manage Popups Hidding
			var ownseen = false;
			var alrpopup = document.getElementsByClassName('popup');
			if (alrpopup.length > 0) {

				for (var p = 0, lenp = alrpopup.length; p < lenp; p++) {
					if (alrpopup[p].style.display == "block") {
						if (alrpopup[p].id == ("popup" + rcell.id) && multi == "true") {
							ownseen = true;
							continue;
						}
						alrpopup[p].PopOut();
					}
				}
			}


			if (isdrpdwn) {

				//get the value holder hidden input element
				var inpval = _(rcell.id + "_dval");
				if (Null(inpval)) {
					inpval = document.createElement("input");
					inpval.id = rcell.id + "_dval";
					inpval.type = "hidden";
					rcell.appendChild(inpval);
				}
				/*var $knwn = false;
				if(drpdwnData.substr(0,1) == "?"){ //if required loading from databse
					drpdwnData = drpdwnData.substr(1);
					var drparr = drpdwnData.ToDataArray();
					 var c= typeof drparr['c'] == _UND?"1=1":drparr['c'];
					 var k= typeof drparr['k'] == _UND?"":drparr['k'];
					 var v= typeof drparr['v'] == _UND?"":drparr['v'];
					 var t= typeof drparr['t'] == _UND?"":drparr['t'];
					 var h= cellHeader.toUpperCase();
				   // var k="";v="";t="";h="";
				}else{*/
				var kn = drpdwnData;
				// $knwn = true;
				var h = cellHeader.toUpperCase();
				// }
				//Check if dynamic Parameter
				var replArr = new Array();
				var niddArr = new Array();

				//*********************** */
				var columnsData = sprtb.Data("displaycolumn");
				//alert(columnsData);
				//get all colomn current values
				var ColVal = {};
				if (columnsData.Trim() != "") {
					var ColValarr = columnsData.split("&");
					if (ColValarr.length > 0) {

						for (var c = 0, lenc = ColValarr.length; c < lenc; c++) {
							var indcol = ColValarr[c];
							//break down to get the column Name and column index
							var indcolarr = indcol.split("=");
							if (indcolarr.length < 1 || indcolarr[0].Trim() == "") continue;
							var indcolName = indcolarr[0];
							//get the current row cell (inner editable div, which carries the value)
							var rwcell = _(cellidarr[0] + "_rw_" + cellidarr[2] + "_" + indcolName + "_edit");
							if (rwcell == null) continue;
							//get the entered/selected value 
							var evalue = rwcell.Data("value");
							var txt = _(indcolName + "_inner").Text();
							//keep the value, to be used in server script
							ColVal[indcolName] = [evalue, txt];

						}
					}
				}

				//*********************** */

				//check if query
				/* if(drpdwnData.substr(0,1) == "#"){ //if query
					//get all table column - data-displaycolumn
					
					
					var fseen = -1;
				   for(var d=0; d<drpdwnData.length ; d++){
					   var char = drpdwnData.charAt(d);
					   
					   if(char == "?"){
						   if(fseen > -1){ //if seen first
							 //get string inbetween
							  //alert(d);
							 var instr = drpdwnData.substr(fseen+1,d-1-fseen);
							 //check if column exist
							 if(_(instr+"_inner") != null){ //if column exist
								 //get the current row cell (inner editable div, which carries the value)
								 var rwcell = _(cellidarr[0]+"_rw_"+cellidarr[2]+"_"+instr+"_edit");
								 if(rwcell != null){
									 //get the entered/selected value 
									 var evalue = rwcell.Data("value");
									 if(evalue.Trim() == ""){
										MessageBox.Show("#"+_(instr+"_inner").Text()+" Cell is Required");
										return;
									 }else{
										 //add to replace and niddle array
										replArr[replArr.length] = evalue;
										niddArr[niddArr.length] = "?"+instr+"?";
									 }
								 }else{
									 MessageBox.Show("#Required Cell Not Found");
									 return;
								 }
							 }
							 fseen = -1; //reset fseen to continue looking for another
						   }else{ //seen for the first time
							  
						   fseen = d;
						   }
					   }
				   }
				   //form new string
				   if(replArr.length > 0){
					   for(var u=0; u<replArr.length; u++){
						   var replc = replArr[u];
						   var niddle = niddArr[u];
						   drpdwnData = drpdwnData.replace(niddle,replc);
					   }
				   }
				   //alert(drpdwnData);
				} */
				//document.getElementsByClassName

				if (ownseen) {
					//if the current cell popout is still displayed and it is a multiselect popup, leave it open, so as to allow multi selection
					return;
				}
				//var title = (multi == "true")?"":"";
				var popdiv = PopUp.Create(rcell, "Select");

				popdiv.SetStyle("margin:0px;min-width:100px");
				var popcont = popdiv.GetPopContainer();
				popcont.SetStyle("text-transform:uppercase");
				popcont.innerHTML = "<div style=\"width:100%;text-align:center;margin-top:20px\">" + "sync fa-spin".Icon() + " </div>";
				//(popdiv.id+": PopIn").__();

				/* if(columnid == "DOB"){ //if dob just display the format
					 popcont.innerHTML = "<div class=\"DOBpopupFormat\">FORMAT: <span>DD</span>/<span>MM</span>/<span>YYYY</span></div><div  class=\"DOBpopupFormat\">EXAMPLE: <span>25</span>/<span>03</span>/<span>1995</span></div>";
					 return;
				 }*/
				// if($knwn){
				//alert(drpdwnData);
				if (SpreadSheet.PopupLoadAjax != null) {

					SpreadSheet.PopupLoadAjax.abort();
					if (SpreadSheet.PopupLoadAjax.Param != null) {
						var loaddiv = _(SpreadSheet.PopupLoadAjax.Param + "_l");
						if (!Null(loaddiv)) {
							loaddiv.Hide();

						}
					}
					SpreadSheet.PopupLoadAjax.Param = null;
				}
				var src = configdata.Core + "cportal/Pages/Scripts/Student/Preloader/loadpopup.php?id=" + rawescape(popdiv.id.Replace("_", "")) + "&knw=" + rawescape(drpdwnData) + "&h=" + h + "&columns=" + rawescape(JSON.stringify(ColVal)) + "&multi=" + multi + "&column=" + rawescape(columnid) + "&SubDir=" + encodeURIComponent(configdata.SubDir);
				//alert(src);
				// }else{
				// var src = "Pages/Scripts/Student/Preloader/loadpopup.php?id="+rawescape(popdiv.id.Replace("_",""))+"&k="+k+"&v="+v+"&t="+t+"&c="+rawescape(c)+"&h="+rawescape(h);

				// }
				// src.__();
				//PopUp.PopIn();
				SpreadSheet.PopupLoadAjax = popcont.HTML(src, function (obj, url, param, res) {
					//(obj.id + ": Loaded").__();
					var popid = obj.id.substr(0, obj.id.length - 5);
					if (res.Trim() != "") {
						var popup = _(popid);
						popup.PopIn();
					} else {
						//hide the loading elem
						var ld = _(popid + "_l");
						if (ld != null) ld.Hide();
					}



				});
				SpreadSheet.PopupLoadAjax.Param = popdiv.id;


			}
			SpreadSheet.SelectText(cell);
		},
		PopupLoadAjax: null,
		SelectText: function (el) {
			var range = document.createRange();
			range.selectNodeContents(el);
			var sel = window.getSelection();
			sel.removeAllRanges();
			sel.addRange(range);
		}
		, CellUuSelect: function (cell) { //onblur

			var cellid = cell.id; //get the cell(editable div) id
			//("Cell id: "+cellid).__();
			var cellidarr = cellid.split("_"); //break id down to get individual id component
			var columnid = cellidarr[3]; //the column id/name
			//get the real table cell of the editable div
			//var rcell = _(cellidarr[0]+"_rw_"+cellidarr[2]+"_"+cellidarr[3]);
			var rcell = cell.parentElement;

			//get the popup div of the cell
			var popupdiv = _("popup" + rcell.id);


			if (popupdiv == null) { //if not dropdown cell
				//alert('Not Drop Down');
				SpreadSheet._SetMaxDataRow(cell);
				cell.textContent = SpreadSheet._CleanData(cell.textContent);
				//update the data value to the cell text content incase there is a changes
				cell.Data("value", cell.textContent);// for non popup cell the display content must be equal to the value content
				return SpreadSheet.UpdateDataString(cell);
			}
			var datastrid = popupdiv.id.Replace("_", "");
			var popuptbData = _("data_" + datastrid);
			// alert("popup");
			//if drop down cell
			if (Null(popuptbData) || (!Null(popuptbData) && popuptbData.Data('multiselect') != "true")) {
				//console.log(popuptbData.Data('multiselect'));
				setTimeout("_('" + popupdiv.id + "').PopOut()", 100);
			}

			//get the popup table datastring
			var datastrobj = _(datastrid + "_data");
			// alert(datastrid.id);
			if (!Null(datastrobj)) {
				// (datastrobj.value).__();
				//convert to array
				var dataarr = datastrobj.value.ToDataArray();

				//("Data Str: "+datastrobj.value).__();
				var txt = cell.textContent.Trim();
				var re = new RegExp(String.fromCharCode(160), "g");
				txt = txt.replace(re, ' ');
				//txt = txt.Replace('&nbsp;', ' ');
				//console.log(txt);
				//alert(columnid+" - Gotten Text:"+txt.Replace(" ","_"));
				//("Text Content: "+txt).__();
				//var txtarr = txt.split(":");
				if (txt != "") {
					//form the array of user typed text, so as to cater for both multi and single
					var txtidarr = (!Null(popuptbData) && popuptbData.Data('multiselect') == "true") ? txt.split(",") : [txt];

					var ftextarr = [];
					var tvalarr = [];
					var curtxtval = cell.Data("value");
					//console.log("Current Value:"+curtxtval);
					var valarr = curtxtval.Trim(":").split("::");
					for (var tt = 0, lentt = txtidarr.length; tt < lentt; tt++) {
						var txtid = txtidarr[tt].Trim();
						//console.log("Current Val in array: "+txtid);
						//alert(columnid+" - Gotten Text in loop:"+txtid);
						if (typeof dataarr[txtid] != _UND) { //if user supplied the id
							//alert(columnid+" - ID Entered:"+txtid+" ; Values:"+dataarr[txtid]);
							//("text value: "+dataarr[txtid]).__();
							ftextarr[ftextarr.length] = dataarr[txtid]
							tvalarr[tvalarr.length] = txtid
							//console.log("Value Found:"+dataarr[txtid]);
							//cell.textContent = dataarr[txtid];
							//set the value

							//_(cellidarr[0]+"_rw_"+cellidarr[2]+"_"+cellidarr[3]+"_edit").Data("value",txtid);						
						} else { //if user entered the value text
							//							//check if exist in val array
							//flip array
							var dataarrflip = dataarr.Flip();
							//console.log(JSON.stringify(dataarrflip));
							//var gid=Object.keys(dataarr).find(key => dataarr[key] === txtid);
							//alert("Tuition Fee-"+txtid);
							//var ss='Tuition Fee';
							var gid = dataarrflip[txtid];
							//	alert(columnid+" - Text Key:"+gid);
							if (typeof gid != _UND) {
								ftextarr[ftextarr.length] = dataarr[gid]
								tvalarr[tvalarr.length] = gid;
							}
							//console.log("Text Found:"+txtid);
							//alert(gid);
							/* var inde = valarr.indexOf(gid);
							if(inde > -1){ //if exist
								tvalarr[tvalarr.length] = gid;
								ftextarr[ftextarr.length] = txtid;
							} */

							/* var val = cell.Data("value"); //cell value
							if(val.Trim() != ""){ //if value exist
							
							if(typeof dataarr[val] != _UND){ //if current or set id exist
								//dataarr[val].__();
								cell.textContent = SpreadSheet._CleanData(dataarr[val]); //get the text and set it
							}else{ //if not exist, clear the screen
								cell.textContent = "";
								cell.Data("value","");
								SpreadSheet.ClearRequired(rcell);
							}
							}else{ //else if no value found clear the display text
								cell.textContent = "";
							} */
							//var newarr = dataarr.indexOf("a");
							//alert(newarr);

						}
					}
					var ntxt = ftextarr.join(",");
					//alert(columnid+":"+ntxt);
					cell.textContent = ntxt;
					var vtxt = tvalarr.length == 1 ? tvalarr[0] : ":" + tvalarr.join("::") + ":";
					//alert(columnid+":"+vtxt);
					//if changes exist
					if (curtxtval != SpreadSheet._CleanData(vtxt)) {
						cell.Data("value", SpreadSheet._CleanData(vtxt));
						SpreadSheet.ClearRequired(rcell);
					}

					//("text id: "+txtid).__();
					/* //form array of selected values
							var valarr = val.Trim(":").split("::");
							for(var dd=0;dd<valarr.length;dd++){
								var rval = valarr[dd];
								if(typeof dataarr[rval] != _UND){ 
									ftextarr[ftextarr.length]
								}
							} */
				} else {
					cell.Data("value", "");
					SpreadSheet.ClearRequired(rcell);
				}

			} else {
				//(datastrid + "_data: Not found").__(); 
			}

			//alert(cell);
			SpreadSheet._SetMaxDataRow(cell);

			return SpreadSheet.UpdateDataString(cell);
		},
		//*Preloader.PopListUnSelect *Preloader.PopupList *Preloader.DropDownList
		PopListUnSelect: function (obj) {

			//get the click(unselect) text and valuue
			var txt = obj.Text(); //the text content of the sellected cell

			var txtarr = txt.split(":");
			var val = txtarr[0].Trim();
			txtarr[0] = "";
			var ntxt = txtarr.join(":").Trim().TrimLeft(":").Trim();
			//remove from display txt in cell

			//get the popup cell
			var popid = obj.id.split("_")[0];
			// ("popupid id: "+popid).__();
			var popuptb = _(popid);
			var cell = popuptb.parentNode.parentNode.parentNode.parentNode;
			var editdiv = cell.firstElementChild;

			var selval = editdiv.Data("value").Trim();
			var seltxt = editdiv.textContent;
			//alert(selval + "=>" + seltxt);
			//remove from value
			selval = selval.substr(0, 1) == ":" ? selval.replace(":" + val + ":", "") : selval.replace(val, "").Trim();

			//remove in text
			seltxt = (":" + seltxt.split(",").join("::") + ":").replace(":" + ntxt + ":", "").TrimLeft(":").TrimRight(":").split("::").join(",");
			//alert(":"+ntxt+":");
			//var rrr = ":"+seltxt.split(",").join("::")+":"
			//alert(rrr +" => "+ ":"+ntxt+":");
			//reset the value
			editdiv.Data("value", selval);
			//reset the text 
			editdiv.textContent = seltxt;
			//console.log(val +" = "+ntxt);
			//console.log(editdiv.Data("value") +" = "+editdiv.textContent);
			//console.log(selval +" = "+seltxt);

		},
		//*Preloader.PopListSelect *Preloader.PopupList *Preloader.DropDownList
		PopListSelect: function (obj) {
			//salert('aaa');
			var rwid = obj.id; //the id of the selected cell
			// ("selected cell id: "+rwid).__();
			var popid = rwid.split("_")[0];
			// ("popupid id: "+popid).__();
			var popuptb = _(popid);
			var datainp = _("data_" + popid);
			var multi = typeof datainp != _UND ? datainp.Data("multiselect") : "false";
			if (popuptb == null) return;
			var cell = popuptb.parentNode.parentNode.parentNode.parentNode;//popuptable . popup container div . popup inner div . popup div . cell

			if (cell != null) {

				//alert(onchanged);
				//breakdown id
				var cellidarr = cell.id.split("_");
				var columnid = cellidarr[3];
				//check if fac select  Student.PreLoader.ClearRequired(inpuvaldept);

				//var editdiv = _(cell.id+"_edit");
				var editdiv = cell.firstElementChild;
				var curval = editdiv.Data("value");

				var txt = obj.Text(); //the text content of the sellected cell
				var txtarr = txt.split(":");

				//("selected cell content: "+txt).__();
				/*var userid = "inp_"+rwid; //get the user defined id input element id
				//var selstate = _("inpsel_"+rwid).value;
				//("selected cell userid hidden element id: "+userid).__();
				var userID = _(userid).value; //grt the user defined id for the cell
				
				//editdiv.textContent = txt;
				//alert(txt);
				inpuval = _(cell.id+"_dval");
				var val = ""
				  if(!Null(inpuval)){
					  inpuval.value = userID.split("_")[0];
					  val = inpuval.value
				  }*/

				if ((txtarr[0].Trim() != curval && multi != "true") || multi == "true") { //if selection changed
					if (multi == "true") { //cocatinate for multiple selection

						editdiv.Data("value", curval + ":" + SpreadSheet._CleanData(txtarr[0].Trim()) + ":");
					} else {
						editdiv.Data("value", SpreadSheet._CleanData(txtarr[0].Trim()));
					}

					var nowval = txtarr[0];
					txtarr[0] = "";
					var ntxt = txtarr.join(":").Trim().TrimLeft(":");
					if (multi == "true") { //cocatinate for multiple selection
						//console.log("Current Text:" + editdiv.textContent);
						editdiv.textContent = editdiv.textContent.Trim() == "" ? SpreadSheet._CleanData(ntxt.Trim()) : editdiv.textContent + "," + SpreadSheet._CleanData(ntxt.Trim());
						//console.log("After Text:" + editdiv.textContent);
					} else {
						editdiv.textContent = SpreadSheet._CleanData(ntxt.Trim());
					}
					if (curval != editdiv.Data("value")) { //if changes exist
						SpreadSheet.ClearRequired(cell);
						//run the onchange method if exist
						var celltable = cell.parentElement;
						while (celltable.tagName.toLowerCase() != "table") {
							celltable = celltable.parentElement;
						}
						var onchanged = celltable.Data("onchange");
						//alert(onchanged);
						//if(onchanged != "")eval(onchanged+"(_('"+cell.id+"'),'"+nowval+"')");
						if (onchanged != "") setTimeout(onchanged + "(_('" + cell.id + "'),'" + nowval + "')", 1);
					}
				}

				SpreadSheet._SetMaxDataRow(cell);
				SpreadSheet.UpdateDataString(editdiv);

				if (multi == "false") {
					var nxtCell = SpreadSheet.GetNextCell(cell); //get the next cell
					if (nxtCell != null) { //if it exist
						//var nxteditdiv = _(nxtCell.id+"_edit"); //get the editable div
						var nxteditdiv = nxtCell.firstElementChild; //get the editable div
						//document.getElementById().firstElementChild
						if (nxteditdiv != null) {
							nxteditdiv.focus(); //set focus
							return false;
						}
					}
				}

				//editdiv.focus();
				//("selected cell user id: "+userID).__();
			}
			/* var cellidstr = popid.substr(5);
			// ("popup cell id: "+cellidstr).__();
			 var cellidarr = cellidstr.split("rw");
			 var ssobjid = cellidarr[0];
			  //("spreadsheet id: "+ssobjid).__();
			  var rowcol = cellidarr[1];
			  
			  rownum = parseInt(rowcol);
			 // ("Cell row num: "+rownum).__();
			  colunmid = rowcol.TrimLeft(rownum + "");
			 // ("Cell Column Id: "+colunmid).__();
			 cell = _(ssobjid + "_rw_" + rownum+ "_" + colunmid);
			 if(Null(cell))return;*/

			//alert(rwid);
			editdiv.focus();
			return false;
		},
		//clean data by removing keyword (#~# , *~*)
		_CleanData: function (data) {
			return data.Replace("#~#", "").Replace("*~*", "");
		},
		//*Preloader.ClearRequired *PreLoader.ClearCell
		ClearCell: function (pogcell, clreq, force) { //function to clear the spread sheet field data
			force = typeof force == _UND ? false : force; //determine if cell must be cleared
			clreq = typeof clreq == _UND ? true : clreq; //determine if required cell are to be cleard

			//var cellidarr = pogcell.id.split("_");
			// var pogcell = _(cellidarr[0]+"_rw_"+cellidarr[2]+"_ProgID");//get the programme cell
			if (pogcell == null) { return false; }
			/* var inpuvalpog = _(pogcell.id+"_dval");
			 if(Null(inpuvalpog) || inpuvalpog.value == ""){
		  	
			}else{//if selected value exist clear it
				 inpuvalpog.value = "";*/
			var edita = _(pogcell.id + "_edit");
			if (edita != null) {
				var dataval = edita.Data("value");
				if ((edita.contentEditable.Trim() == "true" || force == true) && (dataval != "" && edita.textContent != "")) {
					//clear if cell is an editable or force is true and if the cell is not empty
					//("Clearing "+pogcell.id).__();
					edita.textContent = "";
					edita.Data("value", "");
					//alert(edita.keyUp);
					if (clreq) {
						SpreadSheet.ClearRequired(pogcell);
					}
					var updt = SpreadSheet.UpdateDataString(edita);
					return true
				}
			} else {
				var sw = _(pogcell.id + "_sw");
				if (sw != null) {
					sw.SwitchOff();
					sw.Data("value", 0);
					var updt = SpreadSheet.UpdateDataString(sw);
					return true

				}
			}
			return false;
			//}
			//alert(edita.id);

		},
		//clear required generic
		ClearRequired: function (maincell) {
			// ("Clearing Required of"+maincell.id).__();
			var idarr = maincell.id.split("_");
			if (maincell != null) {
				var columnid = SpreadSheet.ColumnID(maincell); //get the cell column ID
				//("Clearing Cell ColumnID"+columnid).__();
				var dependables = _(idarr[0]).Data("dependables"); //get the spreadsheet dependables(required) data string
				if (dependables != "") {
					//("SPS Dependables = "+dependables).__();
					var dependablesarr = dependables.ToDataArray(); //convert to array 
					if (typeof dependablesarr[columnid] != _UND && dependablesarr[columnid] != "") {
						//("Dependables Found").__();
						//get the depending column name
						var dependinColumnID = dependablesarr[columnid];
						//(columnid+" Dependables => "+dependablesarr[columnid]).__();
						var multidepe = dependinColumnID.split("~"); //if multiple column depends on the maincolumn
						for (var ss = 0, lenss = multidepe.length; ss < lenss; ss++) {
							var dependinccell = _(idarr[0] + "_rw_" + idarr[2] + "_" + multidepe[ss]);

							if (dependinccell != null) {
								//("Clearing Dependable => "+dependinccell.id).__();
								SpreadSheet.ClearCell(dependinccell, true, true);
							}
						}

					}
				}
			}
		},
		//set maxdatarow
		_SetMaxDataRow: function (cell) {
			//alert(cell);
			var cellidarr = cell.id.split("_"); //get id breakdown
			var celleditdiv = cellidarr.length == 5 ? cell : _(cell.id + "_edit"); //get the editable div of the cell
			if (celleditdiv.textContent != "") { //if contain text
				var rwnum = cellidarr[2].ToNumber(); //get the row number
				var SpreadS = _(cellidarr[0]); //get the spreadseet (table)
				if (SpreadS != null) { //if stradsheet exist
					var curmaxrow = SpreadS.Data("maxdatarow").ToNumber();
					if (rwnum > curmaxrow) { //if cell row is greater than cur max data row
						SpreadS.Data("maxdatarow", rwnum - 1); //set as new maxdata row
						var spdatastrObj = _(cellidarr[0] + "_datastring");
						var dtstr = spdatastrObj.value;
						spdatastrObj.value = DataString.Set(dtstr, "MaxDataRow", rwnum - 1);
					}
				}
			}
		},
		//get sheet data 
		_SheetData: function (spreadsObj) {

		},
		//update sheet datastring
		UpdateDataString: function (cell) {
			//console.log(cell);
			var idarr = cell.id.split("_");
			//console.log(cell);
			var spshetid = idarr[0];
			var rownum = idarr[2].ToNumber() - 1;
			var colnum = cell.Data("column");
			var key = rownum + "_" + colnum;
			var newval = cell.Data("value");
			if (newval == null || newval.Trim() == "") newval = cell.textContent.Trim();
			//console.log(key + " => "+newval);
			SpreadSheet.SetDataString(key, newval, spshetid);
			/* 	//check if exist in Update Flag
		if(typeof SpreadSheet.UpdateFlag[spshetid] != _UND && SpreadSheet.UpdateFlag[spshetid] == true){
					//curently busy
		  //keep in waitinglog
		   if(typeof SpreadSheet.WaitingLog[spshetid] == _UND){
						 SpreadSheet.WaitingLog[spshetid] = [[key,newval]];
					 }else{
SpreadSheet.WaitingLog[spshetid] = [[key,newval]];
					 }
				}
			 var spdatastrObj = _(idarr[0]+"_datastring");
			 
			 if(newval.Trim() == "")newval = cell.textContent.Trim();
			// if(newval == ""){return true;}
			 if(spdatastrObj != null){
				// var datastr = spdatastrObj.value;
				 
				
				 spdatastrObj.value = DataString.Set(spdatastrObj.value,rownum +"_"+ colnum,newval); 
				//alert(spdatastrObj.value);
			 }

			 return true;*/
		},
		SetDataString: function (key, newval, sheetid, force) {
			force = force || false;
			//var key = rownum +"_"+ colnum;
			//var newval = cell.Data("value"); 
			//check if exist in Update Flag
			if (typeof SpreadSheet.UpdateFlag[sheetid] != _UND && SpreadSheet.UpdateFlag[sheetid] == true && force == false) {
				//curently busy
				//keep trying untill its freed
				if (typeof SpreadSheet.WaitingLog[sheetid] == _UND) SpreadSheet.WaitingLog[sheetid] = [];
				SpreadSheet.WaitingLog[sheetid].push([key, newval]);
			} else { //if it is free
				//set the working flag
				SpreadSheet.UpdateFlag[sheetid] = true;
				//perform update
				var spdatastrObj = _(sheetid + "_datastring");
				if (spdatastrObj != null) {

					spdatastrObj.value = DataString.Set(spdatastrObj.value, key, newval);
					//console.log(key+"="+newval);
					//console.log(spdatastrObj.value);
				}
				//check if there is waiting update
				if (typeof SpreadSheet.WaitingLog[sheetid] != _UND && SpreadSheet.WaitingLog[sheetid].length > 0) {
					//get the latest in quee
					var latext = SpreadSheet.WaitingLog[sheetid].shift();
					//perform update
					SpreadSheet.SetDataString(latext[0], latext[1], sheetid, true);
				} else { //if no more update waiting
					//release the object
					SpreadSheet.UpdateFlag[sheetid] = false;
				}
			}
		},
		_GetDisplayColumns: function (spsheet) {
			return spsheet.Data("displaycolumn");
		},
		SwicthChange: function (obj) {

			if (typeof obj == _UND) return;
			var id = obj.id;
			var idarr = id.split("_");
			var spdatastrObj = _(idarr[0] + "_datastring");
			//alert(idarr[0]);
			if (spdatastrObj != null) {
				var newval = obj.GetStatus();
				//var datastr = spdatastrObj.value;
				var rownum = idarr[2].ToNumber() - 1;
				var colnum = obj.Data("column");
				obj.Data("value", newval);
				//alert(newval);
				// alert(rownum +"_"+ colnum+" => "+newval);

				/* console.log("Before");
					console.log(spdatastrObj.value); */
				spdatastrObj.value = DataString.Set(spdatastrObj.value, rownum + "_" + colnum, newval);
				/* console.log("After");
				console.log(spdatastrObj.value); */

			}
		}

	}

}();
Object.prototype.GetDisplayColumns = function () { return SpreadSheet._GetDisplayColumns(this) }
Object.prototype.GetDataString = function () { return _(this.id + "_datastring").value }
Object.prototype.GetDataObject = function () { return _(this.id + "_datastring") }
Object.prototype.ClearSpreadSheet = function (allow) { SpreadSheet._ClearAll(this, allow) }
var PopUp = {
	Create: function (parent, title) {
		var popdiv = document.createElement("div");
		parent = (typeof parent == _UND || Null(parent)) ? document.body : parent;
		var dt = new Date();
		var popupid = (typeof parent.id == _UND || parent.id == "") ? "popup" + dt.getTime() : "popup" + parent.id;
		if (!Null(_(popupid))) { _(popupid + "_l").Show(); return _(popupid) };
		popdiv.id = popupid;
		popdiv.className = "popup";
		title = typeof title == _UND ? "" : title;
		popdiv.title = title;
		popdiv.SetStyle("opacity:0;visibility:hidden;margin-left:30px");
		popdiv.innerHTML = '<div class="inner"><div class="tit"> ' + title + ' </div> <div class="cls" onclick="_(\'' + popupid + '\').PopOut()"> ' + ("times".Icon()) + ' </div>  <div style="clear:both"></div><div class="cont" id="' + popupid + '_cont" contenteditable="false" ></div></div></div>';
		var loading = document.createElement("div");
		loading.classList.add("popuploadin");
		loading.id = popupid + "_l";
		loading.style.display = "none";
		loading.innerHTML = "cog fa-spin".Icon();
		parent.appendChild(loading);
		loading.Show();
		parent.appendChild(popdiv);
		//alert(popdiv);
		//	(popdiv.id + ": Created").__();
		return popdiv;
	},
	Display: function (popup) {
		//var rect = _(popup.id.substr(5)).getBoundingClientRect(); //get cell rectangular cordinate relative to the window
		//var X = rec
		//alert(rect);
		//(popup.id + ": Displayed").__();
		//initial
		popup.style.marginLeft = "0px";
		popup.style.marginTop = "0px";
		var ld = _(popup.id + "_l");
		if (ld != null) ld.Hide();
		popup.Show();
		var rect = popup.getBoundingClientRect();
		var W = ScreenMgr.GetWidth();
		var H = ScreenMgr.GetHeight();
		var X = Math.round(rect.left);
		var Y = Math.round(rect.top);
		var popW = Math.round(rect.width);
		var popH = Math.round(rect.height);
		var offX = (X + popW) - (W - 100);
		var offY = (Y + popH) - (H - 50);
		//(popup.id + " => Xoff : " + offX).__();
		if (offX > 0) {
			popup.style.marginLeft = (popup.style.marginLeft.ToNumber() - offX - 20) + "px";
		} else {
			popup.style.marginLeft = "30px";
		}
		var ConsumeSpace = popH + (H - Y) + 30;
		if (ConsumeSpace > H && offY > 0) {
			popup.style.marginTop = (60 - Y) + "px";
		} else {
			if (offY > 0) {
				//for other popup apart from spreadsheet cell set tolerance to 10
				var tol = ld != null ? 30 : 0;
				popup.style.marginTop = (popup.style.marginTop.ToNumber() - popH - tol) + "px";
			}
		}
		//(rect.left+","+rect.top+","+rect.width+","+rect.height).__();
		popup.Animate({ CSSRule: "opacity:1;visibility:visible", Time: 200 });
	},
	Hide: function (popup) {
		//(popup.id + ": Hidden").__();
		popup.Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 100, DoAt: 1.0, EndAction: "_('" + popup.id + "').Hide()" });
	},
	_Destroy: function (popdiv) {
		if (typeof popdiv == _UND || popdiv == null) return;
		var parent = popdiv.parentNode;
		if (!Null(parent)) {
			//	(popdiv.id + ": Destroyed").__();
			parent.removeChild(popdiv);
			parent.removeChild(_(popdiv.id + "_l"));
		}
	},
	Close: function (popdiv) {
		popdiv.Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 100, DoAt: 1.0, EndAction: "PopUp._Destroy(_('" + popdiv.id + "'));" });
	},
	_GetContainer: function (popdiv) {
		return _(popdiv.id + "_cont");
	},
	FinishMulti: function (obj) {

		var popupdv = obj.parentElement.parentElement.parentElement;
		var cell = popupdv.parentElement;
		var nxtCell = SpreadSheet.GetNextCell(cell); //get the next cell
		if (nxtCell != null) { //if it exist
			//var nxteditdiv = _(nxtCell.id+"_edit"); //get the editable div
			var nxteditdiv = nxtCell.firstElementChild; //get the editable div
			//document.getElementById().firstElementChild
			if (nxteditdiv != null) {
				nxteditdiv.focus(); //set focus
				return;
			}
		}

		popupdv.PopOut();
		//return false
		//console.log(cell);
	}
}
Object.prototype.AddPopUp = function (title) { PopUp.Create(this, title) }
Object.prototype.PopIn = function () { PopUp.Display(this) }
Object.prototype.PopOut = function () { PopUp.Hide(this) }
Object.prototype.PopClose = function () { PopUp.Close(this) }
Object.prototype.GetPopContainer = function () { return PopUp._GetContainer(this) }
//global array to hold all created SSB object 
var SSBObjects = new Array();
//get the object by its id
function GetSSBObject(id) {
	var ssbobj = SSBObjects[id];
	return typeof ssbobj != _UND ? ssbobj : null;
}
//function to get selected item student in SSB
function _SelectedStudent(ssbobjdiv) {
	srst = ssbobjdiv;
	// var srst = _("searchStud");
	var selectedRegNo = "";
	var selobj = _SelectedObject(srst);
	if (selobj != null) {
		selectedRegNo = selobj.Text().Trim()
	}

	return selectedRegNo;
}
//function to get the ssb selected object
function _SelectedObject(srst, row) {
	row = typeof row == _UND ? false : row;
	var obj = null;
	if (!Null(srst)) {
		if (srst.Data("type") == "table") {
			if (!Null(srst.Selected())) {
				if (row) {
					obj = srst.Selected();
				} else {
					obj = srst.Selected().Cell(1);
				}

			}
		} else if (srst.Data("type") == "thumbnail") {
			if (typeof ThumbNail.Selected[srst.id] != _UND) {
				var selectdThumbn = _(ThumbNail.Selected[srst.id]);
				if (selectdThumbn != null) {
					obj = selectdThumbn;
				}
			}
		}

	}
	return obj;
}

//function to deselect selected object in Search Box
function _deselect(rsttable) {
	if (!Null(rsttable)) {
		var selectedcell = rsttable.SelectedObject(true);
		if (!Null(selectedcell)) {
			selectedcell.click(); //click it to unselect it
		}
	}
}
Object.prototype.SelectedStudent = function () { return _SelectedStudent(this) }
Object.prototype.SelectedText = function () { return _SelectedStudent(this) }
Object.prototype.SelectedDataID = function () {
	var obj = _SelectedObject(this, true);
	if (obj != null) {
		if (obj.Data("id") != "") {
			return obj.Data("id");
		}
	}
	return this.SelectedStudent();
}
Object.prototype.SelectedObject = function (row) { return _SelectedObject(this, row) }
Object.prototype.Deselect = function () { _deselect(this) }
Object.prototype.ReLoad = function (func) {
	var objid = this.id;
	var ssbobj = typeof window["obj_" + objid] == _UND ? null : window["obj_" + objid];
	if (ssbobj == null) { return }
	ssbobj.ReSearch(func);
}
Object.prototype.TextObject = function () {
	return _(this.id + "searchtxt");
}
//function to handle Student Search Box for cportal
var SSB = function (ownerId) {
	this.ownerId = ownerId;
	SSBObjects[ownerId] = this; //register the object
	//alert(ownerId);
	//get selected student (regNo)
	this.Selected = function () {

	};

	this.Ajax = new Ajax();
	this.SearchAjax = null; //ajax of object loading the search result
	this.SearchLoaded = 0; //holds the total number loaded
	this.CurSearcParam = "";//hold the current serach criterial and serach text
	this.SearchBoxSrolled = function () {
		if ((_(this.ownerId + "searchrst").scrollHeight - _(this.ownerId + "searchrst").scrollTop <= _(this.ownerId + "searchrst").style.height.ToNumber() + 10) && this.SearchLoaded > 0) {
			this.Search();
		}
		//document.getElementById().scrollHeight;
		//document.getElementById().scrollTop
		//Tracer.Tag("Scrolled");
	}
	this.SearchTimmer = null;
	this.ReSearch = function (func) {
		this.SearchLoaded = 0;
		this.Search(func);
	};
	this.ClearSelect = function () {
		var stable = _(this.ownerId);
		if (stable != null) {
			//get selected
			var sel = stable.Selected();
			if (sel != null) Table.Deselect(sel);
		}
	}
	this.Clear = function (continu) {
		continu = typeof continu == _UND ? true : continu;
		_(this.ownerId + "searchrst").FadeOut(200);
		if (continu) {
			_(this.ownerId + "searchloadbx").Animate({ CSSRule: "opacity:1;visibility:visible", Time: 300 });
		}
		_(this.ownerId + "totsearch").Text("--");
		//clear the current result
		_(this.ownerId + "searchrst").innerHTML = "";
		ThumbNail.Selected[ownerId] = ""; //reset the selected item array
	};
	this.RadioChange = function (obj) {
		ownid = obj.id.split("_")[0];
		//eval("obj_"+ownid+".Search(null)");
		setTimeout("obj_" + ownid + ".Search(null)", 1);
		//alert(ownid);
	}
	this.CurrFunc = null;
	this.SearchReal = function (obj) {
		//console.log('ddd');
		var This = this;
		(new Promise((resolve, reject) => {
			var func = null;
			if (typeof obj == "function") {
				this.CurrFunc = obj;
				obj = null;
			} else {
				this.CurrFunc = null;
			}
			var searchval = _(this.ownerId + "searchtxt").TextContent();

			if (searchval.Trim() == "") {

				this.Clear(false);
				return;
			}
			if (_(this.ownerId + "_crtlb").Checked()) {
				var searchcrit = "regsc";
			} else {
				var searchcrit = "imgsc";
			}
			// var searchcrit = _(this.ownerId+"searchCriterial").ValueContent();
			//__(searchcrit);
			if (searchcrit == null || searchcrit.Trim() == "") { //if no criterial selected
				//MessageBox.Show("Select a valid search criterial");
				reject("Select a valid search criterial");
				//Tracer.Tag("No Search Criterial Supplied");
				return;
			}
			if (obj == null) { //if search criterial is selected, i.e is obj sent (onchange handler of the textbox)
				_(this.ownerId + "searchtxt").TextFocus();
				//alert('focus');
			}



			//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 (this.CurSearcParam != searchcrit + ";" + searchval && this.SearchLoaded > 0) {
				this.SearchLoaded = 0;
				//Tracer.Tag("Search start index reset to zero(0) due to change in the start parameters, for fresh searching");
			}
			if (this.SearchAjax != null) {
				this.SearchAjax.abort();
				this.SearchAjax = null;
				//Tracer.Tag("Current searching aborted, due to new search request");
			}
			var onselect = ""; //holds the table row/cell select handler 
			var onunselect = "";
			var onselectobj = _(this.ownerId + "onselect");
			var onunselectobj = _(this.ownerId + "onunselect");
			var param = _(this.ownerId + "param").value;
			if (onselectobj != null) {//if the onselect hidden object is found
				onselect = onselectobj.value;
			}
			if (onunselectobj != null) {//if the onunselect hidden object is found
				onunselect = onunselectobj.value;
			}
			var scri = _(this.ownerId + "_engineScript").value; //Pages/Scripts/Student/studsearch.php
			scri = scri.Trim() == "" ? configdata['Core'] + "cportal/Pages/Scripts/Gen/searchbox.php" : scri;
			var domain = _(this.ownerId + "domain").value;
			var criteria = _(this.ownerId + "criteria").value;
			var img = _(this.ownerId + "img").value;
			var dir = _(this.ownerId + "dir").value;
			var ext = _(this.ownerId + "ext").value;
			var thumbnailtext = _(this.ownerId + "thumbnailtext").value;
			var thumbnailtitle = _(this.ownerId + "thumbnailtitle").value;
			//alert(domain + "; "+ criteria);,script=Pages/Scripts/Users/usersearch.php
			var src = scri + "?crit=" + escape(searchcrit) + "&val=" + escape(searchval) + "&startindex=" + this.SearchLoaded + "&callId=" + this.ownerId + "&onselect=" + onselect + "&onunselect=" + onunselect + "&param=" + escape(param) + "&domain=" + escape(domain) + "&criteria=" + escape(criteria) + "&img=" + escape(img) + "&dir=" + escape(dir) + "&ext=" + escape(ext) + "&thumbnailtext=" + escape(thumbnailtext) + "&thumbnailtitle=" + escape(thumbnailtitle) + "&SubDir=" + encodeURIComponent(configdata['SubDir']) + "&Core=" + encodeURIComponent(configdata['Core']);
			//alert(src);

			// src.__();
			if (this.SearchLoaded == 0) { //if searching for the first trip
				this.Clear();
				//Tracer.Tag("First Trip Search");
			}
			this.CurSearcParam = searchcrit + ";" + searchval; //set the search param (criterial and text)
			//Tracer.Tag(Student.BioData.SearchLoaded);
			if (this.SearchLoaded > 0) _(this.ownerId + "moreloading").Animate({ CSSRule: "visibility:visible;opacity:1", Time: 200 });
			// alert(src);
			this.SearchAjax = _(this.ownerId + "searchrst").AppendHTML(src, function (res) {
				// _("searchrst").Animate({CSSRule:"opacity:1",Time:300});
				//Tracer.Tag("Return from Server");
				var resarr = res.id.split("searchrst");
				var ownerId = resarr[0];
				//alert(_(ownerId+"searchStud").rows.length);
				totobj = _("totrw_" + ownerId);
				//alert(totobj);
				if (!Null(totobj)) { //loaded completely
					var rws = _("totrw_" + ownerId).value.ToNumber() - 1;
					//alert(rws);
					if (rws > 0) {
						_(ownerId + "totsearch").Text(rws);
					} else {
						_(ownerId + "totsearch").Text("Empty Set");
					}
					// eval("obj_"+ownerId+".SearchLoaded = 0; ");
					setTimeout("obj_" + ownerId + ".SearchLoaded = 0; ", 1);
					if (window["obj_" + ownerId].CurrFunc != null) window["obj_" + ownerId].CurrFunc();
					//this.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");

					//this.SearchLoaded += 500; 
					//eval("obj_"+ownerId+".SearchLoaded += 500; ");//increament load limit index to start from record 500
					setTimeout("obj_" + ownerId + ".SearchLoaded += 500; ", 1);//increament load limit index to start from record 500
					//alert(this.ownerId+"totsearch");
					//eval('_("'+ownerId+'totsearch").Text(obj_'+ownerId+'.SearchLoaded+"*")'); 
					setTimeout('_("' + ownerId + 'totsearch").Text(obj_' + ownerId + '.SearchLoaded+"*")', 1);
					//continue loading
					//Tracer.Tag("Trying to continue load for start index: "+Student.BioData.SearchLoaded);

				}
				_(ownerId + "searchrst").FadeIn(300);
				_(ownerId + "searchloadbx", ownerId + "moreloading").Animate({ CSSRule: "opacity:0;visibility:hidden", Time: 200 });
				// _().Animate({CSSRule:"visibility:visible;opacity:1",Time:200});
			}, function () { });
		})).catch(err => { MessageBox.Show(err) });

	}
	this.Search = function (obj) {
		//Tracer.Start("Search Start");
		//Tracer.Tag("Start Index: "+Student.BioData.SearchLoaded);	

		if (typeof obj == _UND) {
			obj = null
		} else {
			if (obj == null) {
				obj = "null";
			} else {
				obj = obj.toString();
			}

		}
		if (this.SearchTimmer != null) {
			clearTimeout(this.SearchTimmer);
			this.SearchTimmer = null;
			if (this.SearchAjax != null) this.SearchAjax.abort();

		}
		this.SearchTimmer = setTimeout("obj_" + this.ownerId + ".SearchReal(" + obj + ")", 200);

		// alert(searchcrit + ";" + searchval);
	}
}

function SSBObject(SSBId) {
	return typeof SSBObjects[SSBId] == _UND ? null : SSBObjects[SSBId];
}

//ThumbNails object
var ThumbNail = {
	Selected: new Array(),
	Select: function (obj, selfunc, unselfunc) { //select operation of the thumbnail element 
		if (obj.classList.contains("ThumbNail")) {
			if (obj.classList.contains("sel")) { //if currently selected
				obj.classList.remove("sel"); //un select it
				ThumbNail.Selected[obj.Data("group")] = ""; //clear selected determinal
				if (unselfunc != null) unselfunc(obj);
			} else {

				if (typeof ThumbNail.Selected[obj.Data("group")] != _UND) { //if selected variable exist
					if (ThumbNail.Selected[obj.Data("group")].Trim() != "") { //if an item is selected
						var curselobj = _(ThumbNail.Selected[obj.Data("group")]);
						if (curselobj != null) {
							curselobj.classList.remove("sel"); //un selected it
						}

					}
				}
				ThumbNail.Selected[obj.Data("group")] = obj.id; //reset selected
				obj.classList.add("sel"); //select it
				if (selfunc != null) selfunc(obj);

			}
		}
	}
}

//document.location = 
//Pdf Printer Object 
var PDFPrinter = {
	//the display object(design)
	Display: {
		//dropdown iten select operation
		DropSelect: function (dropid, selVal, selText, selLogo) {
			//var id = obj.id;
			// var dropid = id.split("_")[0];
			_(dropid + "_val").value = selVal;
			_(dropid + "_inp").value = selText;
			_(dropid + "_logo").innerHTML = Icon(selLogo);
		},
		Show: function () {
			//alert('sss');
			_('taquaPdfPrinter').style.cssText = "";
			_('taquaPdfPrinter').classList.add("show");
		},
		Close: function () {
			_('taquaPdfPrinter').classList.remove("show");
			_("pdfPrintIframe").src = "";
		},
		ConvertToNumber: function (tb) {
			//var tb = _(tbid);
			if (tb != null) {
				tb.value = tb.value.ToNumber();
			}
		},
		GetSetting: function (datastr) {
			datastr = (typeof datastr == _UND) ? "" : datastr;
			if (datastr != "") {
				var fields = ["paper=paperPrint", "orientation=paperorien", "fontsize=fontsizee", "ML=marginL", "MR=marginR", "MT=marginT", "MB=marginB"];
				for (var s = 0, lens = fields.length; s < lens; s++) {
					var item = fields[s];
					var itemarr = item.split("=");
					var datt = DataString.Get(datastr, itemarr[0]);
					// datastr = DataString.Remove(datastr,itemarr[0]);
					if (datt.Trim() != "" && (itemarr[1] == "paperPrint" || itemarr[1] == "paperorien")) {
						_(itemarr[1] + '_drpdwn_' + datt).click();
					} else if (datt.Trim() != "") {
						_(itemarr[1] + '_inp').value = datt;
					}
				}
				// _('PdfPrinterData').value = datastr;
			}

			var paper = _('paperPrint_val').value;
			var orienta = _('paperorien_val').value;
			var fontsize = escape(_('fontsizee_inp').value);
			var ML = escape(_('marginL_inp').value);
			var MT = escape(_('marginT_inp').value);
			var MR = escape(_('marginR_inp').value);
			var MB = escape(_('marginB_inp').value);
			var sett = "paper=" + paper + "&orientation=" + orienta + "&fontsize=" + fontsize + "&ML=" + ML + "&MT=" + MT + "&MR=" + MR + "&MB=" + MB;
			return sett;
		}, Start: function () {
			_('pdfprintloadintxt').innerHTML = Icon("cog fa-spin") + " Generating View ...";
			_("pdfPrintIframe").onload = PDFPrinter.Display.End;
			_('pdfPrinterloading').classList.remove('hide');
		}, End: function () {
			_('pdfPrinterloading').classList.add('hide');
		}, Message: function (txt) {
			_('pdfprintloadintxt').innerHTML = txt;
			_('pdfPrinterloading').classList.remove('hide');
			setTimeout("_('pdfPrinterloading').classList.add('hide');", 1000);
		}
	},
	Print: function (url, datastr, filename, actions) {
		filename = typeof filename == _UND ? "document.pdf" : filename;
		actions = typeof actions == _UND ? null : actions;
		var sett = PDFPrinter.Display.GetSetting(datastr);
		if (datastr.Trim() != "") {
			//datastr = _('PdfPrinterData').value;
		}
		//sett.__();
		//alert(paper);
		//alert(url);
		if (url.Trim() != "") {
			var urlsplit = url.split(".");
			if (urlsplit.length > 1) {
				var ext = urlsplit[urlsplit.length - 1];
				if (ext == "epr") { //meaning it is using the generator script
					datastr = "Markup=" + url + "&" + datastr;
					url = configdata.Core + "general/TaquaLB/Elements/Script/generator.php";
				}/* else{
				url = configdata.Core+"cportal/"+url; 
			 } */
			}
			datastrsubcheck = datastr.split("&SubDir=");
			if (datastrsubcheck.length < 2) {
				datastr += "&SubDir=" + encodeURIComponent(configdata.SubDir);
			}
			datastr = "fn=" + filename + "&" + datastr;
			// _("pdfPrintIframe").src = "";
			_('PdfPrinterUrl').value = url;
			_('PdfPrinterData').value = datastr;
			var size = ScreenMgr.GetWidth();
			if (size >= 640) {
				PDFPrinter.Display.Start();
				_("pdfPrintIframe").src = url + "?dl=0&" + sett + "&" + datastr;
			}
			//clear action btn bx
			pdfPrintActionBtn = _('pdfPrintActionBtn');
			if (pdfPrintActionBtn != null) {
				pdfPrintActionBtn.innerHTML = '';
				//get the template button
				if (actions != null) {
					var tempbtn = _('pdfprinttempbtn');
					if (tempbtn != null) {
						//get the html
						var temphtml = tempbtn.outerHTML;
						//loop troug all actions and add the button
						for (var d = 0, lend = actions.length; d < lend; d++) {
							var actbtn = actions[d];
							var newbtnhtml = temphtml;
							if (typeof actbtn.ID == _UND) actbtn.ID = "acbtn_" + d;
							if (typeof actbtn.DisplayText == _UND) actbtn.DisplayText = "";
							if (typeof actbtn.Logo == _UND) actbtn.Logo = "tasks";
							if (typeof actbtn.Title == _UND) actbtn.Title = "Action";
							if (typeof actbtn.Action == _UND) actbtn.Action = "";
							var st = actbtn.DisplayText.Trim() == "" ? "padding-right:0px;" : "";
							var chktxt = actbtn.DisplayText.Trim() == "" ? '<div class="txt">??txt??</div>' : "??txt??";
							newbtnhtml = newbtnhtml.Replace("pdfprinttempbtn", actbtn.ID).Replace(chktxt, actbtn.DisplayText).Replace("??logo??", actbtn.Logo).Replace("??title??", actbtn.Title).Replace("??action??", actbtn.Action).Replace("display:none", st + "display:");
							pdfPrintActionBtn.insertAdjacentHTML('beforeend', newbtnhtml);
						}
					}
				}
			}

			PDFPrinter.Display.Show();
		}
	}, Preview: function () {
		_("pdfPrintIframe").src = "";
		PDFPrinter.Display.Start();
		var sett = PDFPrinter.Display.GetSetting();
		//alert(sett);
		var datastr = _('PdfPrinterData').value;
		var url = _('PdfPrinterUrl').value;
		_("pdfPrintIframe").src = url + "?dl=0&" + datastr + "&" + sett;
	},
	Reset: function () {
		//alert(_('pdfprintdocCont').style.visibility);
		//alert(ScreenMgr.GetWidth());
		_('paperPrint_val').value = "A4";
		_('paperPrint_inp').value = "A4";
		_('paperorien_val').value = "P";
		_('paperorien_inp').value = "Portrait";
		_('paperorien_logo').innerHTML = Icon('file fa-flip-horizontal');
		_('fontsizee_inp').value = "10";
		_('marginL_inp').value = "4";
		_('marginT_inp').value = "4";
		_('marginR_inp').value = "4";
		_('marginB_inp').value = "16";
	}, Download: function () {
		//_('dwnloadff_btnlogo').innerHTML = Icon("cog fa-spin");
		//PDFPrinter.Display.Message()
		var sett = PDFPrinter.Display.GetSetting();
		var datastr = _('PdfPrinterData').value;
		var url = _('PdfPrinterUrl').value;
		// _("pdfPrintIframedl").onload = function(){alert('sss');_('dwnloadff_btnlogo').innerHTML = Icon("download");}
		_("pdfPrintIframedl").src = url + "?dl=1&" + sett + "&" + datastr;
	}
}

var Markups = {
	GroupBoxPlaceholder: function (iconclass, txt, colorclass) {
		iconclass = iconclass || 'table';
		txt = txt || 'Content Container';
		colorclass = colorclass || 'altColor2';
		return '<div class="defaultTabText ep-animate-opacity"><div><i class="fa fa-' + iconclass + ' fa-3x ' + colorclass + '" aria-hidden="true" style=""></i></div><div>' + txt + '</div></div>';
	}
}

var Editor = {
	GetBodyFromAction: (ActionBtn) => {
		if (typeof ActionBtn == "undefined") return null;
		return ActionBtn.parentElement.parentElement.parentElement.nextElementSibling;
	},
	GetCurrentSelected: (ActionBtn) => {
		//.querySelectorAll('.editor-selectable.is-selected');
		var Body = Editor.GetBodyFromAction(ActionBtn);
		if (Body == null) return null;
		var selected = Body.querySelectorAll('.editor-selectable.is-selected');
		if (selected.length < 1) {
			if (Body.classList.contains("editor-body")) return Body;
			return null;
		}
		return selected[0];
	},
	AddGrid: (ActionBtn, verfunc) => {
		//get the question id
		/* var QID = _('curQID').value.ToNumber();
		if(QID < 1){
			MessageBox.Show("#No Question Loaded");
			return;
		} */
		if (verfunc() < 1) {
			return;
		}
		var Body = Editor.GetBodyFromAction(ActionBtn);
		
		var gridmarkup = '<div class="w3-row-padding ep-animate-opacity editor-grid editor"><button class="w3-hide altColor editor-close" onclick="this.parentElement.parentElement.removeChild(this.parentElement)"><i class="fa fa-trash fa-fw"></i></button><div class="m6 w3-col editor-grid-col editor-selectable"></div><div class="m6 w3-col editor-grid-col editor-selectable"></div></div>';
		Body.insertAdjacentHTML('beforeend', gridmarkup);
	},
	AddText: (ActionBtn, verfunc, isTitle) => {
		isTitle = isTitle || false;
		//get the question id
		if (verfunc() < 1) {
			return;
		}
		//get curent selected
		var CurSel = Editor.GetCurrentSelected(ActionBtn);
		//alert(CurSel.tagName.toLowerCase());
		if (CurSel == null || CurSel.tagName.toLowerCase() != "div") { MessageBox.Show("No Valid Insert Area Selected"); return; } //invalid operation
		if (CurSel.classList.contains('editor-text')) { //if selected is a text
			CurSel.contentEditable = true; CurSel.firstElementChild.focus(); return;
		}
		var titlecl = isTitle ? "editor-text-title" : "";
		var textmarkup = `<div class="editor-text ep-animate-opacity editor editor-selectable ${titlecl}" autofocus >
		<div contenteditable ="true" ></div>
		<button contenteditable ="false" class="fa fa-trash fa-fw w3-hide altColor editor-close" onclick="this.parentElement.parentElement.removeChild(this.parentElement)"></button>
		
		</div>`;
		CurSel.insertAdjacentHTML('beforeend', textmarkup);
		CurSel.lastElementChild.firstElementChild.focus();
	},
	AddImage: (ActionBtn, verfunc) => {
		//get the question id
		//var QID = _('curQID').value.ToNumber();
		/* if(verfunc() < 1){
			return;
		}
		 var CurSel = Editor.GetCurrentSelected(ActionBtn);
		 if(CurSel == null){MessageBox.Show("No Valid Insert Area Selected");return;} //invalid operation
		 if(CurSel.tagName.toLowerCase() != "div" || CurSel.classList.contains('editor-text')){MessageBox.Show("Inalid Insert Area Selected");return;} //invalid operation
		 _File.Local({FileID:"editorimg",MaxSize:(200*1000),Accept:"image/*",ReadType:"DataURL",OnLoad:function(param){
		 
		  Editor.InsertFile(ActionBtn,param.Result,"img");
		}}); */
		//Editor.AddFile(ActionBtn,1000*1000*1000,"video/*");

		Editor.AddFile(ActionBtn, 1000 * 1000 * 1000, "image/*", verfunc);

	},

	AddVideo: (ActionBtn, verfunc) => {

		Editor.AddFile(ActionBtn, 1000 * 1000 * 1000, "video/*", verfunc);
	},
	AddFile: (ActionBtn, MaxSize, Accept, verfunc) => {
		(new Promise((resolve, reject) => {
			var CurSel = Editor.GetCurrentSelected(ActionBtn);
			//verification function will return a numeric value, 0 rep failed
			var QID = verfunc();
			if (QID < 1) {
				return;
			}
			if (CurSel == null) { MessageBox.Show("No Valid Insert Area Selected"); return; } //invalid operation

			do {
				//get the question id
				//var QID = _('curQID').value.ToNumber();

				var fn = QID + "_" + (Math.floor(Math.random() * 10000000000));
			} while (_(fn) != null);

			/* if(obj == null){
				reject("#Invalid Insert Area Selected");
				return;
			} */

			_File.Local({
				FileID: fn, MaxSize: MaxSize, Accept: Accept, ReadType: "FileName", OnLoad: function (param) {
					var obj = Editor.InsertTemplate(ActionBtn);
					if (obj == null) {
						reject("#Invalid Insert Area Selected");
						return;
					}
					var upload = new AJAX;
					var newinsert = obj.lastElementChild;
					//get the loding element
					var LodingElem = newinsert.querySelector(".editor-progressbar > div");
					var Data = {};
					Data["FileName"] = fn;
					Data[fn] = "?";
					Data["SubDir"] = configdata['SubDir'];
					//console.log(Data);
					upload.Post({
						Action: configdata['Core'] + "general/TaquaLB/Elements/Editor/Script/loader.php",
						Data: Data,
						OnProgress: delta => {
							LodingElem.style.width = Math.floor(delta * 95) + "%";
							//console.log(delta);
						},
						OnComplete: (res) => {
							//alert(res);return;
							LodingElem.style.width = "100%";
							if (res.substr(0, 1) == "#") {
								//MessageBox.Show(res.substr(1));
								newinsert.parentElement.removeChild(newinsert);
								reject(res);
							}
							var tempimg = newinsert.querySelector(".img-temp");
							LodingElem.parentElement.parentElement.removeChild(LodingElem.parentElement);
							tempimg.parentElement.removeChild(tempimg);
							//check the file type
							var vv = '';
							if (Accept == "video/*") { //video
								vv = '<video class="inserted-file ep-animate-opacity" data-src="' + res + '" src="' + res + '" alt="" standby="" controls ></video>';
							} else if (Accept == "audio/*") {
								vv = '<audio class="inserted-file ep-animate-opacity" data-src="' + res + '" src="' + res + '" alt="" standby="" controls ></audio>';
							} else if (Accept == "image/*") {
								vv = '<img class="inserted-file ep-animate-opacity" data-src="' + res + '" src="' + res + '" alt="Image" >';
							} else {
								vv = '<object  class="inserted-file ep-animate-opacity" data-src="' + res + '" data="' + res + '" alt="" standby="" /></div>'
							}
							newinsert.insertAdjacentHTML("beforeend", vv);
							resolve(newinsert);
						}
					});
					//Editor.InsertFile(ActionBtn,param.Result,"v",'class="video"');
				}
			})
		})).then(res => {

		}).catch(res => {
			MessageBox.Show(res);
		});

	},
	InsertTemplate: ActionBtn => {
		var CurSel;
		if (typeof ActionBtn == "string") {
			//check if exist in Selected
			if (typeof Editor.Selected[ActionBtn] != "undefined" && typeof Editor.Selected[ActionBtn] != null) {
				CurSel = Editor.Selected[ActionBtn];
			} else {
				CurSel = _(ActionBtn);
			}
		} else {
			CurSel = Editor.GetCurrentSelected(ActionBtn)
		}
		if (CurSel == null || !_IsFound(CurSel)) return null;
		//var CurSel = (typeof ActionBtn == "object")?Editor.GetCurrentSelected(ActionBtn):_(ActionBtn);
		//alert(CurSel.tagName.toLowerCase());
		if (CurSel.tagName.toLowerCase() != "div" || CurSel.classList.contains('editor-text')) return null; //invalid operation
		img = "<div class='ep-animate-opacity editor-image editor' style='border-radius:3px'><button class='w3-hide altColor editor-close' onclick='Editor.RemoveFile(this)'><i class='fa fa-trash fa-fw fa-fw'></i></button><div class='editor-progressbar'><div class='altBgColor'></div></div><img class='img-temp' src='" + configdata['Core'] + "general/TaquaLB/Elements/Editor/file.jpg" + "'></div>";
		CurSel.insertAdjacentHTML('beforeend', img);
		return CurSel;
	},
	AddAudio: (ActionBtn, verfunc) => {
		Editor.AddFile(ActionBtn, 1000 * 1000 * 1000, "audio/*", verfunc);
	},

	RemoveFile: RemoveBtn => {
		//check type of file that exist
		var insertfile = RemoveBtn.parentElement.querySelectorAll(".inserted-file");

		if (insertfile.length > 0) {
			RemoveBtn.disabled = true;
			RemoveBtn.innerHTML = "<i class='fa fa-spin mbri-setting3'></i>";
			var allfile = [];
			insertfile.forEach(instfile => {
				allfile.push(instfile.Data('src'));
			});
			var remajax = new AJAX;
			remajax.Post({
				Action: configdata['Core'] + "general/TaquaLB/Elements/Editor/Script/removefile.php",
				Data: { URL: allfile.join(";"), "SubDir": configdata['SubDir'] },
				OnComplete: (res) => {
					if (res.substr(0, 1) == "#") {
						MessageBox.Show(res.substr(1));
						RemoveBtn.disabled = false;
						RemoveBtn.innerHTML = "<i class='fa fa-times fa-fw'></i>";
						//newinsert.parentElement.removeChild(newinsert);
					} else {
						RemoveBtn.parentElement.parentElement.removeChild(RemoveBtn.parentElement)
					}

				}
			})
		} else {
			RemoveBtn.parentElement.parentElement.removeChild(RemoveBtn.parentElement)
		}

	},

	InsertFile: function (ActionBtn, filedata, type, attr) {
		attr = attr || "";
		var CurSel = Editor.GetCurrentSelected(ActionBtn);
		//alert(CurSel.tagName.toLowerCase());
		if (CurSel.tagName.toLowerCase() != "div" || CurSel.classList.contains('editor-text')) return; //invalid operation

		var id = "rand" + Math.random();
		//var doc = document.getElementById("editor");
		// doc = doc.document ? doc.document : doc.contentWindow.document;
		var doc = document;
		if (typeof type != "undefined" && type == "img") {
			img = "<div class='ep-animate-opacity editor-image editor'><button class='editor-close w3-hide altColor' onclick='this.parentElement.parentElement.removeChild(this.parentElement)'><i class='fa fa-trash fa-fw'></i></button><img src='" + filedata + "' " + attr + " id='" + id + "'></div>";
		} else if (typeof type != "undefined" && type == "v") {
			img = "<div class='ep-animate-opacity editor-image editor'><button class='editor-close w3-hide altColor' onclick='this.parentElement.parentElement.removeChild(this.parentElement)'><i class='fa fa-trash fa-fw'></i></button>" + '<video id="' + id + '" ' + attr + ' src="' + filedata + '" alt="" standby="" controls ></video></div>';
		} else if (typeof type != "undefined" && type == "a") {
			img = "<div class='ep-animate-opacity editor-image editor'><button class='editor-close w3-hide altColor' onclick='this.parentElement.parentElement.removeChild(this.parentElement)'><i class='fa fa-trash fa-fw'></i></button>" + '<audio id="' + id + '" ' + attr + ' src="' + filedata + '" alt="" standby="" controls ></audio></div>';
		} else {
			img = "<div class='ep-animate-opacity editor-image editor'><button class='editor-close w3-hide altColor' onclick='this.parentElement.parentElement.removeChild(this.parentElement)'><i class='fa fa-trash fa-fw'></i></button>" + '<object id="' + id + '" ' + attr + ' data="' + filedata + '" alt="" standby="" /></div>';

		}

		CurSel.insertAdjacentHTML('beforeend', img);

		/* 
		  if(document.all) {
			var range = doc.selection.createRange();
			range.pasteHTML(img);
			range.collapse(false);
			range.select();
		  } else {
			doc.execCommand("insertHTML", false, img);
			// _(id).execCommand("enableObjectResizing",false,true);
		  }
		  return doc.getElementById(id); */
	},
	AddPlaceHolder: (ActionBtn, verfunc) => {
		if (verfunc() < 1) {
			return;
		}
		document.execCommand('insertHTML', false, '<input class="editor-ph" placeholder="Text" />');
	},
	BringToFront: (elem, btn, func) => {
		func = func || null;
		var rst = btn.parentElement.parentElement.querySelectorAll(".option-is-active");
		if (rst.length > 0) {
			rst.forEach(element => {
				element.classList.remove('option-is-active')
			});
		}
		btn.classList.add('option-is-active');
		elem.parentElement.insertBefore(elem, elem.parentElement.childNodes[0]);
		if (func != null) func(btn);
	},
	Selected: {},
	SelectAs: (tagname, obj) => {
		Editor.Selected[tagname] = obj;
	},
	/* StartScroll:function(){
_('Cbttab_tb_0_body').addEventListener("scroll",ev=>{
	  //console.log('Scrolling');
	 var view = document.querySelectorAll('.inview');
	 //console.log(view.length);
	 if(view.length > 0){
		 view.forEach(viewobj=>{
			if(Editor.InView(viewobj)){
				viewobj.classList.add("isinview")
			}else{
				viewobj.classList.remove("isinview")
			}
		 })
	 }

  }
  );
	},
	InView:elem=>{
	var rect = elem.getBoundingClientRect();
	var elemtop = rect.top;
	var elembottom = rect.bottom;
	var isAllVisible = (elemtop >= 0) && (elembottom <= window.innerHeight)
	var isPartVisible = (elemtop <  window.innerHeight) && (elembottom >= 0)
	return isAllVisible;
	}, */
	FontType: function (fontname) {
		//alert(fontname);
		document.execCommand("fontName", true, fontname);

	},
	FontSize: function (fontsize) {
		fontsize = fontsize.options[fontsize.selectedIndex].textContent;
		//alert(fontsize);
		fontsize = fontsize == "Default" ? "2px" : fontsize;
		document.execCommand("fontSize", false, fontsize)
	},
	Bold: function () {

		document.execCommand("bold");
	},
	Italic: function () {
		document.execCommand("italic");
	},
	Underline: function () {
		document.execCommand("underline");
	},
	StrikeThrough: function () {
		document.execCommand("strikeThrough");
	},
	FontColor: function (color) {
		document.execCommand("foreColor", false, color);
	},
	BackColor: function (color) {
		document.execCommand("hiliteColor", false, color);
	},
	OrderedList: function () {
		document.execCommand("insertOrderedList");
	},
	UnOrderedList: function () {
		document.execCommand("insertUnorderedList");
	},
	AlignCenter: function () {
		document.execCommand("justifyCenter");
	},
	AlignLeft: function () {
		document.execCommand("justifyLeft");
	},
	AlignRight: function () {
		document.execCommand("justifyRight");
	},
	AlignFull: function () {
		document.execCommand("justifyFull");
	}
}

var Widget = {
	Loading: () => {
		return '<svg class="spinner-container" viewBox="0 0 44 44"><circle class="path" cx="22" cy="22" r="20" fill="none" stroke-width="4"></circle></svg>';
	}
}

onDOMReady(() => {


	document.body.addEventListener("click", ev => {
		//console.log(ev.target.className);
		if (ev.target.classList.contains("editor-selectable") || ev.target.classList.contains("editor-body") || ev.target.classList.contains("editor-grid") || ev.target.classList.contains("editor-item")) {

			//check if target is already selected
			if (ev.target.classList.contains("is-selected")) return;
			//get all editor selectable and on select them
			//var selected = ev.target.parentElement.parentElement.querySelectorAll('.editor-selectable.is-selected');
			var selected = document.querySelectorAll('.editor-selectable.is-selected');

			if (selected.length > 0) {
				for (var s = 0, l = selected.length; s < l; s++) {
					selected[s].classList.remove("is-selected")
				}
			}
			if (!ev.target.classList.contains("editor-body") && !ev.target.classList.contains("editor-grid") && !ev.target.classList.contains("editor-item")) ev.target.classList.add("is-selected")
		}

		if (!ev.target.classList.contains("dropdownline-line-obj")) {
			var allopendrp = document.getElementsByClassName('dropdowncont');
			if (allopendrp.length > 0) {
				for (var ss = 0, sslen = allopendrp.length; ss < sslen; ss++) {
					allopendrp[ss].style.display = 'none';
				}
			}

		}
	}
	);


	document.body.addEventListener("dblclick", ev => {
		if (ev.target.classList.contains("editor-text")) {
			ev.target.contentEditable = true; ev.target.focus();
		}
	});

}
);

// DropDownLine
var DropDownLine = {
	Drop: obj => {
		var Dropdown = obj.getElementsByClassName('dropdowncont')[0];
		Dropdown.style.display = Dropdown.style.display == "none" ? "block" : "none";
	},
	DropSelect: item => {
		var itemval = item.getAttribute('data-value');
		if (itemval == "0") return;
		var it = item.parentElement.getElementsByClassName('isselect')[0];
		if (item != it) {
			disobj = item.parentElement.parentElement.getElementsByClassName('displaytxt')[0];
			disobj.innerHTML = item.innerHTML;
			disobj.setAttribute('data-value', itemval);

			item.classList.add('isselect');
			it.classList.remove('isselect');

		}
	},
	Selected: dropdid => {
		var dropobject = _(dropdid);
		if (dropobject == null) return "";
		var displayobj = dropobject.getElementsByClassName('displaytxt')[0];
		//alert(displayobj.outerHTML);
		return { Value: displayobj.getAttribute('data-value'), Text: displayobj.innerHTML };
	},
	SetTheme: (dropdid, theme) => {
		if (theme != "ok" && theme != "error") theme = "";
		var dropobject = _(dropdid);
		if (dropobject == null) return;//
		var droppdown = dropobject.getElementsByClassName('droppdown')[0];
		//remmove ll previous ones
		droppdown.classList.remove("error");
		droppdown.classList.remove("ok");
		if (theme != "") droppdown.classList.add(theme);
	}
}


var CardList = {
	Filter: inp => {
		// var datadiv = inp.parentElement.parentElement.parentElement.lastElementChild;
		var indcontentdivs = inp.parentElement.parentElement.parentElement.children[1].children;
		var displayelem = inp.parentElement.nextElementSibling;
		if (indcontentdivs.length > 0) {
			var diselem = Array.from(indcontentdivs).filter(indelem => {
				if (indelem.textContent.toLowerCase().indexOf(inp.value.toLowerCase()) < 0 && inp.value.trim() != "") {
					indelem.style.display = 'none';
				} else {
					indelem.style.display = 'flex';
					return indelem;
				}
			});
			displayelem.textContent = diselem.length + " / " + indcontentdivs.length + " displayed";
			//console.log(diselem.length);
		} else {
			displayelem.textContent = "";
		}




	},
	Empty: btn => {
		var indcontentdivs = btn.parentElement.parentElement.parentElement.children;
		indcontentdivs[1].innerHTML = "";
		indcontentdivs[2].innerHTML = "[]";
		CardList.Filter(btn.parentElement.children[1]);
	},
	Delete: (btn, key, cardlistid) => {
		var contentsdiv = btn.parentElement.parentElement.parentElement;

		var datas = contentsdiv.nextElementSibling.innerHTML;
		try {
			var data = JSON.parse(datas);
			if (typeof data[key] != "undefined") {
				delete data[key];
				contentsdiv.nextElementSibling.innerHTML = JSON.stringify(data);

			}
			contentsdiv.removeChild(btn.parentElement.parentElement);

			CardList.Filter(_(cardlistid));
		} catch (error) {
			MessageBox.Show("#Updating List Data Failed");
		}
		//console.log(datas);

	},
	Data: id => {
		return _(id + "_data").innerHTML;
	},
	Loading: (id) => {
		_(id + "_cardbx").innerHTML = '<div class="cardbx-loading">' + Widget.Loading() + '</div>';
		_(id + "_data").innerHTML = "{}";
		//
	}
}




