// misc js routines
	

// show loader gif
var ajaxGIF='<img src="/bookmark/web9/common/library/images/systems/ajax-loader.gif" alt="Fetching Data" border="0" height="24px" width="24px">';

/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;


function isNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}


function isDate(dtStr){
    
	var daysInMonth = new Array();
        for (var i = 1; i <= 12; i++) {
		daysInMonth[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {daysInMonth[i] = 30}
		if (i==2) {daysInMonth[i] = 29}
         }
        
        
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
   	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

        
	if (pos1==-1 || pos2==-1){
	//	alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
	//	alert("Please enter a valid month")
		return false
	}
        
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
	//	alert("Please enter a valid day")
		return false
	}
        
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
	//	alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
        
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
	//	alert("Please enter a valid date")
		return false
	}
        
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }


var monthNames = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
function dateToExpandedText(d){
    

    m = d.getMonth();
    return d.getDate()+' '+monthNames[m]+' '+d.getFullYear();
}

 
 /*************************************************************************
                                                               pop over routines
 *************************************************************************/
 
var popoverW = 700;
var popoverH = 500;

window.size = function(){
var w = 0;
var h = 0;

//IE
if(!window.innerWidth)
{
    //strict mode
    if(!(document.documentElement.clientWidth == 0))
    {
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    }
    //quirks mode
    else
    {
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
}
//w3c
else
{
    w = window.innerWidth;
    h = window.innerHeight;
}

return {width:w,height:h};
}

window.offset = function(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};

var offsetX = 0;
var offsetY = 0;

//IE
if(!window.pageYOffset)
{
//strict mode
if(!(document.documentElement.scrollTop == 0))
{
offsetY = document.documentElement.scrollTop;
offsetX = document.documentElement.scrollLeft;
}
//quirks mode
else
{
offsetY = document.body.scrollTop;
offsetX = document.body.scrollLeft;
}
}
//w3c
else
{
offsetX = window.pageXOffset;
offsetY = window.pageYOffset;
}


return{x:offsetX,y:offsetY};
}


 
function setBlankerPos(){

	var blanker = document.getElementById('blanker');	
	var popover = document.getElementById('popover');	
	var w=window.size().width;
	var h=window.size().height;
	var offsetY=window.offset().y;
// lee change: added + 'px' to sizes so assigned correctly in firefox etc - not needed in some other doctypes
	blanker.style.width=w-21 + 'px';
	blanker.style.height=h-20 + 'px';
	blanker.style.top=offsetY-1 + 'px';

	popover.style.width=popoverW + 'px';
	popover.style.height=popoverH + 'px';
	
	l = (w - popoverW)/2;
	l-=20; //assum right hand scroll bar
	popover.style.left = l + 'px';
	popover.style.top= offsetY+((h - popoverH) * 1 / 3) + 'px';//start 1/3 down the page
	
}


 
 function showBlanker(bTitle,bHeader,bBody){
     
	 setBlankerPos();
	
	document.getElementById('popoverTitle').innerHTML = bTitle;
	document.getElementById('popoverHeader').innerHTML = bHeader;
	document.getElementById('popoverBody').innerHTML = bBody;
	document.getElementById('blanker').style.display='';	
	document.getElementById('popover').style.display='';	
	
	//document.getElementById('HOME').style.display  = 'none';
}


function hideBlanker(){

	document.getElementById('blanker').style.display='none';
	document.getElementById('popover').style.display='none';
        //lee change: changed the below to the above
	//blanker.style.display='none';
	//popover.style.display='none';
}


function shiftBlanker(){
	
	setBlankerPos();
}

/******************************************************************************
                                               GENERIC SEARCH BOX ROUTINES
******************************************************************************/

// to set up a search box, call
// setSearch(title,procTag,callbackKey,class,fixedParams)
// this returns a number which is the id of the search box (its index in the _sb array) although there
// should only ever be one
// title : search box title
// procTag : the online_accessible_procs procTag of this search
// callbackKey : the key value used by OnSucceededWithContext
// class : class to be applied to <tr><td><input><select> etc (class needs to be defined on form's style sheet)
// fixedparams : additional params to be sent to search proc that are not editable eg, in exam screens, atp search needs to know service id of exam but shouldn't allow it to be edited, so pass when setting up search : added tmc 25 feb 2010
//                         can be changed after the search has been created by setSearchFixedParams

//
// then call (for each search field) one of the following
//addSearchInput(searchindex,newrow,prompt,mandatory,default,validation,values)
//addSearchRadio(searchindex,newrow,prompt,mandatory,default,validation,values)
//addSearchSelect(searchindex,newrow,prompt,mandatory,default,validation,values)
//addSearchCheckbox(searchindex,newrow,prompt,mandatory,default,validation,values)


// searchindex : the return value from setSearch
// row : start on a new row in the table of fields (1) or show on same row as previous field (0)
// prompt : the label for this search field
// default : optional default value
// mandatory : 0 = field is not mandatory, 1 = at least one of the fields with mandatory = 1 must have a value, 2 = this field must have a value
// validation : not yet used, but will be validation for this field
// values : csv list of possible values

// finally, activate the search with displaySearch(searchindex)

// note : the ajax will build up csv string of parameters based on the
// values returned from the search fields
// note that the parameters will be built in the order the addSearch... functions were called above

// example
// for events
//
// on the form, set eventSearch = -1
// 
// in the search function

