var md5Hash=false
var anactor

var a = document.location + " "
a=a.toLowerCase()
pos = a.indexOf("?")
if (pos !== -1) { a = a.substr(0, pos) }
a = reverseString(a) 
pos = a.indexOf("/")
if (pos !== -1) { a = a.substr(pos) }
a = reverseString(a) + "cdbi/"
a=replace(a,"cdbi/cdbi/","cdbi/")
//alert("JS: " +a)

//=====================================
function reverseString(a) {
    newa = ""
    for (var i = a.length - 1; i >= 0; i--) {
        newa = newa + a.substr(i, 1)
    }
    return newa
}

//===========================================================================================================================<description>
// Javascript function to be included in CDBI
//===========================================================================================================================</description>

$(document).ready(function() {
    deobfuscate()

    initCalendar()

    jQuery(".unselected").hover(function() { jQuery(this).addClass("unselected_hover") }, function() { jQuery(this).removeClass("unselected_hover") })


    adiv = document.createElement("div")
    //if (gebi("widthdiv")) { gebi("widthdiv").appendChild(adiv) }
    if (gebi("widthdiv")) { document.body.appendChild(adiv) }

    adiv.style.position = "absolute"
    adiv.style.display = "none"
    adiv.id = "CDBIPoptext"
    adiv.className = "CDBIPoptext"
    //if (jQuery(".maintable input:text")
    //if (jQuery(".maintable input:text")[0]) { jQuery(".maintable input:text")[0].focus() }
    addBehavior()
    //if (gebi('waiting')) { gebi('waiting').style.display = 'none'; }
    //if (gebi('widthdiv')) gebi('widthdiv').style.display = '';
    //if (gebi('CDBInavholder')) gebi('CDBInavholder').style.display = 'block';

    // set height of navholder
    oh = 0
    jQuery(".selected").each(function() {
        oh = max(oh, parseInt(this.style.top) + this.offsetHeight)
    })

    jQuery(".CDBInavholder").css("height", oh)



    if (anactor) {
        lastScroll = gebi("currentScroll").value
        lastTop = gebi("currentTop").value
        now = 0

        if (gebi("footer")) { now = jQuery("#footer_" + anactor).offset().top }
        document.body.scrollTop = lastTop - (lastScroll - now)


        if (anaction) {
            //if (anaction === "insert") {
            //if (gebi("footer_" + anactor)) {gebi("footer_" + anactor).scrollIntoView() }
            //}xx
        }
    }


})



function addBehavior() {
    $(".trnormal, .trnormalodd,.tdform, .listviewheader tbody,.formviewheader tbody, .editviewheader tbody, .newviewheader tbody, .footer, .selected,.unselected, .CDBIPoptext,.infodiv,.maintable").css("behavior", "y")
    $(".trnormal, .trnormalodd,.tdform, .listviewheader tbody,.formviewheader tbody, .editviewheader tbody, .newviewheader tbody, .footer, .selected,.unselected, .CDBIPoptext,.infodiv,.maintable").css("behavior", "url('PIE.htc')")
}


//=====================================
function deobfuscate() {

    $('.codedirection').each(function () {
        var email = $(this).html()
        newmail = ""
        for (var i = email.length - 1; i >= 0; i--) {
            newmail = newmail + email.substr(i, 1)

        }
        $(this).removeClass("codedirection")
        $(this).html('<a href="mailto:' + newmail + '" rel="nofollow">' + newmail + '</a>')
    })


}

// ======================================================================;
function test_email(emailStr) {
    if (emailStr === "") { return false; }
    emailStr = Trim(emailStr);
    var emailPat = /^[a-zA-Z][\w\.\-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.\-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
    var matchArray = emailStr.match(emailPat);
    if (matchArray === null) { return false; }
    return true;
}

//=====================================
function initCDBI(domakelines) {

    //if (gebi("currentScroll")) { document.body.scrollTop = gebi("currentScroll").value }
    //zdocument.body.scrollTop = gebi("currentScroll").value }

    $(".popper").hover(function (e) { showCDBIPop(e, this.getAttribute('helptext')); }, function () { killCDBIPop(); });

    if (domakelines) {
        makeLines()
    }




    if (gebi("actor")) {
        actor = gebi("actor").value
        //if (gebi("indent_" + actor)) { document.body.scrollTop = $("#indent_" + actor).position().top }
    }


    //alert($(".textcontainer").length)


    setTextContainers()
    setTextContainers()

}


//=====================================
function setTextContainers() {
    //return

//return
    $(".textcontainerlist").each(function() {
        if (this.scrollWidth > 200) { this.style.width = min(200, this.scrollWidth) + "px" }
        if (this.scrollHeight > 100) { this.style.height = min(100, this.scrollHeight) + "px" }
    })
    $(".textcontainerform").each(function() {
        if (this.scrollWidth > 500) { this.style.width = min(500, this.scrollWidth) + "px" }
        if (this.scrollHeight > 100) { this.style.height = min(100, this.scrollHeight) + "px" }
    })
}
//=====================================
function showCDBIPop(e,text, anx, any) {

    var e=e||window.event;
    var x = 0,y = 0;
    curx = e.clientX+document.body.scrollLeft;
    cury = e.clientY+document.body.scrollTop;

    if (text === "") { return; }
    if (!anx) { var anx = curx } if (!any) { var any = cury; }

    if (gebi("CDBIPoptext")) {popper = gebi("CDBIPoptext") } else { popper = gebi("poptext") }


    popper.innerHTML = text;

    //any=any-$("#widthdiv").offset().top
    $(popper).stop().css("display", "inline-block").css("opacity", 0);
    popper.style.width = "";
    if (popper.offsetWidth > 300) {
        popper.style.width = 300;
    }
    else {
        popper.style.width = "";
    }

    if (anx +50+ popper.offsetWidth > getWindowSize("w")) {
        anx = anx - popper.offsetWidth - 100
    }
    else {
        anx = anx
    }

    popper.style.left = (anx+50)+"px";
    popper.style.top = any+"px";

    $(popper).stop().css("display", "none").css("opacity", 1).fadeIn(500);

}

//=====================================
function vpWidth() {
    return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}
function vpHeight() {
    return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

//=====================================
function killCDBIPop() {
    $("#CDBIPoptext").stop().fadeOut(500);
    $("#poptext").stop().fadeOut(500);
}


function gebi(id) {return document.getElementById(id)}

//---------------------------------------------------------------------------
function setvalue(fieldname, avalue, dosubmit, target) {
	
//---------------------------------------------------------------------------------------------------------------------------<description>
// set the value of control 'fieldname' on form 'formname' to value 'avalue'
// sumbits the form when dosubmit is true
//---------------------------------------------------------------------------------------------------------------------------</description>

		theform=findForm(gebi(fieldname))
		//thefield = eval("document." + formname + "." + fieldname)
		thefield = gebi(fieldname)

		if (!thefield) { return }
		thefield.value = avalue

		if (dosubmit) {

		    if (gebi("alwaysajax_" + target).value === "True") {
		        anaction = gebi("action_" + target).value
		        atable = gebi("table_" + target).value
		        aview = gebi("view_" + target).value
		        aviewmode = gebi("viewmode_" + target).value
		        awhere = gebi("where_" + target).value
		        awhereval = gebi("whereval_" + target).value
		        athepage = gebi("thepage_" + target).value
		        athesort = gebi("sort_" + target).value
		        asearch = gebi("search_" + target).value

		        allowswitch = gebi("allowswitch_" + target).value
		        adefaultpagesize = gebi("defaultpagesize_" + target).value
		        showAjax(target, anaction, atable, aview, aviewmode, awhere, awhereval, athepage, athesort, asearch, allowswitch, adefaultpagesize)

		        return
		    }

		    if (gebi("currentScroll")) { gebi("currentScroll").value = $("#footer_" + fieldname.split("_")[1]).offset().top }
		    if (gebi("currentTop")) {gebi("currentTop").value = document.body.scrollTop}

			if (gebi("excel")) {gebi("excel").value=''}
			thefield=gebi(fieldname)
			gebi("actor").value = fieldname.split(/\_/)[1]

			killCDBIPop()
			document.body.style.display = "none"

			theform.submit()
			if (window.opener) {
			    if (window.opener.popwindow) {
			        window.opener.popwindow.close()
			    }
			} 
		}
	}

	//==========================================================================
	function findForm(a) {
	    while (a.parentNode.tagName.toLowerCase() !== "form") {
	        if (a.parentNode.tagName.toLowerCase() === "body") {
	            alert("no form defined!")
	            return
	        }
	        a = a.parentNode
	    }
	    return (a.parentNode)
	}
//---------------------------------------------------------------------------
	function setcb(acb,aname){

//---------------------------------------------------------------------------------------------------------------------------<description>
// set the value of contraol 'aname' on form 'formname' to 0 or 1 depending on the state of checkbox 'acb'
//---------------------------------------------------------------------------------------------------------------------------</description>
	
		if (acb.checked) {
			gebi(aname).value=1
		}
		else {
		    gebi(aname).value = 0
		}
	}
	
//---------------------------------------------------------------------------
	function checkform(anid,afield,anaction,target) {
//---------------------------------------------------------------------------------------------------------------------------<description>
// checks a filled-in form for errors (so with new or update)
// inputs: 
// anid: ID of the form as defined in the call to showtable()
// formname: name of the form to submit
// afield: name of a form control to set (action_[id])
// anaction: either 'insert' or 'update'
// returns if there are errors; submits if there are no errors

// values can be checked client-side because fields have a name in the form of  
// datatatype|databaselength|isnullable|fieldname|id|isidentity|caption
// 
//---------------------------------------------------------------------------------------------------------------------------</description>
	//alert(1)

	theform = findForm(gebi("table_" + anid))
	//alert("anid " +anid)

		for (var i=0, l=theform.length;i<l;i++) {
			thename=theform[i].name
			thevalue = Trim(theform[i].value)
			//alert(thevalue)
			theform[i].value=thevalue
			if (thename.indexOf("|")!==-1) {
				pars=thename.split(/\|/)
				type=pars[0]
				len=parseInt(pars[1])
				nullable=pars[2]
				fname=pars[3]
				id=pars[4]
				xcaption=pars[6]
				if (id==anid) {
					numeric=false
					character=false
					//alert(type)
					if (type=="int") {numeric=true}
					if (type=="tinyint") {numeric=true}
					if (type=="smallint") {numeric=true}
					if (type=="bigint") {numeric=true}
					if (type=="float") {numeric=true}
					if (type=="real") {numeric=true}
					
					if (numeric) {thevalue=replace(thevalue,",","")}
					if (numeric) {
					    thisval = thevalue
					    if (thevalue.substr(0,1)==="=") {thisval=thevalue.substr(1)}
					    if (isNaN(thisval)) {
					        alert(textlabel47 + " '" + xcaption + "'")
					        
					        theform[i].focus()
						    if (theform[i].nextSibling) { if (theform[i].nextSibling.name==="autocomplete") {theform[i].nextSibling.focus()}}
					        return true	
						}

		            }
                    if (theform[i].nextSibling) {
                        if (theform[i].nextSibling.name === "autocomplete") {
                            if (theform[i].nextSibling.className.indexOf("redish") !== -1) {
                                if (nullable == "1") {
                                    alert(textlabel48 + " '" + xcaption + "'" + " (or leave blank)") 
                                }
                                else {
                                    alert(textlabel48 + " '" + xcaption + "'")
                                }     
                                theform[i].nextSibling.focus()

                                return true
                            }
                        }
		            }  
					
					
					if (thevalue=="") {
						if (nullable=="1") {
						}
						else {
							alert(textlabel48 + " '"+xcaption + "'")
							theform[i].focus()
							if (theform[i].nextSibling) { if (theform[i].nextSibling.name==="autocomplete") {theform[i].nextSibling.focus()}}
							return true	
						}
		            }
		            
		            if ((fname.toUpperCase().indexOf("EMAIL") !== -1) && (thevalue !== "") && (fname !== "EMAILLIST_KEY") ) {

		                if (!test_email(thevalue)) {
		                    alert(textlabel75);
		                    theform[i].focus();
		                    return true
                        }
		            }
		            
					if (type.indexOf("char")!==-1) {
						if (thevalue.length>len) {
							alert(textlabel49+' ' + xcaption + ' = ' +len+' '+textlabel50)
							theform[i].focus()
							if (theform[i].nextSibling) { if (theform[i].nextSibling.name==="autocomplete") {theform[i].nextSibling.focus()}}
							return true	
						}
					}
				}
			}
		}	
		
		setvalue(afield,anaction,true,anid)
	}
	
//---------------------------------------------------------------------------
	function replace(string,text,by) {
	
//---------------------------------------------------------------------------------------------------------------------------<description>
// Replaces text with by in string
//---------------------------------------------------------------------------------------------------------------------------</description>
	
	    var strLength = string.length, txtLength = text.length;
	    if ((strLength == 0) || (txtLength == 0)) return string;

	    var i = string.indexOf(text);
	    if ((!i) && (text != string.substring(0,txtLength))) return string;
	    if (i == -1) return string;

	    var newstr = string.substring(0,i) + by;

	    if (i+txtLength < strLength)
	        newstr += replace(string.substring(i+txtLength,strLength),text,by);

	    return newstr;
	}		
	
//---------------------------------------------------------------------------
function LTrim(str) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// removes leading spaces, tabs from string 'str'
//---------------------------------------------------------------------------------------------------------------------------</description>


   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {

      var j=0, i = s.length;

      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      s = s.substring(j, i);
   }
   return s;
}

//---------------------------------------------------------------------------
function RTrim(str) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// removes trailing spaces, tabs from string 'str'
//---------------------------------------------------------------------------------------------------------------------------</description>


   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {

      var i = s.length - 1;       // Get length of string
 
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;

      s = s.substring(0, i+1);
   }

   return s;
}