//  if (eventSearch==-1){
// 	eventSearch = setSearch('Search Events','srchevent','SearchEvents')
// 	addSearchInput(eventSearch,1,'Code',1,'','','');
// 	addSearchInput(eventSearch,1,'Description',1,'','','');
// 	addSearchRadio(eventSearch,0,'Status',0,'1','','Active=1,Inactive=0,All=2');
//   }
//   displaySearch(eventSearch)

// the searchbox itself will call the ExecCascadeQuery
// so it is self contained
//
// on the form, the OnSucceededWithContext should populate the popoverbody with search results
// AND use storeSearchContent to remember the result to re-display if we re-open the search
// eg
//if (userContext == 'SearchEvents'||userContext == 'SearchVenues'||userContext == 'SearchPersons')
//                   {
//                     //handle_xml(userContext,result);
//
//					   res=xmldoc2table('No items found matching this search');
//                                           storeSearchContent(eventSearch,res)
//					   document.getElementById('popoverBody').innerHTML = res;
//                    }



var _sb = new Array(); // array of search boxes




function _searchBox(schTitle,schTag,schKey,schClass,schFixedParams){
	this.schTitle= schTitle;
	this.schTag= schTag;
	this.schKey=schKey;
	this.schClass = schClass;
	this.schFixedParams = schFixedParams;
        this.content = ''; // remember the last content so we can
	this._sbf = new Array();
}


function storeSearchContent(searchindex,content){ // remember the result of the search so we can re-present it if we re-open the search box
  _sb[searchindex].content = content;
}
function setSearch(schTitle,schTag,schKey,schClass,schFixedParams){
	_sb[_sb.length]=new _searchBox(schTitle,schTag,schKey,schClass,schFixedParams);
	return _sb.length-1;
}

//addSearchInput(searchindex,row,prompt,mandatory,default,validation,values)

function _searchfield(searchindex,newrow,prompt,mandatory,defaultvalue,validation,values,type){
	this.searchindex = searchindex;
	this.newrow=newrow;
	this.prompt=prompt;
	this.mandatory=mandatory;
	this.defaultvalue=defaultvalue;
	this.validation=validation;
	this.values=values;
	this.type=type;
}



function setSearchDefault(searchIndex,searchFieldIndex,value){ // used when reopening existing search to set the values to the last entered
    _sb[searchIndex]._sbf[searchFieldIndex].defaultvalue=value;
}
function setSearchFixedParams(searchIndex,schFixedParams){
	_sb[searchindex].schFixedParams = schFixedParams;
}


function addSearchInput(searchindex,newrow,prompt,mandatory,defaultvalue,validation,values){
	nr = newrow;
	if(_sb[searchindex]._sbf.length==0){nr=1} // first field is always a new row even if not specified!
	_sb[searchindex]._sbf[_sb[searchindex]._sbf.length] = new _searchfield(searchindex,nr,prompt,mandatory,defaultvalue,validation,values,1);
}

function addSearchRadio(searchindex,newrow,prompt,mandatory,defaultvalue,validation,values){
	nr = newrow;
	if(_sb[searchindex]._sbf.length==0){nr=1} // first field is always a new row even if not specified!
	_sb[searchindex]._sbf[_sb[searchindex]._sbf.length] = new _searchfield(searchindex,nr,prompt,mandatory,defaultvalue,validation,values,2);
}

/*
checkbox not yet implemented as no default way to handle multiple values in the ajax params
function addSearchCheckbox(searchindex,newrow,prompt,mandatory,defaultvalue,validation,values){
	nr = newrow;
	if(_sb[searchindex]._sbf.length==0){nr=1} // first field is always a new row even if not specified!
	_sb[searchindex]._sbf[_sb[searchindex]._sbf.length] = new _searchfield(searchindex,nr,prompt,mandatory,defaultvalue,validation,values,3);
}
*/

function addSearchSelect(searchindex,newrow,prompt,mandatory,defaultvalue,validation,values){
	nr = newrow;
	if(_sb[searchindex]._sbf.length==0){nr=1} // first field is always a new row even if not specified!
	_sb[searchindex]._sbf[_sb[searchindex]._sbf.length] = new _searchfield(searchindex,nr,prompt,mandatory,defaultvalue,validation,values,4);
}