//---------------------------------------------------------------------------
function Trim(str) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// removes leading and trailing spaces, tabs from string 'str'
//---------------------------------------------------------------------------------------------------------------------------</description>

   return RTrim(LTrim(str));
}	

//---------------------------------------------------------------------------
function getobject(aname) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// cross-browser to get an DOM element by it's id
// returns: an object
//---------------------------------------------------------------------------------------------------------------------------</description>


	if (gebi) {
		return gebi(aname)
	}
	else {
		return document.getElementById(aname)
	}
}



//---------------------------------------------------------------------------
function make_lines() {

//---------------------------------------------------------------------------------------------------------------------------<description>
// Creates the lines for the tree view . should be called with the <body onload=make_lines()>
//---------------------------------------------------------------------------------------------------------------------------</description>
		var cells=$(".btarget")
		for (var i=0, l=cells.length;i<l;i++) {
			next=has_siblings(i)
			if (next!==-1) {
				colid=cells[i].id.split(/\_/)[2]
				for (var j=i+1, k=next;j<k;j++) {
					colid2=cells[j].id.split(/\_/)[2]
					if (colid==colid2) {
						cells[j].style.borderLeftWidth=3
					}
				}
			}
			else {
			}
		}
		
}

	
//---------------------------------------------------------------------------
function has_siblings(anindex) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// returns the index of the last sibling or -1 when no sibling
// cells have name indent_x_y_top (or bottom) or space_x_y_top (or bottom) x= max indent, y=current indent
//---------------------------------------------------------------------------------------------------------------------------</description>
		
	start=anindex
    //alert(start)
    var cells = $(".btarget")
    //alert(cells.length)
	typeA = cells[start].id.split(/\_/)[0]  // either space or indent
	indentA=cells[start].id.split(/\_/)[1]
	colA=cells[start].id.split(/\_/)[2]
	topboteA=cells[start].id.split(/\_/)[3]

	foundindex=-1
	if (typeA=="space") return -1
	skip=false
	for (var i=start+1, l=cells.length;i<l;i++) {
	
		typeB=cells[i].id.split(/\_/)[0]  // either space or indent
		indentB=cells[i].id.split(/\_/)[1]
		colB=cells[i].id.split(/\_/)[2]
		topbotB=cells[i].id.split(/\_/)[3]
		
		if (indentB<indentA) skip=true
		
		if (!skip) {
			if  ((colA==colB) && (indentA==indentB)) {
				foundindex=i
			}
		}
	}
	return foundindex
}



//---------------------------------------------------------------------------
function CDBIsearch(anid) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// called when the search button is pressed. show seacrh box or submit
//---------------------------------------------------------------------------------------------------------------------------</description>


	if (gebi("search_"+anid).value=="") {
		// show it
		gebi("search_"+anid).style.visibility="visible"
		//gebi("search_"+anid).style.width=100
		gebi("cancelsearch_" + anid).style.display = "inline"
		gebi("search_" + anid).focus()
}
else {
        gebi("thepage_" + anid).value=1
        //findForm(gebi("table_"+anid)).submit()
        setvalue("search_" + anid, gebi("search_" + anid).value, true, anid)
	}
}

//---------------------------------------------------------------------------
function cancel_CDBIsearch(anid) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// called when the cancel search button is pressed. hides search box
//---------------------------------------------------------------------------------------------------------------------------</description>

	gebi("search_"+anid).style.visibility="hidden"
	//gebi("search_"+anid).style.width=1
	gebi("cancelsearch_"+anid).style.display="none"


	if (gebi("search_"+anid).value=="") {
		// show it
	}
	else {
	    setvalue("search_" + anid, "", true, anid)
	    //findForm(gebi("table_" + anid)).submit()
}
}


// ======================================================================	
function hide(formname, anid) {
	list=$(".tr_"+anid)
	if (list[0]) {
		object=list[0]
	}
	else {
		object=list
	}
	
	if (object.style.display=='none') {

		// currently hidden, make visible
		
		newvisib='inline'
		eval("document."+formname+".hidden_"+anid+".value=''")
		getobject("eye_"+anid).style.display='inline'
		getobject("sleep_"+anid).style.display='none'
		
		//if (gebi("ti_"+anid)) {gebi("ti_"+anid).style.display='none'}
		$(".ti_" + anid).css("display", "none")
		$(".tr_" + anid).css("display", "")


	}
	else {
		newvisib='none'
		eval("document."+formname+".hidden_"+anid+".value='1'")
		getobject("eye_"+anid).style.display='none'
		getobject("sleep_"+anid).style.display='inline'
		//if (gebi("ti_"+anid)) {gebi("ti_"+anid).style.display='inline'}
		$(".ti_" + anid).css("display", "")
		$(".tr_" + anid).css("display", "none")
		
	}
	
	if (list[0]) {
		for (var i=0, l=list.length;i<l;i++) {
			//list[i].style.display=newvisib
		}
	}
	else {
		//list.style.display=newvisib
	}
	

}