function displaySearch(searchindex){
    
	// first build html

	// first work out how many columns we need - ie max no of fields that share the same row
	maxcols = 0;
	cols=0;
	for(i=0;i<_sb[searchindex]._sbf.length;i++){
		nr = _sb[searchindex]._sbf[i].newrow;
			
		if (nr==0){cols+=1}else{cols=1} //increment columns if not a new row
		if(cols>maxcols){maxcols=cols}
	}
	//
	// ok now build html string
	//
	_html = '';
	cols = 0;
	cl = _sb[searchindex].schClass;
	clH = 'class = "' + cl + '"'
	
	for(i=0;i<_sb[searchindex]._sbf.length;i++){
	    sbfield = _sb[searchindex]._sbf[i];
	
		if(sbfield.newrow==1){ // new row, so start new <tr>
			
			if (i>0){ // if not first field, close off previous row
				// first, pad to needed columns
				
				for(j=cols;j<maxcols;j++){
					_html+='<td ' + clH+'>&nbsp;</td><td ' + clH+'>&nbsp;</td>';
				}
				
				_html+='</tr>'
			}
			_html+='<tr ' + clH+' >';
			cols=0;
		} // 	if(sbfield.newrow==1){
		//
		// ok,now add the field
		//
		cols+=1;
		_html+='<td ' + clH+'>' + sbfield.prompt+'</td>';
		
		// now add input
		_html+='<td '+clH+'>' ;
		fieldname = 's_'+searchindex+'_'+i;
		fH = 'name ="' + fieldname+'"';
		switch(sbfield.type){
			
			case(1): // text input
				_html+='<input  '+clH+' '+fH;
				if(sbfield.defaultvalue!=''){_html+=' value="' + sbfield.defaultvalue+'"'}
				_html+='>' ;
				break;
			
			case (2): //radio button
				valpairs = sbfield.values.split(',');
				for(vp=0;vp<valpairs.length;vp++){
					valp = valpairs[vp].split('=');
					_html+='<input type = "radio" ' + clH+' '+fH;
					_html+='  value="'+valp[1]+'"';
					if(valp[1]==sbfield.defaultvalue){_html+=' checked=true '}
					_html+='>'+valp[0];
				}
				break;
			
				
				case (3): //check box
				valpairs = sbfield.values.split(',');
				for(vp=0;vp<valpairs.length;vp++){
					valp = valpairs[vp].split('=');
					_html+='<input type = "checkbox" ' + clH+' '+fH;
					_html+='  value="'+valp[1]+'"';
					if(valp[1]==sbfield.defaultvalue){_html+=' checked="true" '}
					_html+='>'+valp[0];
				}
					break;
				
				
				case (4): //select
				valpairs = sbfield.values.split(',');
				_html+='<select ' + clH+' ' + fH+'>';
					_html+='<option value="">Select...</option>';
				
				for(vp=0;vp<valpairs.length;vp++){
					valp = valpairs[vp].split('=');
					_html+='<option value="' + valp[1]+'" ';
					if(valp[1]==sbfield.defaultvalue){_html+='selected="selected" '}
					_html+='>'+valp[0]+'</option>';
				}
				_html+='</select>';
				
				break;
		}
		
		
		_html+='</td>';
			
		
	} // 	for(i=0;i<_sb[searchindex]._sbf.length;i++){
	
	if(_html!=''){
		// first, pad to needed columns
				for(j=cols;j<maxcols;j++){
					_html+='<td>&nbsp;</td><td>&nbsp;</td>';
				}
		// now add search button
		_html+='<tr '+clH+'><td '+clH+'><input onclick="goSearch(' + searchindex+');" type="button" value="search" ' + clH+'></td><td '+clH+'>&nbsp;</td>';		
		cols=1;
		for(j=cols;j<maxcols;j++){
			_html+='<td>&nbsp;</td><td>&nbsp;</td>';
		}
		_html='<table '+clH+' width="100%">'+_html+'</tr></table>';
	}
	
	//alert(searchindex)
	//alert(_html);
	
	showBlanker('<h4>'+_sb[searchindex].schTitle+'</h4>',_html,_sb[searchindex].content);
	//alert(23);
	// now adjust height of popover body as Header height changes dependent on the number of rows of search fields
	h = document.getElementById('popoverTitle').offsetHeight + document.getElementById('popoverHeader').offsetHeight;
	bh = 470-h;
	bhp = bh+'px';
	document.getElementById('popoverBody').style.height = bhp;
	
	if(_sb[searchindex]._sbf.length>0){
		focusname = 's_'+searchindex+'_'+0;
		//document.forms[0](focusname).focus();
                document.forms[0][focusname].focus();
	}
	
	

	
	
}

function goSearch(searchindex){
	// get all values and build parameter string
	// check mandatory fields found

	// still need to add checks for valid values
	var anyMand = false; // fields where mandatory = 1 (any one of these fields having a value will suffice)
	var anyMandCount = 0; // fields where mandatory = 1 (as above) - if > 0 and anyMand still false at end, no mand field has value
	var Mand = true; // fields that must have a value
	var fm = document.forms[0];
	var anyMandErrorList = '';
	var MandErrorList = '';
	
	var invalidValues=false;//an input field does not contain a valid value
	var invalidValuesList='';//an input field does not contain a valid value
	
	
	var ajaxParams = '';
	
	for(i=0;i<_sb[searchindex]._sbf.length;i++){
		sbfield = _sb[searchindex]._sbf[i];
		fieldname = 's_'+searchindex+'_'+i;
		
		
		
		var fval = '';
		var fmand = sbfield.mandatory;
		if(fmand==1){anyMandErrorList+=sbfield.prompt+'\n'} // in case we need to display list of mandatory=1 fields ie, if none have a value
		
		switch (sbfield.type){
			case(1): //input
				fval = fm(fieldname).value;
				// acceptable value?
				fok = true;
				if(sbfield.values!=''){
					valpairs = sbfield.values.split(',');
					fok=false;
					for(vp=0;vp<valpairs.length;vp++){
						valp = valpairs[vp].split('=');
						if(fval==valp[0]){fok=true}					
					}
				}
				if (fok==false){
					invalidValues=true;//an input field does not contain a valid value
					invalidValuesList+=sbfield.prompt+'\n';//an input field does not contain a valid value
				}
			
			
			
				break;
			case(2): //radio
				for(r=0;r<fm(fieldname).length;r++){
					if(fm(fieldname)[r].checked){fval=fm(fieldname)[r].value}
				}
				break;
			//case(3): //input
				//fval = fm(fieldname).value;
				//break;
			case(4): //select
				fval = fm(fieldname).options[fm(fieldname).selectedIndex].value;
				break;
				
		}  //  switch (sbfield.type){
		if(fmand==1){anyMandCount+=1}
		// check mandatory
		if (fval==''){
			if (fmand==2){
				Mand=false
				MandErrorList+=sbfield.prompt+'\n';
			} // mandatory field has no value
		}else{
			if(fmand==1){anyMand=true}//at least one of the mandatory = 1 fields has a value
		}
		
		
		// ok so now build ajax params
		if(i>0){
			ajaxParams+=',';
		}
                // mod tim crannigan 12 may 2010
                // remember values so if user reopens search, they are rememberer
                setSearchDefault(searchindex,i,fval);
		ajaxParams+="'"+fval+"'"
		
	} // for(i=0;i<_sb[searchindex]._sbf.length;i++){
	
	
	
	if(anyMand==false&&anyMandCount>0){
		alert('At least one of the following fields must have a value before searching : \n'+anyMandErrorList);
		return false;
	}
	
	
	if(Mand==false){
		alert('The following fields fields must have a value before searching : \n'+MandErrorList);
		return false;
	}
	
	
	if(invalidValues==true){
		alert('The following fields field(s) contain an invalid value: \n'+invalidValuesList);
		return false;
	}
	
	
	fixedParams = _sb[searchindex].schFixedParams;
	if(fixedParams==undefined){fixedParams=''}
	if(fixedParams==null){fixedParams=''}
	
	
	if(fixedParams!=''){
		ajaxParams+=','+fixedParams;
	}
	//alert(ajaxParams);
	
	//alert(_sb[searchindex].schTag);
	runSearch(_sb[searchindex].schTag,_sb[searchindex].schKey,ajaxParams);
	
	
}