function make_invisible(formname,anid) {

//---------------------------------------------------------------------------------------------------------------------------<description>
// called when the cancel search button is pressed. hides search box
//---------------------------------------------------------------------------------------------------------------------------</description>


}



// ======================================================================	
function removeAllOptions(selectbox) {
    for (var i = selectbox.options.length - 1; i >= 0; i--) {
        selectbox.remove(i);
    }
}



// ======================================================================	;
function CDBIautoSuggest(aval, atable, atextbox, adropdown) {
    $(atextbox).removeClass("greenish").addClass("redish")
    if (Trim(aval) === "") {
        removeAllOptions(adropdown);
        addOption(adropdown, '--select--', '');
        adropdown.style.display = "none";
        $(atextbox).removeClass("greenish").removeClass("redish")
        
    }
    if (aval.length < 3) { return }
    adropdown.style.position = "absolute"
    adropdown.style.top = ($(atextbox).position().top+atextbox.offsetHeight)+"px"
    adropdown.style.left = $(atextbox).position().left+"px"
    if (Trim(aval) !== "") {
        src = cdbiroot+"autocomplete.asp?atable=" + atable + "&database=" +CDBIDatabase + "&search=" + aval
        jQuery.getJSON(src + "&callback=?", function(data) { CDBIautoSuggestCallBack(atextbox, adropdown, data); });
    }
    else {
        removeAllOptions(adropdown);
        adropdown.style.display = "none";
    }
}


// ======================================================================	;
function CDBIautoSuggestCallBack(atextbox, adropdown, data) {
    if (typeof data === "object") { data = toArray(data); }
    removeAllOptions(adropdown);
    if (data.length > 0) { adropdown.style.display = ""; } else { adropdown.style.display = "none";}

    adropdown.size = min(10, data.length);
    addOption(adropdown, '--select--', '');
    
    for (var i = 0; i < data.length; i = i + 2) {
    
        addOption(adropdown, replace(data[i + 1],"()","") , data[i]);
    }
    if (data.length === 2) {    // a single choice
        atextbox.value = data[1]
        adropdown.style.display = "none"
        //atextbox.style.backgroundColor = "#aaffaa"
        $(atextbox).removeClass("redish").addClass("greenish")
        adropdown.value = data[0]
    }

}


// ======================================================================	;
function autosuggestChanged(abox) {

    abox.nextSibling.value=abox.options[abox.selectedIndex].text;
    abox.style.display='none';
    $(abox.nextSibling).removeClass("redish").addClass("greenish")
}
// ======================================================================	;
function autosuggestClear(abutton) {

    abutton.previousSibling.value = '';
    $(abutton.previousSibling).removeClass('redish');
    $(abutton.previousSibling).removeClass('greenish');
    abutton.previousSibling.previousSibling.style.display = 'none';
    removeAllOptions(abutton.previousSibling.previousSibling)
    addOption(abutton.previousSibling.previousSibling, '--select--', '');
    
}


// ======================================================================	;
function toArray(jsonstuff) {
    var j = 0;

    var myarray = [];
    for (var i = 0; i < jsonstuff.items.length; i++) {
        var rec = jsonstuff.items[i];
        for (var n in rec) {
            fieldname = n;
            //myarray[j]=eval("rec."+trim(fieldname+" "));
            myarray[j] = rec[fieldname];

            j++;
        }
    }

    return myarray;


}


//=======================================================;
function checkReturn(evt) {
    (evt) ? thekey = evt.keyCode : thekey = event.keyCode;
    return (thekey == 13) ? true : false;
}


// ======================================================================	;
function JFgetdata(callback, jsonstuff) {

    var j = 0;
    var myarray = [];
    for (var i = 0; i < jsonstuff.items.length; i++) {
        var rec = jsonstuff.items[i];
        for (var n in rec) {
            fieldname = n;
            myarray[j] = rec[fieldname];
            j++;
        }
    }
    callback(myarray);
}
//===================================================================================================;
function min(a, b) {
    if (a < b) { return a; } else { return b; }
}

//===================================================================================================;
function max(a, b) {
    if (a > b) { return a; } else { return b; }
}
// ======================================================================	;
function addOption(selectbox, text, value,selected) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    optn.selected=selected
    selectbox.options.add(optn);
}

// ======================================================================	;
function showWindow(abutton, target, oldid, atable) {

    adiv = document.createElement("div")
    gebi("frm1").appendChild(adiv)

    adiv.id = "fader"
    adiv.style.position = "absolute"
    adiv.style.top = "-200px"
    adiv.style.left = "-200px"
    adiv.style.width = "200%"
    adiv.style.height = "400%"
    adiv.style.zIndex = 200
    adiv.style.backgroundColor = "#000000"
    $(adiv).css("opacity", 0.5)

    otherdiv = document.createElement("div")
    otherdiv.id = "popwindow"
    otherdiv.style.position = "absolute"
    //otherdiv.style.top = $("#holder_" + oldid).offset().top + "px"
    //otherdiv.style.left = $("#holder_" + oldid).offset().left + "px"
    //otherdiv.style.top = $(abutton).offset().top + "px"
    //otherdiv.style.left = $(abutton).offset().left + "px"

    
    otherdiv.style.zIndex = 201
    gebi("frm1").appendChild(otherdiv)

    var left = (viewport().width / 2) - (100 / 2);
    var top = (viewport().height / 2) - (100 / 2);
    gebi("popwindow").style.top = top - $(gebi("frm1")).offset().top + document.documentElement.scrollTop + "px"
    gebi("popwindow").style.left = $(abutton).position().left + "px"
    
    
    otherdiv.style.zIndex = 310
    //otherdiv.scrollIntoView()
    otherdiv.innerHTML = "<img src=images/wait4.gif>"
    src = cdbiroot + "cdbi_ajax.asp?table=" + atable + "&viewmode=new&id=" + target + "&script=" + scriptName
    src = src + "&c_autosuggestfields=" + gebi("c_autosuggestfields_" + oldid).value
    src = src + "&c_autosuggesttables=" + gebi("c_autosuggesttables_" + oldid).value
    
    $.get(src, function (data) { showWindowCallback(abutton,target, data); });

}

// ======================================================================	;
function showWindowCallback(abutton, target, data) {
    if (typeof data === "object") { data = toArray(data); }



    gebi("popwindow").innerHTML = data

    var w = gebi("popwindow").offsetWidth
    var h = gebi("popwindow").offsetHeight
    var left = (viewport().width / 2) - (w / 2) ;
    var top = (viewport().height / 2) - (h / 2);
    gebi("popwindow").style.top = top - $(gebi("frm1")).offset().top + document.documentElement.scrollTop + "px" 
    gebi("popwindow").style.left=$(abutton).position().left+"px"
    addBehavior()

    if (typeof getContainer!=="undefined") {
        target = replace(getContainer(gebi("popwindow")), "_scroller", "")
        if (haveScrollbar || target.find("modal")) {
            setVsize(target, "checkLast 1");
        }
        else {
            setVsize("all", "checkLast 2");
        }
    }

}

// ======================================================================	;
function viewport() {
    var e = window
, a = 'inner';
    if (!('innerWidth' in window)) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width: e[a + 'Width'], height: e[a + 'Height'] }
}