function runSearch(schTag,schKey,Params){
var fm = document.forms[0];
	var s 
	var params
	var appid
	var password
	s = GetUserSessionID();
	appid = GetAppID();
	password = GetAppPassword();
	
			document.getElementById('popoverBody').innerHTML = '<div width="100%" align="center" ><img         src="App_Themes/DefaultTheme/Images/bookmark_data/ajax-loader.gif"></div>';
                        //a = prompt('debug',Params)
	ExecCascadeQueryXML( schTag, Params, s, appid, password, schKey );
	
	
}


/******************************************************************************
                                                    WEB HTML CONTROL ROUTINES FOR FORMS
******************************************************************************/

pathError=0;

function cleanPath(inPath){
	
	// clean path to image in case using share or direct link
	pathError = 0;
	
	
	image = inPath;
	
	
	image=image.toUpperCase();



	image=image.replace(/\\/g,'\/');
	//pathCheck='\\\\SI817\\SII ROOT\\WEBSITE FILES\\';
	//        pathCheck='//SI817/SII ROOT/WEBSITE FILES/';
        pathCheck='//CISIPDC/CISI ROOT/SI475_LIBRARY/';
	ii=image.indexOf(pathCheck);
	
	if (ii==-1){
		alert('Images and file must be in ' + pathCheck+' (your selection ='+image+')');
		pathError=1;
		return false;
	}

        if(image.indexOf('\'')!=-1){
            alert('Files may not contain the single quote character (\')');
            pathError=1;
            return false;
        }

	
	
	image=image.substring(pathCheck.length-1,image.length);
	

	
		
	image='/BOOKMARK/WEB9/COMMON/LIBRARY'+image;
	return image;
}



// generic tinyMCE insert text function
function insertText(txt){
		tinyMCE.execCommand('mceInsertContent',false,txt);
	//tinyMCE.execInstanceCommand('mceInsertContent',false,txt);
}



//-----------------------------------------------------
//                         INSERT FILE
//-----------------------------------------------------


function insertFile(img){
//	alert('Files must be in the Bookmark application folder /web9/common/library/files');
	document.getElementById('LOCAL_FILE_CONTROL').click();
	
}


function getFile(){
	
	
	
	var fm = document.forms[0];
	fileimage = fm('LOCAL_FILE_CONTROL').value;
	fileimage=fileimage.toUpperCase();
	if (fileimage==''){return false}
	
	fileimage = cleanPath(fileimage);
	
	if(pathError!=0){	return false;}
	
	
	a = prompt('Enter link for this file','');
	
	ig = '<a href="'+fileimage+'" target="_blank">' + a + '</a>';
	insertText(ig);
}
//-----------------------------------------------------
//                         END INSERT FILE
//-----------------------------------------------------


//-----------------------------------------------------
//                            INSERT IMAGE
//-----------------------------------------------------



function insertImage(img){
//	alert('Images must be in the Bookmark application folder /web9/common/library/files');
	document.getElementById('LOCAL_IMAGE_CONTROL').click();
	
}


function getImage(){
	
	
	var fm = document.forms[0];3
	fileimage = fm('LOCAL_IMAGE_CONTROL').value;
	
	if (fileimage==''){return false}
	
	fileimage = cleanPath(fileimage);
	
	if(pathError!=0){	return false;}
	
	
	a = prompt("Please enter the 'Alt Text' for this image","");
	if (a==''){
		alert('You must supply \'Alt Text\' for images');
		return false;
	}
	ig = '<img src="' + fileimage+'" alt="' + a+'">';
	
	
		
	insertText(ig);
}



function getImage_Field(Fieldname){
	
	//alert( Fieldname);
	var fm = document.forms[0];

	
	fileimage = fm('LOCAL_IMAGE_CONTROL').value;
	
	if (fileimage==''){return false}
	
	fileimage = cleanPath(fileimage);
	
	if(pathError!=0){	return false;}
		
	a = prompt("Please enter the 'Alt Text' for this image","");
	if (a==''){
		alert('You must supply \'Alt Text\' for images');
		return false;
	}
	
	document.getElementById(Fieldname).value =  '<img src="' + fileimage+'" alt="' + a+'">';	 
	
}

	