// ======================================================================	;
function showAjax(target, anaction, atable, aview, viewmode, where, whereval, thepage, thesort, search, allowswitch, defaultpagesize) {

    gebi("action_" + target).value = anaction
    gebi("viewmode_" + target).value = viewmode
    gebi("thepage_" + target).value = thepage
    gebi("sort_" + target).value = thesort
    gebi("search_" + target).value = search
    gebi("allowswitch_" + target).value = allowswitch
    gebi("defaultpagesize_" + target).value = defaultpagesize



    aloc=(document.location+" ").toUpperCase()
    pkvalue=gebi("pkvalue_"+target).value
    //src = "cdbo_ajax.asp?action_" + target + "=" + anaction + "&viewmode_" + target + "=" + viewmode + "&table=" + atable + "&view=" + aview + "&where=" + where + "&whereval=" + whereval + "&id=" + target + "&thepage_" + target + "=" + thepage + "&sort_" + target + "=" + thesort + "&search_" + target + "=" + search + "&allowswitch_" + target + "=" + allowswitch + "&pkvalue_" + target + "=" + pkvalue


    src = cdbiroot + "cdbi_ajax.asp?table=" + atable + "&view=" + aview + "&where=" + where + "&whereval=" + whereval + "&id=" + target 
    

    src = src + "&maskfields=" + gebi("maskfields_" + target).value
    src = src + "&maskvalues=" + gebi("maskvalues_" + target).value
    src = src + "&skipfields=" + gebi("skipfields_" + target).value
    src = src + "&showwhere=" + gebi("showwhere_" + target).value
    src = src + "&alwaysajax=" + gebi("alwaysajax_" + target).value
    src = src + "&c_extrawhere=" + gebi("c_extrawhere_" + target).value
    src = src + "&c_autosuggestfields=" + gebi("c_autosuggestfields_" + target).value
    src = src + "&c_autosuggesttables=" + gebi("c_autosuggesttables_" + target).value
    src = src + "&script=" + encodeURIComponent(scriptName)
    src = src + "&defaultpagesize=" + defaultpagesize
    src = src + "&vbasepath=" + encodeURIComponent(vbasepath)
    if (md5Hash) { src = src + "&md5Hash=" + md5Hash }
    if (site_key) { src = src + "&site_key=" + site_key }
    $("#frm1 input,#frm1 textarea,#frm1 select ").each(function () {
        src=src+"&" +encodeURIComponent(this.name) + "=" + encodeURIComponent(this.value)
    })



    $(".tr_" + target).css("visibility", "hidden")
    if ((viewmode === "edit") || (viewmode == "new")) {

        // hide all other insert delete and edit icons

        $(".editcontrol").css("display", "none")
    }
    else {
        $(".editcontrol").css("display", "")
    }


    gebi("maintable_" + target).style.visibility = "hidden"
    img = document.createElement("img")
    img.src = cdbiroot+"images/wait4.gif"
    img.style.position = "absolute"
    //gebi("maintableholder_" + target).appendChild(img)
    $(img).addClass("wait")
    gebi("maintableholder_" + target).insertBefore(img, gebi("maintable_" + target))
    
    //alert(img.parentNode.id)
    img.style.top  = 40
    img.style.left = 20
    gebi("actor").value=target

    gebi("currentScroll").value = $("#footer_" + target).offset().top
    gebi("currentTop").value = document.body.scrollTop

    $.get(src, function (data) { showAjaxCallback(target,data); });
}

// ======================================================================	;
function showAjaxCallback(target, data) {

    killCDBIPop()
    if (typeof data === "object") { data = toArray(data); }
    adiv = document.createElement("div")
    adiv.id = "holder_" + target
    adiv.innerHTML = data

    gebi("outerholder_" + target).replaceChild(adiv, gebi("outerholder_" + target).childNodes[0])

    $(".popper").hover(function (e) { showCDBIPop(e, this.getAttribute('helptext')); }, function () { killCDBIPop(); });
    deobfuscate()
    initCalendar()
    addBehavior()

    makeLines()

    //$(".maintable input:text")[0].focus()
    lastScroll = gebi("currentScroll").value
    lastTop = gebi("currentTop").value
    now=0
    if (gebi("footer")) {now = $("#footer_" + target).offset().top}
    setTextContainers()
    setTextContainers()

    document.body.scrollTop = lastTop - (lastScroll - now)


        if (typeof getContainer !== "undefined") {
            target = replace(getContainer(gebi("outerholder_" + target)), "_scroller", "")
            if (target !== "") {
                if (haveScrollbar || target.find("modal")) {
                    setVsize(target, "checkLast 1");
                }
                else {
                    setVsize("all", "checkLast 2");
                }
            }
        }



    //adiv.innerHTML = data
    //gebi("table_" + target).parentNode.replaceChild(adiv, gebi("table_" + target))
    //alert(data)
    //gebi("holder_" + target).replaceChild
    //alert("ajax")
}


//=======================================================;
function closePop() {
    if (gebi("fader")) {
        gebi("fader").parentNode.removeChild(gebi("fader"))
        gebi("popwindow").parentNode.removeChild(gebi("popwindow"))
        document.body.style.overflow = ""

    }
}

//=======================================================;
function switchView(id, viewmode, newpage) {
    current = id
    for (var i = current + 1; i < 20; i++) {
        if (gebi("thepage_" + i)) {
            gebi("thepage_" + i).value = 1
        }
    }


    gebi("viewmode_" + id).value = viewmode

    setvalue("thepage_"+id, newpage, true,id)

}

//=======================================================;
function checkReturn(evt) {
    (evt) ? thekey = evt.keyCode : thekey = event.keyCode;
    return (thekey == 13) ? true : false;
}


//=======================================================;
function makeLines() {
    $(".connector").remove()
    $(".maintableholder").each(function(){

        aparent = getParent(this)
        if (aparent) {
            adiv = document.createElement("div")
            document.body.appendChild(adiv)
            adiv.className = "connector"
            adiv.style.height = 50 + "px"
            adiv.style.left = ($(this).offset().left - adiv.offsetWidth)+"px"
            adiv.style.top = ($(aparent).offset().top + aparent.offsetHeight) + "px"
            adiv.style.height = ($(this).offset().top-($(aparent).offset().top+aparent.offsetHeight)+15)+"px"
            //adiv.style.zIndex = 300
        }
    })
}