//-----------------------------------------------------
//                            END INSERT IMAGE
//-----------------------------------------------------	


/*******************************************************
                         AJAX / XML ROUTINES
*******************************************************/



function execProc(procTag,params,Context){
	var s 
	var appid
	var password
	s = GetUserSessionID();
	appid = GetAppID();
	password = GetAppPassword();
        //
        //var a = prompt ('',s);
	//var a = prompt ('',appid);
        //var a = prompt ('',password);
        //var a = prompt ('',params);
        
	ExecCascadeQueryXML(procTag, params, s, appid, password, Context	);
}



function postAjax(procTag,params,Context){
	var s 
	var appid
	var password
	s = GetUserSessionID();
	appid = GetAppID();
	password = GetAppPassword();
	
	//showNotification('');
	ExecCascadeQueryXML(procTag, params, s, appid, password, Context	);
	
}



function parseXML(inxml){
// take incoming xml from ajax and convert to XML document

try //Internet Explorer
 {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(inxml);

  }
catch(e)
 {
 try//Firefox,Mozilla, Opera,etc.
 {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(inxml,"text/xml");
  }
  catch(e)
  {
  alert(e.message);
  return;
  }
}
}


var tim = 0;
function getNode(nodename){
	
// revised getNode function
	if(xmlDoc.getElementsByTagName(nodename)[0]==null){return ''};
        if(xmlDoc.getElementsByTagName(nodename)[0].childNodes.length<1){return ''};
        //if(tim==1){
            rn = ''
            for(rni=0;rni<xmlDoc.getElementsByTagName(nodename)[0].childNodes.length;rni++){
                rn+=xmlDoc.getElementsByTagName(nodename)[0].childNodes[rni].nodeValue
            }
          //  alert(rn.length)
        //}
        return rn
        //return xmlDoc.getElementsByTagName(nodename)[0].childNodes[0].nodeValue;
}



function hex2Char(inst){
    outst = inst;
    outst = outst.replace(/_x002F_/gi,'/')
    return outst;
}

function xmldoc2table(  noRecordmessage ){
	// automatically display table based on xmldoc attributes eg from search
	//kxa 03/02/2010 made changes so the function returned the result and introduced parameter noRecordmessage. Tim is going make any necessary changes to the forms.
var res = '';
var res_head='';
var res_data = '';
var row_data = '';
var rowcount = 0;
var rc=-1;
var rs='tr2';
var colcount = 0;

y=xmlDoc.documentElement.childNodes;

// loop through root nodes

//alert('nodes : ' + y.length);
for (i=0;i<y.length;i++){
  if (y[i].nodeType!=3&&y[i].nodeName=='Results'){
          //loop through children of 'Results'
          
            row_data = '';
            for (z=0;z<y[i].childNodes.length;z++){
               
                 if (y[i].childNodes[z].nodeType!=3){
                       colcount+=1;
                       if (rowcount==0){
                            colTitle = y[i].childNodes[z].nodeName;
                            colTitle = colTitle.replace(/_x0020_/gi," ")
                            //res_head=res_head+'<th class="ajaxTbl"><b>'+hex2Char(y[i].childNodes[z].nodeName)+'</b></th>'
                            res_head=res_head+'<th class="ajaxTbl ajaxTbl_col_'+colcount+'"><b>'+colTitle+'</b></th>'
                           
                       }
                        nodeValue = '';
                        if (y[i].childNodes[z].hasChildNodes()==true){
                                nodeValue=y[i].childNodes[z].childNodes[0].nodeValue
                        }
                        row_data=row_data+'<td class="ajaxTbl ajaxTbl_col_'+colcount+'">'+ nodeValue + '</td>';

                  }
            }  //             for (z=0;z<y[i].childNodes.length;z++){

           
            if (row_data!=''){
                                    rc=rc*-1;
                                    if (rc==1){rs='tr1'}else{rs='tr2'}      

                                    res_data=res_data+'<tr class="' + rs+'">'+row_data+'</tr>'
                                    }
                 rowcount+=1;
                 colcount=0;
       } //       if (y[i].nodeType!=3&&y[i].nodeName=='Results'){

     

}  //for (i=0;i<y.length;i++){


if(res_data!=''){
          res_head = '<thead class="ajaxTableHEAD"><tr class="tr2">' + res_head+'</tr></thead>';
          res_data = '<tbody class="ajaxTableBODY">' + res_data+'</tbody><tfoot></tfoot>';
          res = '<table id="ajaxTable" cellspacing="2px" width="100%">' + res_head + res_data + '</table>' ;
}
else{
	if (noRecordmessage == null )
	{	      	
        res= '<b>RESULT</b><br>No Data Found';		
	}	
	else
	{
		res= '<b>RESULT</b><br>'+noRecordmessage;
	}
}

	//document.getElementById('popoverBody').innerHTML = res;
        
return res
}















//xml audit based on triggers

var BA = new Array();
function clearBA(){
	BA=[];
}

function BAitem(name,before,after){
	
	this.name = name;
	this.before = before;
	this.after = after;
	
}