//=======================================================;
function getParent(obj) {
    // returns the parent object

    alist = $(".maintableholder")
    for (i = 0; i < alist.length; i++) {
        if (obj === alist[i]) {
            start = i
        }
    }

    thisoffset = $(alist[start]).offset().left

    for (i = start - 1; i >= 0; i--) {
        if ($(alist[i]).offset().left === thisoffset - 50) { return alist[i] }
    }
    return false

}


//=======================================================;
function message(something) {
    // alert(something)
}

var newwindow=false

//=======================================================;
function tinyBrowserPopUp(type, formelementid, folder, site_key, id) {

    
    aloc = document.location + " "
    if (aloc.indexOf("/cdbi/")) {
        tburl = folder + "../tinybrowser/tinybrowser.php?type=" + type + "&function=" + encodeURIComponent(formelementid) + "&site_key=" + CDBIDatabase + "&id=" + id + "&vbasepath=" + folder

    }
    else {
        tburl = folder + "tinybrowser/tinybrowser.php?type=" + type + "&function=" + encodeURIComponent(formelementid) + "&site_key=" + CDBIDatabase + "&id=" + id + "&vbasepath=" + folder
    }
   if (newwindow && !newwindow.closed) {
       newwindow.focus()
   }
   else {
		newwindow=window.open(tburl,'tinybrowser','height=480,width=770,scrollbars=yes,resizable=yes');
		if (window.focus) { newwindow.focus() }
    }

	return false;
}

//===================================================================================================
function getWindowSize(item) {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    if (item == 'w') { return parseInt(myWidth, 10); }
    if (item == 'h') { return parseInt(myHeight, 10); }
}

var instance = 0;
var tinyZindex = 11002;
var tinyType = "";
var tinyAction = "";
var tinyBrowserWrapperRef=false
var tinynameOfFunction
// ======================================================================	;

function showTinyB2(atype, action, nameOfFunction) {

    tinyZindex = tinyZindex + 10;
    var caption = "CDBI " + atype + " browser";

    if (action === "upload") {
        src = vbasepath + "tinybrowser/upload.php?type=" + atype + "&function=" + nameOfFunction + "&site_key="  +CDBIDatabase;
    }
    else {
        src = vbasepath + "tinybrowser/tinybrowser.php?type=" + atype + "&function=" + nameOfFunction + "&site_key=" + CDBIDatabase;
    }
    
    aloc=document.location+" "
    if (aloc.indexOf("/cdbi/") !== -1) {
        src="../"+src
    }
    if ((tinyBrowserWrapperRef) && (atype === tinyType) && (nameOfFunction === tinynameOfFunction)) {
        tinyBrowserWrapperRef.show();
        gebi("tinyBrowserWrapper").style.zIndex = tinyZindex;
        setTimeout(function() { tinyBrowserWrapperRef.moveTo("middle", "middle"); }, 500);

        tinyBrowserWrapperRef.onclose = function() {

            tinyBrowserWrapperRef = false;
            return true;
        };
    }

    else {
        tinyType = atype;
        tinyAction = action;

        instance++;
        windowH = parseInt(getWindowSize("h"));
        if (tinyBrowserWrapperRef) { // we already have a window open, but for the wrong type


        }
        tinyBrowserWrapperRef = dhtmlwindow.open(tinyZindex, "tinyBrowserWrapper", "iframe", src, caption, "width=700px,height=" + (windowH - 150) + "px,resize=1,scrolling=1,center=1");
        a = window.frames["_iframe-tinyBrowserWrapper"].document.body;
        a.innerHTML = "<br><br>Loading page..&nbsp;&nbsp;<img src='images/wait.gif' />";
        setTimeout(function() { tinyBrowserWrapperRef.moveTo("middle", "middle"); }, 500);
        tinyBrowserWrapperRef.onclose = function() {

            tinyBrowserWrapperRef.hide();

            return false;
        };
    }
}

function setImage(aninput, objname) {
    if (aninput.value !== "") {
        gebi(objname + "img").style.display = ""
        gebi(objname + "img").src = vbasepath + "image.php?image=" + aninput.value + "&amp;&nocache=1&height=" + c_ihf + "&width=" + c_iwf
    }
    else {
        gebi(objname + "img").style.display = "none"
    }

}

function initCalendar() {
    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        onClose: function()    { this.style.visibility = 'visible'},
        beforeShow: function() { this.style.visibility = 'hidden' }

    });
    $(".datepicker").datepicker("option", "dateFormat", "yy-m-dd ")
  
}    