function add2BA(name,val,beforeORafter){
	//add to BA array
	
	BAindex=-1;
	for(j=0;j<BA.length;j++){
		if(BA[j].name == name){
			BAindex=j; // found
		}
	}
	// found?
	if(BAindex==-1){ // new
		if(beforeORafter==0){
			BA[BA.length] = new BAitem(name,val,'');
		}else{
			BA[BA.length] = new BAitem(name,'',val);
		}
	}else{
		if(beforeORafter==0){
			BA[BAindex].before=val;
		}else{
			BA[BAindex].after=val;
		}
	}
	
	
}



function buildBeforeAfter(baAttributes,beforeORafter){
	for(i=0;i<baAttributes.length;i++){
		baName = baAttributes[i].name;
		baValue = baAttributes[i].value;
		add2BA(baName,baValue,beforeORafter);
	}
	
}








var qsar = new Array();
var qsarInit = 0;
function parseQuerystring(){
	qs = unescape( window.location.search.substring(1));
	qsar = qs.split("&");
}

function getQuerystring(item){
        if(qsarInit==0){
            parseQuerystring();
            qsarInit=1;
        }
	var qi='';
	var qspr = new Array();
	for(q=0;q<qsar.length;q++){
		qspair = qsar[q];
		qspr = qspair.split('=');
		if(qspr[0].toUpperCase()==item.toUpperCase()){qi=qspr[1]}
	}
	return qi;
}


function elementHeightChange(fname,chg){
       h=$('#'+fname).height();
    if ((h+chg)>0){
            h=h+chg+'px';
    }
    $('#'+fname).css('height',h)

}





/*************** cookies moved from bdf_cookies.js 8 nov 2010 *****************/
function Set_Cookie( name, value, expires, path, domain, secure )
{
   

// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );


//if the expires variable is set, make the correct
//expires time, the current script below will set
//it for x number of days, to make it for hours,
//delete * 24, for minutes, delete * 60 * 24

if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

dc = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );

//alert('dc = '+dc)
document.cookie = dc;

}



// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}



// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}




// if a function exists on the page, run it
function callIfFunctionExists(fname){
    
  if(typeof window[fname]!='undefined'){
          return eval(fname+'();')
      }else {
                    return '';
      }
}


function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
}


/***************************************************************
**
**   Script by Small Hadron Collider
**   http://www.smallhadroncollider.com
**
**   Distributed under a Creative Commons by-sa License
**   http://creativecommons.org/licenses/by-sa/3.0/
**
**   WARNING: Top 500 passwords array at the bottom contains
**            naughty words. Don't look at it if you're easily
**            offended.
**
***************************************************************/

// Usage: Pass the password string to passwordStrength and string with time it will take is returned

function passwordStrength(password)
{

	// Get password length
	var length = password.length;

	// Check password against common passwords of that length to see if it's in top 500
	if (length > 2 && length < 9)
	{
		for (var i=0; i<arrayOfPasswords[length].length; i++)
		{
			if (password.toLowerCase() == arrayOfPasswords[length][i])
			{
				return 'One of the 500 most common passwords';
			}
		}
	}


	// Calculations per second. Ten million is roughly the number a decent PC could manage uninhibited
	var calculationsPerSecond = 10000000;


	// Keep track of how many character sets are used
	var possibleCharacters = 0;

	// Lowercase
	if (password.match(/[a-z]/)) {possibleCharacters += 26;}

	// Uppercase
	if (password.match(/[A-Z]/)) {possibleCharacters += 26;}

	// Numbers
	if (password.match(/\d+/)) {possibleCharacters += 10;}

	// Symbols
	if (password.match(/[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) {possibleCharacters += 13};


	// Work out the number of possible combinations: possible characters to the power of the password length
	var possibleCombinations = Math.pow(possibleCharacters, password.length);

	// Divide the number of possible combinations by the calculations a PC can do per second
	var computerTimeInSecs = possibleCombinations / calculationsPerSecond;


	// Set up an array of periods with their lenghts in seconds
	var arrayOfPeriods = new Array();
	arrayOfPeriods['minute'] = 60;
	arrayOfPeriods['hour'] = arrayOfPeriods['minute'] * 60;
	arrayOfPeriods['day'] = arrayOfPeriods['hour'] * 24;
	arrayOfPeriods['year'] = arrayOfPeriods['day'] * 365.25;
	arrayOfPeriods['thousand years'] = arrayOfPeriods['year'] * 1000;
	arrayOfPeriods['million years'] = arrayOfPeriods['thousand years'] * 1000;
	arrayOfPeriods['billion years'] = arrayOfPeriods['million years'] * 1000;
	arrayOfPeriods['trillion years'] = arrayOfPeriods['billion years'] * 1000;
	arrayOfPeriods['quadtrillion years'] = arrayOfPeriods['trillion years'] * 1000;
	arrayOfPeriods['quintillion years'] = arrayOfPeriods['quadtrillion years'] * 1000;
	arrayOfPeriods['sextillion years'] = arrayOfPeriods['quintillion years'] * 1000;
	arrayOfPeriods['septillion years'] = arrayOfPeriods['sextillion years'] * 1000;
	arrayOfPeriods['octillion years'] = arrayOfPeriods['septillion years'] * 1000;
	arrayOfPeriods['nonillion years'] = arrayOfPeriods['octillion years'] * 1000;


	// Period type is 'seconds' by default
	var periodType = 'second';
	var strength = '';

	// If it will take less than a second to crack the password, show exactly how long
	if (computerTimeInSecs < 1) {strength = computerTimeInSecs+" seconds";}

	// Otherwise show a rounded-down number
	else
	{

		// Adds the 's' onto anything before a thousand years
		var intoThousands = 's';

		// Adds the 'About' to anything after seconds
		var intoMinutes = '';

		// Round down the time
		var newTime = Math.floor(computerTimeInSecs);

		// Go through different period lengths
		for (var i in arrayOfPeriods)
		{
			// Stop when got to right period
			if (computerTimeInSecs < arrayOfPeriods[i]) {break;}
			else
			{
				if (i == "thousand years") {intoThousands = '';}
				if (i == "minute") {intoMinutes = 'About ';}
				newTime = Math.floor(computerTimeInSecs / arrayOfPeriods[i]);
				periodType = i;
			}
		}

		// If singular
		if (newTime == 1)
		{
			var aType = 'a ';

			// Puts 'an' where needed
			if (periodType == 'hour' || periodType == 'octillion years')
			{
				aType = 'an ';
			}

			strength = "About "+aType+periodType;
		}
		else
		{
			// Convert newTime to string
			newTime += '';

			// Split with commas every three digits
			var regex = /(\d+)(\d{3})/;

			while (regex.test(newTime))
			{
				newTime = newTime.replace(regex, '$1' + ',' + '$2');
			}

			// Combine with 'about' if needed, the time it will take, the period type, and the 's' if needed
			strength = intoMinutes+newTime+" "+periodType+intoThousands;
		}
	}

	return strength;
}


function passwordStrengthType(password)
{

	// Get password length
	var length = password.length;

	// Check password against common passwords of that length to see if it's in top 500
	if (length > 2 && length < 9)
	{
		for (var i=0; i<arrayOfPasswords[length].length; i++)
		{
			if (password.toLowerCase() == arrayOfPasswords[length][i])
			{
				return 'One of the 500 most common passwords';
			}
		}
	}


	// Calculations per second. Ten million is roughly the number a decent PC could manage uninhibited
	var calculationsPerSecond = 10000000;


	// Keep track of how many character sets are used
	var possibleCharacters = 0;

	// Lowercase
	if (password.match(/[a-z]/)) {possibleCharacters += 26;}

	// Uppercase
	if (password.match(/[A-Z]/)) {possibleCharacters += 26;}

	// Numbers
	if (password.match(/\d+/)) {possibleCharacters += 10;}

	// Symbols
	if (password.match(/[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) {possibleCharacters += 13};


	// Work out the number of possible combinations: possible characters to the power of the password length
	var possibleCombinations = Math.pow(possibleCharacters, password.length);

	// Divide the number of possible combinations by the calculations a PC can do per second
	var computerTimeInSecs = possibleCombinations / calculationsPerSecond;


	if (computerTimeInSecs <= 3600) {strength = "weak"}
        if (computerTimeInSecs > 360&&computerTimeInSecs<= 86400) {strength = "medium"}
        if (computerTimeInSecs > 86400) {strength = "strong"}




	return strength;
}


var arrayOfPasswords = new Array();

arrayOfPasswords[3] = ['god','sex'];

arrayOfPasswords[4] = ['1234','cool','1313','star','golf','bear','dave','pass','aaaa','6969','jake','matt','1212','fish','fuck','porn','4321','2000','4128','test','shit','love','baby','cunt','mark','3333','john','sexy','5150','4444','2112','fred','mike','1111','tits','paul','mine','king','fire','5555','slut','girl','2222','asdf','time','7777','rock','xxxx','ford','dick','bill','wolf','blue','alex','cock','beer','eric','6666','jack'];

arrayOfPasswords[5] = ['beach','great','black','pussy','12345','frank','tiger','japan','money','naked','11111','angel','stars','apple','porno','steve','viper','horny','ou812','kevin','buddy','teens','young','jason','lucky','girls','lover','brian','kitty','bubba','happy','cream','james','xxxxx','booty','kelly','boobs','penis','eagle','white','enter','chevy','smith','chris','green','sammy','super','magic','power','enjoy','scott','david','video','qwert','paris','women','juice','dirty','music','peter','bitch','house','hello','billy','movie'];

arrayOfPasswords[6] = ['123456','prince','guitar','butter','jaguar','united','turtle','muffin','cooper','nascar','redsox','dragon','zxcvbn','qwerty','tomcat','696969','654321','murphy','987654','amanda','brazil','wizard','hannah','lauren','master','doctor','eagle1','gators','squirt','shadow','mickey','mother','monkey','bailey','junior','nathan','abc123','knight','alexis','iceman','fuckme','tigers','badboy','bonnie','purple','debbie','angela','jordan','andrea','spider','harley','ranger','dakota','booger','iwantu','aaaaaa','lovers','player','flyers','suckit','hunter','beaver','morgan','matrix','boomer','runner','batman','scooby','edward','thomas','walter','helpme','gordon','tigger','jackie','casper','robert','booboo','boston','monica','stupid','access','coffee','braves','xxxxxx','yankee','saturn','buster','gemini','barney','apples','soccer','rabbit','victor','august','hockey','peanut','tucker','killer','canada','george','johnny','sierra','blazer','andrew','spanky','doggie','232323','winter','zzzzzz','brandy','gunner','beavis','compaq','horney','112233','carlos','arthur','dallas','tennis','sophie','ladies','calvin','shaved','pepper','giants','surfer','fender','samson','austin','member','blonde','blowme','fucked','daniel','donald','golden','golfer','cookie','summer','bronco','racing','sandra','hammer','pookie','joseph','hentai','joshua','diablo','birdie','maggie','sexsex','little','biteme','666666','topgun','ashley','willie','sticky','cowboy','animal','silver','yamaha','qazwsx','fucker','justin','skippy','orange','banana','lakers','marvin','merlin','driver','rachel','marine','slayer','angels','asdfgh','bigdog','vagina','apollo','cheese','toyota','parker','maddog','travis','121212','london','hotdog','wilson','sydney','martin','dennis','voodoo','ginger','magnum','action','nicole','carter','erotic','sparky','jasper','777777','yellow','smokey','dreams','camaro','xavier','teresa','freddy','secret','steven','jeremy','viking','falcon','snoopy','russia','taylor','nipple','111111','eagles','131313','winner','tester','123123','miller','rocket','legend','flower','theman','please','oliver','albert'];

arrayOfPasswords[7] = ['porsche','rosebud','chelsea','amateur','7777777','diamond','tiffany','jackson','scorpio','cameron','testing','shannon','madison','mustang','bond007','letmein','michael','gateway','phoenix','thx1138','raiders','forever','peaches','jasmine','melissa','gregory','cowboys','dolphin','charles','cumshot','college','bulldog','1234567','ncc1701','gandalf','leather','cumming','hunting','charlie','rainbow','asshole','bigcock','fuckyou','jessica','panties','johnson','naughty','brandon','anthony','william','ferrari','chicken','heather','chicago','voyager','yankees','rangers','packers','newyork','trouble','bigtits','winston','thunder','welcome','bitches','warrior','panther','broncos','richard','8675309','private','zxcvbnm','nipples','blondes','fishing','matthew','hooters','patrick','freedom','fucking','extreme','blowjob','captain','bigdick','abgrtyu','chester','monster','maxwell','arsenal','crystal','rebecca','pussies','florida','phantom','scooter','success'];

arrayOfPasswords[8] = ['firebird','password','12345678','steelers','mountain','computer','baseball','xxxxxxxx','football','qwertyui','jennifer','danielle','sunshine','starwars','whatever','nicholas','swimming','trustno1','midnight','princess','startrek','mercedes','superman','bigdaddy','maverick','einstein','dolphins','hardcore','redwings','cocacola','michelle','victoria','corvette','butthead','marlboro','srinivas','internet','redskins','11111111','access14','rush2112','scorpion','iloveyou','samantha','mistress'];


function FitToContent(id, maxHeight) {
    var text = id && id.style ? id : document.getElementById(id);
    if ( !text )
        return;
    var adjustedHeight = text.clientHeight;
    if ( !maxHeight || maxHeight > adjustedHeight )    {
        adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
        if ( maxHeight )          adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ( adjustedHeight > text.clientHeight )
            text.style.height = adjustedHeight + "px";
    }
 }


function screenPause(){
     $.blockUI({
		css: {
                    border: 'none',
                    padding: '2px',
                    backgroundColor: '#000000',
                    '-webkit-border-radius': '5px',
                    '-moz-border-radius': '5px',
                    opacity: .5,
                    color: '#fff'
                },
		overlayCSS:  {
                    backgroundColor: '#ffffff',
                    opacity:         0
                }
          });
}

function screenRelease(){
    $.unblockUI();
}



/*********************************************
 *  fancybox options
 *  titlepos : 'Inside','Outside','Over' : if not specified, defaults to 'Inside'
 *  fadein   : 'elastic','fade' or 'none' : if not specified, defaults to 'fade'
 ********************************************/


function fbOpen(type,divORcontent,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,modal,onComplete){

if(type=='C'){
    st = divORcontent
}else{
    st = $('#'+divORcontent).html();
}



fbopts = new Object();

if(overlayColour==''||overlayColour==undefined){
      overlayColour = '#ffffff'
}
fbopts['overlayColor'] = overlayColour;

if(h!=0||w!=0){
    fbopts['autoDimensions']=false;
    fbopts['width']=w;
    fbopts['height']=h;
}



if(modal==true){
    fbopts['modal']=true;
}
if(title!=''){
   fbopts['title'] = title;
   if(titlepos==''||titlepos==undefined){titlepos = 'float'}


  fbopts['titlePosition'] = titlepos
}


if(titleshow==false){

   fbopts['titleShow'] = false;
}


if(fadein!=''&&fadein!=undefined){
    fbopts['transitionIn'] = fadein;
    fbopts['transitionOut'] = fadein;
}


if(padding!='0'&&(padding=='' || padding==undefined)){

    padding= '10'
}

    fbopts['padding'] = padding;






fbopts['centerOnScroll'] = true;


if (onComplete!=''&&onComplete!=undefined){

    fbopts['onComplete'] = function (){eval(onComplete)}
}

jQuery.fancybox(st,fbopts);
jQuery('.popupButton').button();// by default, saves having to have a call back just for buttons
}


function fbClose(){
jQuery.fancybox.close();
}





function callPopupContent(divContent,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,onComplete){

    fbOpen('C',divContent,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,false,onComplete)

}


function callPopup(divID,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,onComplete){
    fbOpen('D',divID,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,false,onComplete)

}


function callPopResize(){
    jQuery.fancybox.resize();
}

function callPopdown(){

    fbClose();
}


function callPopupContentNoEscape(divContent,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,onComplete){

      fbOpen('C',divContent,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,true,onComplete)
}



function callPopupNoEscape(divID,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,onComplete){

      fbOpen('D',divID,w,h,title,titlepos,fadein,overlayColour,padding,titleshow,true,onComplete)
}


