//dave d edit
//page viewer js

//var refreshTime = 900000; //15 minutes
/*CSS Browser Selector v0.3.3 (Sep 09, 2009)Rafael Lima (http://rafael.adm.br)http://rafael.adm.br/css_browser_selectorLicense: http://creativecommons.org/licenses/by/2.5/Contributors: http://rafael.adm.br/css_browser_selector#contributors*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js'];c = b.join(' ');h.className += ' '+c;return c;};css_browser_selector(navigator.userAgent);




function debug(msg){
if(getQuerystring('crannigan')=='1'){alert('Debug message : ' + msg);}
}

var spacer = '<img src="web9/iSite/spacer.gif" alt="" border="0">'
var icTimer = 180000; // pop up timeout for live help
var timerObjects = new Array();


/*--------------------------------------------------------------------------------------------------
                                     AUTOLIST FUNCTIONS
--------------------------------------------------------------------------------------------------*/									 


function pageTop(){
     if($.browser.safari){
       bodyelem = $("body")
   } else
   {
        bodyelem = $("html,body")
    }
    bodyelem.scrollTop(0)
    setFooterPosition();
}
var alActive = 0; // flag to show 

var dbg='';
var  al = new Array();


// 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">';
var timerGIF = '<img src="/bookmark/web9/common/timer.gif" alt="Fetching Data" border="0" >';



function showLoader(autolist_id){
    ldiv = document.getElementById('ajax_loader_'+autolist_id);
    if(ldiv!=null){
        ldiv.innerHTML = ajaxGIF;
    }

}

function hideLoader(autolist_id){
    ldiv = document.getElementById('ajax_loader_'+autolist_id);
    if(ldiv!=null){
        ldiv.innerHTML = '';
    }

}

function autoL(id,autofire){
	this.id = id;
	this.autofire = autofire;
        this.rowsFound=0; // for autolists that return data
        
}



var alXML = new Array();


function alX(result,processed,alid){
	this.result = result;
	this.processed = processed;
	this.xmlDoc='';
	this.current_autolist='';
	this.current_autolist_id = alid;
	this.nodeRows=-1;
	this.currentRowStyle=-1;
}

function autolistQueue(result,alid){
	//debug(alid+' '+result)
	alXML[alXML.length] = new alX(result,0,alid); // queue in an array, as we otherwise have problems with multiple autolists coming in


	//var xxx = alXML[alXML.length-1].result;
	//dbg+='Length = '+alXML.length+xxx.substring(0,500)+'\n';
	//alert(dbg);
	//if (alActive==0){autolistProcess()} // try to process
        autolistProcess();
}

function autolistProcess(){


	if (alActive==1){

		setTimeout('autolistProcess()',3000);

		return false;
	}


	alActive=1;
	// check for any xml to process

	//if(getQuerystring('crannigan')=='1'){alert(alid);}
	processNeeded=-1;
	for (xi=alXML.length-1;xi>=0;xi--){ // do any need processing (work backwards, so earlier ones checked last and thus processed earlier

			if(alXML[xi].processed==0){

				if (processNeeded==-1){processNeeded=xi}
			}
	}

	if (processNeeded==-1){
			return false;
	//	alert(alXML.length);
	}

	parseXML(alXML[processNeeded].result,processNeeded);
        //debug(alXML[processNeeded].result);

	//window.status=alXML[processNeeded].result;

	//if(getQuerystring('crannigan')=='1'){
         //alert(getNode(alXML[processNeeded].xmlDoc,'STATUS'));
        //}

	var alStatus=getNode(alXML[processNeeded].xmlDoc,'STATUS');

        // check if user has defined a function to call if status is null - usually means no data found
        userALfunc = 'autolistNoData_'+alXML[processNeeded].current_autolist_id;
        //alert(alStatus)
        //debug(alStatus);
        if (alStatus==''){
            if(typeof window[userALfunc]!='undefined'){
                eval(userALfunc+'();')
            }
        }

        // tmc 18 oct 2011 : add oppposite function : there IS data
        userALDatafunc = 'autolistHasData_'+alXML[processNeeded].current_autolist_id;
        if (alStatus!=''){
            if(typeof window[userALDatafunc]!='undefined'){
                eval(userALDatafunc+'();')
            }
        }



	if (alStatus=='1'){//NORMAL TABLE DATA RETURN IE SQL COMMAND TYPE AUTOLIST, SUB TYPE 0 : SELECT STATEMENT
            //alert(alXML[processNeeded].current_autolist_id)
		xmlTraverse(processNeeded);
	}
	if (alStatus=='2'){//JAVASCRIPT RETURN
           
		// fetch the javascript from JS node
		// now includes surveys! (13 oct 2010)
		js = getNode(alXML[processNeeded].xmlDoc,'JS');
                
                //if (getQuerystring('crannigan')=='1'){
                  //  alert(js)
                    //a = prompt('',js)
               //}
                //alert(js)
		//execute the javascript
               // debug(js)
		var jsEval = eval(js);

		}

        if (alStatus=='3'){// SQL COMMAND TYPE AUTOLIST, BUT SUB TYPE = 1 STORED PROC
           //
                    	//alXML[processNeeded].current_autolist_id = getNode(alXML[processNeeded].xmlDoc,'AUTOLIST_ID');

                spAutolistTable(processNeeded);

                displayAutolist(processNeeded);


	}

        // new feature Tim Crannigan 8 mar 2011
        // popuplate ids version
        if (alStatus=='4'){
                     populateContent(processNeeded)
        }

	alXML[processNeeded].processed=1;


       // check if user has defined a function to call after processing
        userALpost = 'autolistPost_'+alXML[processNeeded].current_autolist_id;



            if(typeof window[userALpost]!='undefined'){
                eval(userALpost+'();')
            }

               LOCALuserALpost = 'localautolistPost_'+alXML[processNeeded].current_autolist_id;



            if(typeof window[LOCALuserALpost]!='undefined'){
                eval(LOCALuserALpost+'();')
            }




	alActive=0;
       //  timeOut = setTimeout('setFooterPosition()', 1000)
        loadTimtip()

}



function addAutolist(id,autofire){
    //debug(id)
	// add autolist to array of autolists to be run. Don't run yet until page has finished loading
	// mod Tim Crannigan 26 Jan 2010 : add autofire : 1 = trigger with runAutolists() ie at end of pageLoad, 0 = no, only run manually eg from onChange of a drop down field
	//al[al.length]=id;
       // alert(id+'   '+autofire)



       
	al[al.length]=new autoL(id,autofire);
	
}

function triggerAutolist(id,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10,param11,param12,param13,param14,param15){
    
	//alert(getQuerystring('url'));
        //alert(id)

	//debug (id)
	// fire off a single autolist
        // mod tim crannigan 13 may 2011
	//search = document.forms[0].searchinput.value;
        search = jQuery('#searchinput').val();
        if(search==undefined){search=''}
        //debug(search)
        //alert('')


	//search='press';
	p = "'"+document.getElementById('URL').innerHTML+"',"+id+",'"+document.getElementById('IPADDRESS').innerHTML+"','"+search+ "','"+GetUserSessionID()+"'";
	
	//p+=",'" + param1+"','" + param2 + "','" + param3+ "','" + param4 +  "','" + param5 +  "','" + param6 + "','" + param7 + "','" + param8 + "','" + param9 + "','" + param10 + "'";
        p+=",'" + param1+"','" + param2 + "','" + param3+ "','" + param4 +  "','" + param5 +  "','" + param6 + "','" + param7 + "','" + param8 + "','" + param9 + "','" + param10 + "','"+ param11 + "','"+ param12 + "','"+ param13 + "','"+ param14 + "','"+ param15+"'";
        procparams="'" + param1+"','" + param2 + "','" + param3+ "','" + param4 +  "','" + param5 +  "','" + param6 + "','" + param7 + "','" + param8 + "','" + param9 + "','" + param10 + "','"+ param11 + "','"+ param12 + "','"+ param13 + "','"+ param14 + "','"+ param15+"'";
	
	p+=",'{SK}'"
	//if(id==33){
	//a = prompt('tim',p);
        //}
        // KARU
        //if (getQuerystring('KARU')==1){
            //a = prompt('tim','id = '+id + ',' + p);
           // alert(id+'   ' + param1)
        //}
        //if(getQuerystring('crannigan')=='1'){
	//var a = prompt ('Autolist ' + id,procparams);
        //}

        //if(getQuerystring('crannigan')=='2'){
	//var a = prompt ('Autolist ' + id,p);
        //}
       // a = prompt('',p)
       // //'intranethome',126,'192.168.0.3','','HlgduRiTzUnZDVh5FeExIyYl2zBdb9IuK34x7ZES1yIJNXPu9eM58Q==','2662','','3','','','undefined','undefined','undefined','undefined','undefined','undefined','undefined','undefined','undefined','undefined'
    //a = prompt(id,p)
	callAjax('isite_autolist',p,'autolistORinteraction_'+id);
        
}



function runAutolists(){

	
	// if there are any autolists, execute them
	for(a=0;a<al.length;a++){
		
		//triggerAutolist(al[a],'','',''); // by default, no params are specified, but can be added by other javascript on the page and using triggerAutolist()	}
		// mod Tim Crannigan 26 Jan 2010
                
		if(al[a].autofire==1){
                    triggerAutolist(al[a].id,'','','','','','','','','','','','','','',''); // by default, no params are specified, but can be added by other javascript on the page and using triggerAutolist()	}
		}
	}
}


function buildAutolist(alIndex,rowIndex,colhead,colvalue){// used for type_id 1 autolists, sub_type_id 0 - SQL select where columns are controlled by the autolist
	status=colvalue[0];

	
	
	//alXML[alIndex].current_autolist_id = colvalue[1];  // id of autolist
	// get  the current value of the autolist div (ie where it's going to be displayed)
	// if empty, build the table 
	var cols=new Array();
	var span=1;
	/*******************************************************
	               FIRST ROW - build the table header
	*******************************************************/
	if (rowIndex==0){ // first row, so build table heading
		dbg+=colvalue[13];
		cols = colvalue[13].split('^');
		for(c=cols.length-1;c>=0;c--){
			chead=cols[c];
                       // if blank, increment spans so we know when we *do* find a heading, to use colspan to all columns to its right
			if(chead==''){
				span+=1;
			}else{
				stylecol = c+1;
				alXML[alIndex].current_autolist='<th class="autolist_' + alXML[alIndex].current_autolist_id+' autolist_' + alXML[alIndex].current_autolist_id+'_c' + stylecol+'" style="" colspan="' + span+'">' + chead+'</th>'+alXML[alIndex].current_autolist;
				span=1;
			} //if(chead==''){
		} // for(c=cols.length-1;c>=0;c--){
		if (alXML[alIndex].current_autolist!=''){
			alXML[alIndex].current_autolist = '<tr class="autolist_' + alXML[alIndex].current_autolist_id+'_rh">' + alXML[alIndex].current_autolist+'</tr>'
		}
		//alert(current_autolist);
	} // if (rowIndex==0){ // first row, so build table heading
	/*******************************************************
	               DATA ROWS
	*******************************************************/
	var link_field = colvalue[20]; // is there a field that should be treated as a link to an isite page?
	for(r=14;r<=18;r++){
		row = colvalue[r];
		var rowstring='';
		// again, work back through the columns
		cols=[];
		cols=row.split('^');
		span=1;
		for(c=cols.length-1;c>=0;c--){
			cvalue=cols[c];
			// if blank, increment spans so we know when we *do* find a value, to use colspan to all columns to its right
			if(cvalue=='0'){
				span+=1;
			}else{ 
				// column value
				if (cvalue==1000){ // 1000 = use external title
					dindex=2;//special case, external title
				}else{
				dindex = (1 * cvalue) + 2;
				}
				cdata = colvalue[dindex];
				
				// remove HTML tags
				cdta =  removeHTMLTags(cdata);
				
				
				
				if(cvalue==link_field){ // this is a link field
					if(cdata!=''){
						cdata = '<a class="autolist_' + alXML[alIndex].current_autolist_id+'" href="genericform.aspx?form=29848780&URL=' + colvalue[19]+'">' + cdata+'</a>';
					}
				}
				if(cdata==''){cdata='&nbsp;'}
				

				//alert(row + ' / '+cvalue+' = '+colvalue[dindex]+'   -    '+colvalue[3]+'   '+dindex);
				stylecol = c+1;
				rowstring='<td class="autolist_' + alXML[alIndex].current_autolist_id+' autolist_' + alXML[alIndex].current_autolist_id+'_c' + stylecol + '" colspan="' + span+'">' + cdata + '</td>'+rowstring;
				span=1;
			} //if(cvalue==''){
		} // for(c=cols.length-1;c>=0;c--){
		if (rowstring!=''){
			//alert(rowstring);
			//if(rowIndex%2){OE='e'}else{OE='o'}
			alXML[alIndex].currentRowStyle=alXML[alIndex].currentRowStyle*-1;
			if (alXML[alIndex].currentRowStyle==1){OE='o'}else{OE='e'}
			alXML[alIndex].current_autolist+='<tr valign="top" class="autolist_' + alXML[alIndex].current_autolist_id+'_r' + OE + '">' + rowstring+'</tr>';
		} // if (rowstring!=''){
	} // for(r=14;r<=18;r++){

	}  //  end of function


function populateContent(alIndex){
    // new tim crannigan 8 march 2011

    y=alXML[alIndex].xmlDoc.documentElement.childNodes;

// loop through root nodes


    for (i=0;i<y.length;i++){
       if (y[i].nodeType!=3&&y[i].nodeName=='Results'){
           
           //loop through children of 'Results'
            for (z=0;z<y[i].childNodes.length;z++){
                  if (y[i].childNodes[z].nodeType!=3){

                        // ignore autolist_id and status - they should not be displayed, they are just used by this js to decide whicj
                        // div to display the results and how to parse into a table
                        if(y[i].childNodes[z].nodeName!='AUTOLIST_ID'&&y[i].childNodes[z].nodeName!='STATUS'){
                            nodeID = y[i].childNodes[z].nodeName;
                            nodeValue = '';
                            if (y[i].childNodes[z].hasChildNodes()==true){nodeValue=y[i].childNodes[z].childNodes[0].nodeValue}
                            var jsNode=0;
                            while(nodeValue.indexOf(embedScriptStart)!=-1){
                                        jsNode=1;
                                        jsNodesFound=1;
                                        
					nodeValue = removeAndRunScript(nodeValue);
                                        
                            }
                           // debug(nodeValue)
                            if(jsNode==0||nodeValue!=''){
                                nV = nodeValue.replace(/&lt;/gi,'<')
                                nV = nV.replace(/&gt;/gi,'>')
                                jQuery('#'+nodeID).html(nV)
                                setFooterPosition();
                            }
                        }
                    }
            } // for (z=0;z<y[i].childNodes.length;z++){
        } //        if (y[i].nodeType!=3&&y[i].nodeName=='Results'){
    } // for (i=0;i<y.length;i++){
}

function spAutolistTable(alIndex){// type 0 autolist (SQL Command) sub type 1 (Stored Proc)
  
    var res = '';
var res_head='';
var res_data = '';
var row_data = '';
var rowcount = 0;
var rc=-1;
var rowID = 0;//mod tmc001 tim crannigan 20th july give each row an id so we can address it if needed (eg hide it with a filter)
var rAID = alXML[alIndex].current_autolist_id;



// if we only find jsNodes, just call the js and don't display anything
var jsNodesFound=0;
var tdNodesFound =0;
//debug (rAID)

y=alXML[alIndex].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 = '';
            var colcount=0;
              // mod tmc001
            rowID+=1;
            rowclass = '';
            for (z=0;z<y[i].childNodes.length;z++){


                  if (y[i].childNodes[z].nodeType!=3){

                    // ignore autolist_id and status - they should not be displayed, they are just used by this js to decide which
                    // div to display the results and how to parse into a table
                    
                    // ROWCLASS ADDED TMC 17 JUN 2011
                    
                    if(y[i].childNodes[z].nodeName=='ROWCLASS'){
                         if (y[i].childNodes[z].hasChildNodes()==true){rowclass=y[i].childNodes[z].childNodes[0].nodeValue}
                    }
                    if(y[i].childNodes[z].nodeName!='AUTOLIST_ID'&&y[i].childNodes[z].nodeName!='STATUS'&&y[i].childNodes[z].nodeName!='ROWCLASS'){
                        colcount+=1;
                        
                        // get column titles
                        if (rowcount==0){
                            colTitle = y[i].childNodes[z].nodeName;
                            colTitle = colTitle.replace(/_x0020_/gi," ")
                            //debug(colTitle)
                                res_head=res_head+'<TH class="autolist_'+rAID+' autolist_'+rAID+'_c' + colcount+'">'+colTitle+'</TH>'
                        }
                        nodeValue = '';
                        if (y[i].childNodes[z].hasChildNodes()==true){nodeValue=y[i].childNodes[z].childNodes[0].nodeValue}
                        //if (getQuerystring('crannigan')==1){
                        //    alert(rAID)
                        //}
                        // is it a javascript node?
                        var jsNode=0;
                        while(nodeValue.indexOf(embedScriptStart)!=-1){
                                        jsNode=1;
                                        jsNodesFound=1;
					nodeValue = removeAndRunScript(nodeValue);
                        }
                        if(jsNode==0||nodeValue!=''){
                            row_data+='<td'
                            // mod tmc001
                            tdNodesFound=1;
                            row_data+=' id="'+rowID+'_' + colcount+'"'
                            row_data+=' class="autolist_' + rAID+' autolist_' + rAID+'_c' + colcount+'">'+ nodeValue + '</td>';
                        }
                  } // if(y[i].childNodes[z].nodeName!='AUTOLIST_ID'&&y[i].childNodes[z].nodeName!='STATUS'){

                  }
            }  //             for (z=0;z<y[i].childNodes.length;z++){


            if (row_data!=''){
                                    rc=rc*-1;
                                    if (rc==1){rs='ro'}else{rs='re'}
                                  
                                    res_data+='<tr'
                                    res_data+=' id="' + rowID+'"'
                                    res_data+=' class="'
                                    if(rowclass!=''){res_data+=rowclass+' '}
                                    res_data+='autolist_' + rAID+'_' + rs+'">'+row_data+'</tr>'
                                    }
            rowcount+=1;
       } //       if (y[i].nodeType!=3&&y[i].nodeName=='Results'){

     

}  //for (i=0;i<y.length;i++){

if(tdNodesFound!=0||jsNodesFound==0){

if(res_data!=''){
    
          res_head = '<tr class="autolist_' + rAID+'_rh">' + res_head+'</tr>';
          res_data = '<tr class="autolist_' + rAID+'">' + res_data+'</tr>';
          //res = '<table cellspacing="2px" width="100%" class="autolist_' + rAID+'">' + res_head + res_data + '</table>' ;
          res =  res_head + res_data ;
}
else{
	
		res= '<b>RESULT</b><br>No data found';
	}

}
	//document.getElementById('popoverBody').innerHTML = res;

        // tim crannigan : put no of rows found in autolist array (al) in case post autolist function wants to use it
        for(a=0;a<al.length;a++){
            if(al[a].id==alXML[alIndex].current_autolist_id){
                al[a].rowsFound = rowcount;
            }
        }
alXML[alIndex].current_autolist =  res;
//debug (res)
//alert(res)
}
	
function displayAutolist(alIndex){
    
               hideLoader(alXML[alIndex].current_autolist_id);
		// end of xmlResultset function, ie all rows have been processed so now display
                
		if (alXML[alIndex].current_autolist!=''){
                        // mod tmc001
			//alXML[alIndex].current_autolist = '<table class="autolist_' + alXML[alIndex].current_autolist_id+'">' + alXML[alIndex].current_autolist+'</table>'
                        alXML[alIndex].current_autolist = '<table id="table_autolist_' + alXML[alIndex].current_autolist_id + '" class="autolist_' + alXML[alIndex].current_autolist_id+'">' + alXML[alIndex].current_autolist+'</table>'
		}
		// to view final HTML table content for debugging, uncomment the following line
		//alert(alXML[alIndex].current_autolist);

                //alert(alXML[alIndex].current_autolist)
		//document.getElementById('autolist_'+alXML[alIndex].current_autolist_id).innerHTML = alXML[alIndex].current_autolist;


                // tim crannigan 1 dec 2011 : add new parameter to specify the div id where output table should be shown (in case we use the same autolist id more than once on one page eg intranet home
                //
                
                outputDIV ='#autolist_'+alXML[alIndex].current_autolist_id;
                // have we specified a an alternate div id for this instance of the autolist
                jQuery(outputDIV).html(alXML[alIndex].current_autolist);


                //debug(alXML[alIndex].current_autolist.length)
                //debug(alXML[alIndex].current_autolist)
		
		//debug(alXML[alIndex].current_autolist);
		
		// timeOut = setTimeout('setFooterPosition()', 1000)
              
                setFooterPosition()
	}

	
	

/*--------------------------------------------------------------------------------------------------
                                     INTERACTIONS
--------------------------------------------------------------------------------------------------*/						
var  ia = new Array();

	
	
	
function addInteraction(id){
	// add interaction to array of interactions to be run. Don't run yet until page has finished loading
	ia[ia.length]=id; 
	
	
}


function runInteractions(){ 
	// if there are any autolists, execute them
	for(ii=0;ii<ia.length;ii++){
		triggerInteraction(ia[ii],'','',''); // by default, no params are specified, but can be added by other javascript on the page and using triggerAutolist()
		
	}
}


function triggerInteraction(id,param1,param2,param3){
	
	// fire off a single autolist
	
	search = document.forms[0].searchinput.value;
	
	p = id+",'" + param1 + "','" + param2 + "','" + param3 + "',"+id // use id as div
	//a= prompt('',p);
	callAjax('isite_interaction',p,'autolistORinteraction_'+id);
}


function setInteractionContent(interaction_id,content){
   
	document.getElementById('interaction_'+interaction_id).innerHTML = content;
}


function showInteraction(interaction_id,real_id,div,header,multiple_choice,mcopt1,mcopt2,mcopt3,mcopt4,mcopt5,free_text,free_text_preamble,response_action,message,redirect,param1,param2,param3,type_id,prior_title,allowblock,asknamefirm,inputtitle){


      // tmc 24 jun 2011 add image to home page survey (interaction_id = 0)
        if (interaction_id ==0){
            iheader = '<img src="/bookmark/web9/common/library/images/systems/survey.png" alt="" border="0" style="float:left;">'+header
        }else{
            iheader = header
        }
	ssT = '';
	ssT += '<table class="interaction_' + interaction_id+'">';
	ssT+='<tr class="interaction_' + interaction_id+'">';
        ssT+='<td class="interaction_' + interaction_id+'" colspan="2"><div class="interaction_' + interaction_id + '_header interaction_' + interaction_id + '">' + iheader +'<br><br></td></tr>';

       // tim crannigan 13 oct 2011
       if(inputtitle==1){

            ssT+='<tr><td class="interaction_' + interaction_id + '_label_title interaction_' + interaction_id+'" colspan="2">Title</td></tr>'
            ssT+='<tr><td class="interaction_' + interaction_id + '_input_title interaction_' + interaction_id+'" colspan="2"><input class="interaction_' + interaction_id + '" id ="interaction_title_' + interaction_id+'"></td></tr>'

       }
  
        
	if(multiple_choice==1){
		//alert('ok');
		if (mcopt1!=''){
		ssT += '<tr class="interaction_' + interaction_id + '_label_radio_1 interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'">' + mcopt1+'</td><td><input value="1" class="interaction_radio_' + interaction_id +'" type="radio" name="interaction_radio_' + interaction_id+'"></td></tr>';
		}
		
		if (mcopt2!=''){
		ssT += '<tr class="interaction_' + interaction_id + '_label_radio2 interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'">' + mcopt2+'</td><td><input value="2" class="interaction_radio_' + interaction_id + '"  type="radio" name="interaction_radio_' + interaction_id+'"></td></tr>';
		}
		
		if (mcopt3!=''){
		ssT += '<tr class="interaction_' + interaction_id + '_label_radio3 interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'">' + mcopt3+'</td><td><input value="3" class="interaction_radio_' + interaction_id + '"  type="radio" name="interaction_radio_' + interaction_id+'"></td></tr>';
		}
		
		if (mcopt4!=''){
		ssT += '<tr class="interaction_' + interaction_id + '_label_radio_4 interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'">' + mcopt4+'</td><td><input value="4" class="interaction_radio_' + interaction_id + '"  type="radio" name="interaction_radio_' + interaction_id+'"></td></tr>';
		}
		
		if (mcopt5!=''){
		ssT += '<tr class="interaction_' + interaction_id + '_label_radio_5 interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'">' + mcopt5+'</td><td><input value="5" class="interaction_radio_' + interaction_id + '"  type="radio" name="interaction_radio_' + interaction_id+'"></td></tr>';
		}
	}
	
	if(free_text==1){
		if(free_text_preamble!=''){
			ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><div class="interaction_' + interaction_id + '_label_freetext interaction_' + interaction_id + '">' + free_text_preamble+'</td></tr>';
		}
		ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><textarea id="interaction_' + interaction_id + '_input_freetext" class="interaction_' + interaction_id + '_input_freetext interaction_' + interaction_id + '" name="interaction_input_' + interaction_id+'"></textarea></td></tr>';
	}
	//ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><input  onclick="submitInteraction(' + interaction_id+','+multiple_choice+','+free_text+',\'' + header + '\',' + response_action+',\'' + message + '\',\'' + redirect+'\',\'' + param1 + '\',\'' + param2 + '\',\'' + param3+'\',' + div+');" class="interaction_button_' + interaction_id + '" type="button" value="submit">';
        sheader = header.replace(/"/gi,'')


        // mod tim crannigan 10 oct 2011
        // ask name firm / allow block
        if(asknamefirm==1){
            ssT+='<tr class="interaction_' + interaction_id+'_label_name"><td class="interaction_' + interaction_id + '_label_name interaction_' + interaction_id+'" colspan="2">Enter your name (optional)</td></tr>'
            ssT+='<tr class="interaction_' + interaction_id+'_name"><td class="interaction_' + interaction_id+'" colspan="2"><input class="interaction_' + interaction_id + '_input_name interaction_' + interaction_id + '" id ="interaction_name_' + interaction_id+'"></td></tr>'
            ssT+='<tr class="interaction_' + interaction_id+'_label_firm"><td class="interaction_' + interaction_id + '_label_firm interaction_' + interaction_id+'" colspan="2">Your firm (optional)</td></tr>'
            ssT+='<tr class="interaction_' + interaction_id+'_firm"><td class="interaction_' + interaction_id+'" colspan="2"><input class="interaction_' + interaction_id + '_input_firm interaction_' + interaction_id + '" id ="interaction_firm_' + interaction_id+'"></td></tr>'
        }


        if(allowblock==1){
            ssT+='<tr><td class="interaction_' + interaction_id+'" colspan="2"><input class="interaction_' + interaction_id + '_input_block interaction_' + interaction_id + '" type="checkbox" id="interaction_block_' + interaction_id+'">&nbsp;I do not wish my response to be made public </td></tr>'
            ssT+='<tr><td class="interaction_' + interaction_id+'" colspan="2">';
            ssT+='</td></tr>'
        }





        // submit button
	ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2">';
        //ssT+='<input  onclick="submitInteraction(' +real_id+','+ interaction_id+','+multiple_choice+','+free_text+',\'' + sheader + '\',' + response_action+',\'' + message + '\',\'' + redirect+'\',\'' + param1 + '\',\'' + param2 + '\',\'' + param3+'\',' + div+');" class="interaction_button_' + interaction_id + '" type="button" value="submit">';
        ssT+='<a href=""  onclick="submitInteraction(' +real_id+','+ interaction_id+','+multiple_choice+','+free_text;
        ssT+=',\'' + sheader + '\',' + response_action+',\'' + message + '\',\'' + redirect+'\',\'';
        ssT+=param1 + '\',\'' + param2 + '\',\'' + param3+'\',' + div+','+allowblock+','+asknamefirm+','+inputtitle;

        ssT+=');return false;';
        ssT+='"  class="btn interaction_button_' + interaction_id + '">submit</a>';// type="button" value="submit">';
	
	if(response_action==2){// show chart?
		ssT+='&nbsp;&nbsp;<a href="" onclick="fetchInteractionChart(' + real_id+','+div+');return false;" class="btn interaction_button_' + interaction_id + '">results</a>';// type="button" value="results">';
	}
	
	ssT+='</td></tr>';
	if(type_id==0&&prior_title!=''){ // current quick survey, so link to chart of prior survey
		ssT+='<tr><td class="interaction_' + interaction_id+'" colspan="2"><br>To see the results of our previous Quick Survey on <i>"' + prior_title+'"</i>, click <a class="interaction_' + interaction_id+'"href="" onclick="fetchInteractionChart(-1,0);return false;">previous quick survey</a></td></tr>'
	}



     
	ssT += '</table>';
	
	
	//alert(ssT);
	//a=prompt('',ssT);
	
	setInteractionContent(div,ssT);
        
        







        jQuery('.btn').css('fontSize','11px')
        jQuery('.btn').css('fontWeight','normal')
        jQuery('.btn').css('color','#000000')
        jQuery('.btn').button();
	
	setFooterPosition();

        // tmc 3 nov 2011
        postInteractionFN = 'interactionPost_'+interaction_id;
         if(typeof window[ postInteractionFN]!='undefined'){
                eval( postInteractionFN+'();')
          }

}


function submitInteraction(real_id,interaction_id,multiple_choice,free_text,header,response_action,message,redirect,param1,param2,param3,div,allowblock,asknamefirm,inputtitle){
    // added tmc 15 dec 2011 : allows for non standard manipulation of data prior to saving
     preSubmitInteractionFN = 'interactionPreSubmit_'+interaction_id;
         if(typeof window[ preSubmitInteractionFN]!='undefined'){
                eval( preSubmitInteractionFN+'();')
          }
          
	// params are optional
	var fm = document.forms[0];
	
	
	
	mc = 0;
	
	if(multiple_choice==1){
		
		var rdio = fm['interaction_radio_'+interaction_id];
		//var rdio = document.forms.interaction_radio_9;
		
		
		for(ri=0;ri<rdio.length;ri++){
			if(rdio[ri].checked){mc = rdio[ri].value}
		}
		
		if(mc==0){//no radio button ticked!
			alert('Please select an option in section : '+header);
			return false;
		}
	}
	
	ft = '';
        
	if (free_text ==1){
             
               // 2 dec 2011 use jQuery as form lost on popups
               //ft = fm['interaction_input_'+interaction_id].value;
               ft  = jQuery('#interaction_' +  interaction_id +'_input_freetext').val()
       
		ft = ft.replace(/'/gi,'`');
		if (ft.length>64000){
			alert('Your text entry is too long  - please shorten');
			return false;
		}
	}
	
	

	// submit the response
	//p = interaction_id + ','+mc+',\'' + ft+'\',';
	p = real_id + ','+mc+',\'' + ft+'\',';
	p += "'" + param1 + "','" + param2 + "','" + param3 + "'"
	
	
	// first, replace
	//a = prompt('aaa',p);

        // mod tmc 10 oct 2011
        // allowblock, asknamefirm
        if(allowblock==1){
               if(jQuery('#interaction_block_'+interaction_id).is(':checked')){
                   iBlock=1;
               }else{
                   iBlock=0;
               }
        }else{
            iBlock=0;
        }

        p+=','+iBlock;
        
        if(asknamefirm==1){
            iName = jQuery("#interaction_name_"+interaction_id).val();
            iFirm = jQuery("#interaction_firm_"+interaction_id).val();
        }else{
            iName='';
            iFirm='';
        }




        p+=",'"+iName+"'"
        p+=",'"+iFirm+"'"

     if(inputtitle==1){
            iTitle = jQuery("#interaction_title_"+interaction_id).val();
            if(iTitle==''){
                alert('Please enter the title of your feedback')
                return false;
            }
        }else{
            iTitle='';
        }

         p+=",'"+iTitle+"'"


         p+=",'{SK}'"


     
	callAjax('isite_ia_response',p,'interactionResponse_'+real_id);
	
	switch (response_action){
		case 0://message
			setInteractionContent(div,message);
		break;
		case 1: //redirect
			window.location = redirect;
			break;
		case 2: //chart	
			actionMessage = 'Thank you for your input - this is now being processed';
			setInteractionContent(div,actionMessage);
			fetchInteractionChart(real_id,div);
			break;
                case 3 : // mod tmc 13 0ct 2011 - show earlier entries
                       setInteractionContent(div,message);
                        break;
                case 4 :
                       
                        break;

			
	}
	
	actionMessage = 'Thank you for your input - this is now being processed';
	//actionMessage = '<iframe src="http://chart.apis.google.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World" frameborder="0">	';
        
	return false;
}


function fetchInteractionChart(interaction_id,div){
	p = interaction_id+','+div;
	//a=prompt('',p);
	callAjax('isite_ia_chart',p,'autolistORinteraction_'+interaction_id);

}



function showInteractionChart(interaction_id,div,chart_type,chart_height,chart_width,responses,value1,value2,value3,value4,value5,colour1,colour2,colour3,colour4,colour5,option1,option2,option3,option4,option5,header,textcount,responsecount){
    
	if (responses==0){
		setInteractionContent(div,'No chart available at this moment');
		return false
	}
       
	
	//alert(textcount);
	// ok, so build chart string
	ch = '';
					
	ch +='http://chart.apis.google.com/chart?'; // basic chart
	

	ch +='chs=' + chart_width+'x'+chart_height;  // chart dimensions


       // if(getQuerystring('crannigan')=='1'){
        //    chart_type=1;
      //  }











	
	/**********************************
	                   PIE CHART
	**********************************/
	tot = 0;
	if(chart_type==0){ // pie chart
		// calculate the total
		tot = value1+value2+value3+value4+value5;
	
		
	datalablist =  new Array('A','B','C','D','E');
        datacnt =-1;
	datavals='';
	datalabels='';
	datalabs='';
	datacolours = '';	
		
		
		
	if(option1!=''){
		if (datavals!=''){datavals+=','}
		d = 100*value1/tot;
		r = Math.round(d);
		datavals+=r;
		
		datacnt+=1;
		dl = datalablist[datacnt];
		if (datalabs!=''){datalabs+='|'}
		datalabs+=dl;
		if(datalabels!=''){datalabels+='<br>'}
		datalabels+=dl+' : ' + option1+'   (' + r + '%)';
		 
		col=(colour1=='')?'35c0cd':colour1;
		if(datacolours!=''){datacolours+=','}
		datacolours+=col;
				
	}
	
	if(option2!=''){
		if (datavals!=''){datavals+=','}
		d = 100*value2/tot;
		r = Math.round(d);
		datavals+=r;
		
		
		datacnt+=1;
		dl = datalablist[datacnt];
		if (datalabs!=''){datalabs+='|'}
		datalabs+=dl;
		if(datalabels!=''){datalabels+='<br>'}
		datalabels+=dl+' : ' + option2+'   (' + r + '%)';
		
		col=(colour2=='')?'028e9b':colour2;
		if(datacolours!=''){datacolours+=','}
		datacolours+=col;
	}
		
	
	
	
	if(option3!=''){
		if (datavals!=''){datavals+=','}
		d = 100*value3/tot;
		r = Math.round(d);
		datavals+=r;
		
		
		datacnt+=1;
		dl = datalablist[datacnt];
		if (datalabs!=''){datalabs+='|'}
		datalabs+=dl;
		if(datalabels!=''){datalabels+='<br>'}
		datalabels+=dl+' : ' + option3+'   (' + r + '%)';
		
		
		col=(colour3=='')?'1e6d74':colour3;
		if(datacolours!=''){datacolours+=','}
		datacolours+=col;
	}
	
	if(option4!=''){
		if (datavals!=''){datavals+=','}
		d = 100*value4/tot;
		r = Math.round(d);
		datavals+=r;
		
		
		datacnt+=1;
		dl = datalablist[datacnt];
		if (datalabs!=''){datalabs+='|'}
		datalabs+=dl;
		if(datalabels!=''){datalabels+='<br>'}
		datalabels+=dl+' : ' + option4+'   (' + r + '%)';
		
		col=(colour4=='')?'53c4cd':colour4;
		if(datacolours!=''){datacolours+=','}
		datacolours+=col;
	}
	
	if(option5!=''){
		if (datavals!=''){datavals+=','}
		d = 100*value5/tot;
		r = Math.round(d);
		datavals+=r;
		
		
		datacnt+=1;
		dl = datalablist[datacnt];
		if (datalabs!=''){datalabs+='|'}
		datalabs+=dl;
		if(datalabels!=''){datalabels+='<br>'}
		datalabels+=dl+' : ' + option5+'   (' + r + '%)';
		
		col=(colour5=='')?'015c65':colour5;
		if(datacolours!=''){datacolours+=','}
		datacolours+=col;
	}
	
	ch +='&chd=t:'+datavals;
	ch +='&chl='+datalabs;
	ch +='&cht=p3';
	ch +='&chco='+datacolours;
	//ch+='&chf=a,s,EFEFEFF0'; // transparent
	
	

	// colours 

        //  replacement using jqplot 21 oct 2010
     
            
           // $('#interaction_'+ div).html(ch)

            var pts = new Array();
            var clrs = new Array();
            if(option1!=''){
                pts[pts.length] = ['A',value1];
               clrs[clrs.length] = '#'+((colour1=='')?'3853a4':colour1);
            }
            if(option2!=''){
                pts[pts.length] = ['B',value2];
                clrs[clrs.length]='#'+((colour2=='')?'8b2842':colour2);
            }
            if(option3!=''){
                pts[pts.length] = ['C',value3];
                clrs[clrs.length]='#'+((colour3=='')?'6b66ae':colour3);
            }
            if(option4!=''){
                pts[pts.length] = ['D',value4];
                clrs[clrs.length]='#'+((colour4=='')?'ee3b33':colour4);
            }
            if(option5!=''){
                pts[pts.length] = ['E',value5];
                clrs[clrs.length]='#'+((colour5=='')?'53949d':colour5);
            }
            /*
            plot1 = $.jqplot('ichart_'+ div, [pts], {
                seriesDefaults:{
                        renderer:$.jqplot.PieRenderer,
                        shadow:true
                 },
                 grid:{
                     shadow:false,
                     background:'#f2f8f8',
                     borderWidth:0.0
                 },
                 seriesColors:clrs,
                 legend:{show:true}
            });

    */

        //}
        //
	
	



    
	ch='<div class="interaction_' + interaction_id + '"><h4>Results</h4>' +  header+'</div><img src="' + ch + '" alt=""><div class="interaction_' + interaction_id + '"><br>'+datalabels+'</div>';


// comments?
    if(textcount>0){
		ch+='<input  onclick="popupInteractionComments(' + interaction_id+',\'' + header+'\');" class="interaction_button_' + interaction_id + '" type="button" value="comments">';
    }
    //setInteractionContent(interaction_id,ch);
   
    setInteractionContent(div,ch);
    

   
} // if(chart_type==0){ // pie chart





/**************** tim crannigan 25 oct 2010 bar chart (with optional animation) ***/
	/**********************************
	                   BAR CHART
	**********************************/



if(chart_type==1){

    ch=''
//interaction_id,div,chart_type,chart_height,chart_width,responses,value1,value2,value3,value4,value5,colour1,colour2,colour3,colour4,colour5,option1,option2,option3,option4,option5,header,textcount){

 if(textcount>0){
		//ch+='<input  onclick="popupInteractionComments(' + interaction_id+',\'' + header+'\');" class="interaction_button_' + interaction_id + '" type="button" value="comments">';
                ch+='<a href=""  onclick="popupInteractionComments(' + interaction_id+',\'' + header+'\');return false;" class="btn interaction_button_' + interaction_id + '">comments</a>';// type="button" value="comments">';
    }
    //setInteractionContent(interaction_id,ch);
    
    showBarchart(interaction_id,'interaction_'+div,true,header,20,20,value1,option1,colour1,value2,option2,colour2,value3,option3,colour3,value4,option4,colour4,value5,option5,colour5,ch,responsecount);
    

}


}



function popupInteractionComments(interaction_id,header){
	// popup window to show the comments
	//debug(interaction_id)
	var popup = new Array();
	popupURL = 'genericform.aspx?form=31740187&ID='+interaction_id;
      //  if(getQuerystring('crannigan')=='1'){

      //alert(interaction_id)
               // $('#scTitle').html(header)
                $('#SCH').html(header.replace(/<\/?[^>]+>/gi, ''))// remove all formatting html
                
               triggerAutolist(53,interaction_id,'','','')
               return false;
               // callPopup('autolist_53',700,600,'')
              
              // ciAlert('Survey Comments',$('#autolist_53').html(),700,600)

        //}

/*

	if (window.showModalDialog) {
		//alert(popupURL);
		window.showModalDialog(popupURL,popup,"dialogWidth:500px;dialogHeight:650px");
} 
else
{
	window.open(popupURL,'popup','scrollbar=0,resizable=0,height=600,width=500,menubar=0,toolbar=0');
}
*/
}

function autolistPost_53(){
    //ciAlert('Survey Comments',$('#autolist_53').html(),700,600)

//debug($('#surveyComments').html())
h = $('#SCH').height();
//alert($('#SCH').html())
h1 = 518-h;
$('#autolist_53').css('height',h1+'px')
$('#surveyCommentsHeader').html($('#SCH').html());

     callPopup('surveyComments',700,600,'')
    
}





var barCharts = new Array();
var animateBCLength = 100; // milliseconds to complete bar chart animation
var animateSteps = 40; // no of steps

function animateBarchart(bci){

    max=barCharts[bci].v1;
    if(barCharts[bci].v2>max){max=barCharts[bci].v2}
    if(barCharts[bci].v3>max){max=barCharts[bci].v3}
    if(barCharts[bci].v4>max){max=barCharts[bci].v4}
    if(barCharts[bci].v5>max){max=barCharts[bci].v5}
    div=barCharts[bci].div;
    //
    aniMore=false;
    step=max / animateSteps; // 20 steps


    // option 1
    if(barCharts[bci].a1<barCharts[bci].v1){
        barCharts[bci].a1+=step;
        if(barCharts[bci].a1>barCharts[bci].v1){barCharts[bci].a1=barCharts[bci].v1}
        if(barCharts[bci].a1<barCharts[bci].v1){aniMore=true}
        w1=100.0 * barCharts[bci].a1/max;
        w2=100-w1;
        //ie7 fix : doesn't like 100% width with 0% width!
        if(w1>99){
                w1=99;
                w2=1;
         }
        $('td#td_v1A_'+div).width(w1+'px')
        $('td#td_v1B_'+div).width(w2+'px')
     }


    // option 2
    if(barCharts[bci].a2<barCharts[bci].v2){
        barCharts[bci].a2+=step;
        if(barCharts[bci].a2>barCharts[bci].v2){barCharts[bci].a2=barCharts[bci].v2}
        if(barCharts[bci].a2<barCharts[bci].v2){aniMore=true}
        w1=100.0 * barCharts[bci].a2/max;
        w2=100-w1;
        //ie7 fix : doesn't like 100% width with 0% width!
        if(w1>99){
                w1=99;
                w2=1;
         }
        $('td#td_v2A_'+div).width(w1+'px')
        $('td#td_v2B_'+div).width(w2+'px')
    }

    // option 3
    if(barCharts[bci].a3<barCharts[bci].v3){
        barCharts[bci].a3+=step;
        if(barCharts[bci].a3>barCharts[bci].v3){barCharts[bci].a3=barCharts[bci].v3}
        if(barCharts[bci].a3<barCharts[bci].v3){aniMore=true}
        w1=100.0 * barCharts[bci].a3/max;
        w2=100-w1;
        //ie7 fix : doesn't like 100% width with 0% width!
        if(w1>99){
                w1=99;
                w2=1;
         }
       
        $('td#td_v3A_'+div).width(w1+'px')
        $('td#td_v3B_'+div).width(w2+'px')

    }

    // option 4
    if(barCharts[bci].a4<barCharts[bci].v4){
        barCharts[bci].a4+=step;
        if(barCharts[bci].a4>barCharts[bci].v4){barCharts[bci].a4=barCharts[bci].v4}
        if(barCharts[bci].a4<barCharts[bci].v4){aniMore=true}
        w1=100.0 * barCharts[bci].a4/max;
        w2=100-w1;
        //ie7 fix : doesn't like 100% width with 0% width!
        if(w1>99){
                w1=99;
                w2=1;
         }
        $('td#td_v4A_'+div).width(w1+'px')
        $('td#td_v4B_'+div).width(w2+'px')
    }


     // option 5
    if(barCharts[bci].a5<barCharts[bci].v5){
        barCharts[bci].a5+=step;
        if(barCharts[bci].a5>barCharts[bci].v5){barCharts[bci].a5=barCharts[bci].v5}
        if(barCharts[bci].a5<barCharts[bci].v5){aniMore=true}
        w1=100.0 * barCharts[bci].a5/max;
        w2=100-w1;
        //ie7 fix : doesn't like 100% width with 0% width!
        if(w1>99){
                w1=99;
                w2=1;
         }
        $('td#td_v5A_'+div).width(w1+'px')
        $('td#td_v5B_'+div).width(w2+'px')
    }


    if (aniMore==true){
       animateBC = animateBCLength / animateSteps;
         tout = "animateBarchart(" + bci+");"
        a = setTimeout(tout,animateBC)
    }


}

function barChart(div,v1,t1,v2,t2,v3,t3,v4,t4,v5,t5){
    this.div=div;
    this.v1=v1;
    this.a1=0;
    this.t1=t1;
    this.v2=v2;
    this.a2=0;
    this.t2=t2;
    this.v3=v3;
    this.a3=0;
    this.t3=t3;
    this.v4=v4;
    this.a4=0;
    this.t4=t4;
    this.v5=v5;
    this.a5=0;
    this.t5=t5;
}



function showBarchart(interaction_id,div,animated,header,optwid,optheight,v1,t1,c1,v2,t2,c2,v3,t3,c3,v4,t4,c4,v5,t5,c5,postchartHTML,responsecount){


    st = '<table width="100%">'

    max=v1;
    if(v2>max){max=v2}
    if(v3>max){max=v3}
    if(v4>max){max=v4}
    if(v5>max){max=v5}
    tot = v1 + v2 + v3 + v4 + v5;



    if(header!=''){
       st+='<tr><td colspan="2" class="' + div+'">' + header+'<br><br></td></tr>'
    }

    // option 1
    if(t1!=''){
        clr1=(c1!='')?c1:'#3853a4';
        if(animated==false){
            w1=100.0 * v1/max;
            w2=100-w1;
        }else{
            w1="0"
            w2=100;
        }
        
        st+= '<tr><td style="width:' + optwid+'px;" class="' + div+'">A</td><td><table border="0" width="100%" cellpadding="0" cellspacing="0"><tr id="tr_v1_' + div+'" height="'+optheight+'px"><td id = "td_v1A_'+div+'" style="background-color:' + clr1+';" width="' + w1+ '%"></td><td id="td_v1B_' + div+'"width="' + w2+'%">' + spacer+'</td></tr></table></td></tr>'
    } //if(t1!=''){

    // option 2
    if(t2!=''){
        clr2=(c2!='')?c2:'#8b2842';
        if(animated==false){
            w1=100.0 * v2/max;
            w2=100-w1;
        }else{
            w1="0"
            w2=100;
        }

        st+= '<tr><td style="width:' + optwid+'px;" class="' + div+'">B</td><td><table border="0" width="100%" cellpadding="0" cellspacing="0"><tr id="tr_v2_' + div+'" height="'+optheight+'px"><td id = "td_v2A_'+div+'" style="background-color:' + clr2+';" width="' + w1+ '%"></td><td id="td_v2B_'+div+'" width="' + w2+'%">' + spacer+'</td></tr></table></td></tr>'
    } //if(t1!=''){


 // option 3
    if(t3!=''){
        clr3=(c3!='')?c3:'#6b66ae';
        if(animated==false){
            w1=100.0 * v3/max;
            w2=100-w1;
        }else{
            w1="0"
            w2=100;
        }

        st+= '<tr><td style="width:' + optwid+'px;" class="' + div+'">C</td><td><table border="0" width="100%" cellpadding="0" cellspacing="0"><tr id="tr_v3_' + div+'" height="'+optheight+'px"><td id = "td_v3A_'+div+'" style="background-color:' + clr3+';" width="' + w1+ '%"></td><td id="td_v3B_'+div+'" width="' + w2+'%">' + spacer+'</td></tr></table></td></tr>'
    } //if(t1!=''){


 // option 4
    if(t4!=''){
        clr4=(c4!='')?c4:'#ee3b33';
        if(animated==false){
            w1=100.0 * v4/max;
            w2=100-w1;
        }else{
            w1="0"
            w2=100;
        }

        st+= '<tr><td style="width:' + optwid+'px;" class="' + div+'">D</td><td><table border="0" width="100%" cellpadding="0" cellspacing="0"><tr id="tr_v4_' + div+'" height="'+optheight+'px"><td id = "td_v4A_'+div+'" style="background-color:' + clr4+';" width="' + w1+ '%"></td><td id="td_v4B_'+div+'" width="' + w2+'%">' + spacer+'</td></tr></table></td></tr>'
    } //if(t1!=''){


 // option 5
    if(t5!=''){
        clr5=(c5!='')?c5:'#53949d';
        if(animated==false){
            w1=100.0 * v5/max;
            w2=100-w1;
        }else{
            w1="0"
            w2=100;
        }

        st+= '<tr><td style="width:' + optwid+'px;" class="' + div+'">E</td><td><table border="0" width="100%" cellpadding="0" cellspacing="0"><tr id="tr_v5_' + div+'" height="'+optheight+'px"><td id = "td_v5A_'+div+'" style="background-color:' + clr5+';" width="' + w1+ '%"></td><td id="td_v5B_'+div+'" width="' + w2+'%">' + spacer+'</td></tr></table></td></tr>'
    } //if(t5!=''){



    // show values
    st+='<tr><td colspan="2">'+spacer+'</td></tr>'

    if(t1!=''){
        //pc1 =  Math.floor(100 * v1 / tot);
        pc1 =  Math.round(100 * v1 / tot);
        st += '<tr valign="top"><td style="width:' + optwid+'px;"  class="' + div +'">A</td><td class="' + div+'">' + t1 + ' (' + pc1 + '%)</td></tr>'
    }

    if(t2!=''){
        pc2 = Math.round(100 * v2 / tot);
        st += '<tr valign="top"><td style="width:' + optwid+'px;"  class="' + div+'">B</td><td class="' + div+'">' + t2 + ' (' + pc2 + '%)</td></tr>'
    }


    if(t3!=''){
        pc3 = Math.round(100 * v3 / tot);
        st += '<tr valign="top"><td style="width:' + optwid+'px;"  class="' + div+'">C</td><td class="' + div+'">' + t3 + ' (' + pc3 + '%)</td></tr>'
    }

    if(t4!=''){
        pc4 = Math.round(100 * v4 / tot);
        st += '<tr valign="top"><td style="width:' + optwid+'px;"  class="' + div+'">D</td><td class="' + div+'">' + t4 + ' (' + pc4 + '%)</td></tr>'
    }

    if(t5!=''){
        pc5 = Math.round(100 * v5 / tot);
        st += '<tr valign="top"><td style="width:' + optwid+'px;"  class="' + div+'">E</td><td class="' + div+'">' + t5 + ' (' + pc5 + '%)</td></tr>'
    }






    st +='</table>'
   // alert(st)


   // tmc  15 dec 2011 : add response count
   if (responsecount!=-1){
   st+='<br><span class="'+ div+'_ResponsesLabel">Responses received : <span class="' +div+'_ResponsesCount">'+responsecount+'</span><br><br>'
   }


   if(postchartHTML!=''){
       st+=postchartHTML;
   }

   
    $('#'+div).html(st)
    //alert(st)
      jQuery('.btn').css('fontSize','11px')
        jQuery('.btn').css('fontWeight','normal')
        jQuery('.btn').css('color','#000000')
        jQuery('.btn').button();
    setFooterPosition();
    //alert(st)
    if (animated==true){
        bci = barCharts.length;
        barCharts[bci] = new barChart(div,v1,t1,v2,t2,v3,t3,v4,t4,v5,t5)

        tout = "animateBarchart(" + bci+");"
         animateBC = animateBCLength / animateSteps;
        a = setTimeout(tout,animateBC)
    }
 
}

/*--------------------------------------------------------------------------------------------------
                                     AJAX FUNCTIONS
--------------------------------------------------------------------------------------------------*/									 
function removeHTMLTags(strInputCode){
	// credit to http://robertnyman.com/roblab/javascript-remove-tags.htm
		/* 
			This line is optional, it replaces escaped brackets with real ones, 
			i.e. &lt; is replaced with < and &gt; is replaced with >
		*/	
		
		return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		
}


function nodeA(name,value){
	is.name = name;
	this.value = value;
}


//var nodeRows=-1;
var colhead = new Array();
var colvalue = new Array();

function OnSucceededWithContext(result, userContext, methodName){
//a = prompt('',result)
        //a = prompt('',result+','+userContext+','+methodName)
//alert(result)
//debug (userContext+','+result)
    if (userContext){

        //if (getQuerystring('crannigan')=='1'){a=prompt(userContext,result)}
      

                                // mod Tim Crannigan 4th Oct 2011
                                // may want to run follow up on interaction
                                uc=userContext+'                          '
                               if(uc.substring(0,20)=='interactionResponse_'){
                                    iDoc =  XMLDocParse(result);
                                   iaID = getNode(iDoc,'interactionSubmitted');
                                     postInteractionCall = 'interactionPost_'+iaID;
                                     if(typeof window[postInteractionCall]!='undefined'){
                                        eval(postInteractionCall+'();')
                                    }

                               }
                                // mod tim crannigan 13 oct 2011
                                // interaction may now return table of results ie like an autolist
                                // so check for this
                                ialuc = 'interactionResponse_';
                                ialucl = ialuc.length;
                                var ialr = new Array();
                                ialr = userContext.split('_');
                                ialid = ialr[1]  ;
                                if (userContext.substring(0,ialucl)==ialuc){

                                	autolistQueue(result,'I_'+ialid);
				}

                                //alert(userContext)
                                // mod tim crannigan 16 mar 2010
                                // include autolist_id at end of userContext so we know which autolist
                                // previously obtained from recordset but if recorset empty, this was no good
				aluc = 'autolistORinteraction_';
                                alucl = aluc.length;
                                var alr = new Array();
                                alr = userContext.split('_');
                                alid = alr[1]  ;
                                //parseQuerystring();if(getQuerystring('crannigan')=='1'){alert(result);}
                                // if userContext starts 'autolistORinteraction_' then it's an autolist (or survey!)
                                if (userContext.substring(0,alucl)==aluc){
                                	autolistQueue(result,alid);
				}

                                
                                
                                // survey submit?
                                if (userContext=='surveySubmit'){
                                   
                                   sDoc =  XMLDocParse(result);
                                   sJS = getNode(sDoc,'JS')
                                   // a = prompt ('',sJS)
                                    eval(sJS);
                                    
                                }


                                 if(userContext == 'updatePFD'){
                                     window.location.reload()
                                 }
		// mod tim crannigan 20 may 2010
                // add facility to call local function to process the result
                localOSWC = 'localOnSucceededWithContext';

            if(typeof window[localOSWC]!='undefined'){
                loswc = localOSWC+'(userContext,result);'
                //alert(loswc);
                eval(loswc)
            }


       }   
}



var timt = '';
function tim(tst){
	timt+=tst;
}


function callAjax(procTag,params,Context){
  
	var s 
	var appid
	var password
	s = GetUserSessionID();
	appid = GetAppID();
	password = GetAppPassword();
        //if(getQuerystring('crannigan')=='1'){
          //  var a = prompt ('appid',appid);
            //var a = prompt ('password',password);

	//var a = prompt ('session',s);
        //var a = prompt ('params',p);
       //}
        
	ExecCascadeQueryXML(procTag, params, s, appid, password, Context	);

}


function getNode(xmlDocument,nodename){
	
	thisNode = xmlDocument.getElementsByTagName(nodename);
	if(thisNode&&thisNode[0]&&thisNode[0].firstChild&&thisNode[0].firstChild.nodeValue){
            
		//return thisNode[0].childNodes[0].nodeValue;
                if (typeof(thisNode[0].textContent)!='undefined'){return thisNode[0].textContent}
                return thisNode[0].childNodes[0].nodeValue;

	}else{
		return ''
		}
			
//	alert(nodename);
//if(xmlDocument.getElementsByTagName(nodename)[0].childNodes.length<1){return ''};
   //return xmlDocument.getElementsByTagName(nodename)[0].childNodes[0].nodeValue;
}


function XMLDocParse(inxml){
    
    var thisxmlDoc;
    try //Internet Explorer
 {
thisxmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  thisxmlDoc.async="false";
	 thisxmlDoc.async="true";
  thisxmlDoc.loadXML(inxml);

  }
catch(e)
 {
 try//Firefox,Mozilla, Opera,etc.
 {
  parser=new DOMParser();
  thisxmlDoc=parser.parseFromString(inxml,"text/xml");
  }
  catch(e)
  {
  alert(e.message);
  return;
  }
}
return thisxmlDoc;
}



function parseXML(inxml,alIndex){
	
try //Internet Explorer
 {
alXML[alIndex].xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  alXML[alIndex].xmlDoc.async="false";
	 alXML[alIndex].xmlDoc.async="true";
  alXML[alIndex].xmlDoc.loadXML(inxml);

  }
catch(e)
 {
 try//Firefox,Mozilla, Opera,etc.
 {
  parser=new DOMParser();
  alXML[alIndex].xmlDoc=parser.parseFromString(inxml,"text/xml");
  }
  catch(e)
  {
  alert(e.message);
  return;
  }
}
}


var embedScriptStart = '<![CDATA[';
var embedScriptEnd = ']]>';

function removeAndRunScript(inText){
	l = inText.indexOf(embedScriptStart);
	st = l + embedScriptStart.length;
	// store anything before <![CDATA[ and remove <![CDATA[
	pre='';
	if (l!=0){   
		pre=inText.substring(0,l);
	}
	
	inText=inText.substring(st,inText.length);
	//debug ('inText = ' + inText)
	// ok, now look for closing ]]
	m=inText.indexOf(embedScriptEnd);
	js = '';
	if(m!=-1){
		js=inText.substring(0,m);
	}
	if(js!=''){
            //debug('js = ' + js)
		eval(js);
	}
	su = m + embedScriptEnd.length;
	
	inText=inText.substring(su,inText.length);
	//alert(pre+'\n'+l+' = ' + st+'\n'+inText);
	
	
	return pre+inText;
	
}

function xmlTraverse(alIndex){
	var  x=alXML[alIndex].xmlDoc.getElementsByTagName('isite_autolist');
	
	for(xi=0;xi<x[0].childNodes.length;xi++){
	
		if(x[0].childNodes[xi].nodeType!=3){ // skip #text types as FF assumes whitespace is a new node, so ignore these
			x1=x[0].childNodes[xi];
			alXML[alIndex].nodeRows+=1;
			
			var coli=-1;
			for(xj=0;xj<x1.childNodes.length;xj++){
				x2 = x1.childNodes[xj];
			
				
				if(x2.nodeType!=3){  // again skip text nodes FF
					
					n = x2.nodeName;
					//alert(n);
					coli+=1;
					colhead[coli]=n;
			
					if(x2.childNodes.length==1){
						v=x2.childNodes[0].nodeValue;
						//alert(v);
					}else{
						v=''
					} //if(x2.childNodes.length==1){
					
					
					
					
					
			// mod tmc 25 feb 2010
			// can now include embedded javascript in the colvalue 
			// by surrounding with
			// <![CDATA[
			// ]]
			// eg
			// <![CDATA[alert(123);]]
			// the section below strips it out
					
					
			var cv = v;
			
			//alert(cv);
			
			//debug=getQuerystring('crannigan');
			//if (debug=='1'){
			//	alert(123);
			//}
				
				

				while(cv.indexOf(embedScriptStart)!=-1){
					cv = removeAndRunScript(cv);
				}
				v=cv;
			//}
			
			// end of mod tmc 25 feb 2010
					colvalue[coli]=v;
				}// if(x.nod
			} // for (xj
			
	
			buildAutolist(alIndex,alXML[alIndex].nodeRows,colhead,colvalue);
		} // if(x[0]
		
	}// for (xi
	
	//a=x.getFirstChildElement('isite_autolist');
//	b=a.getFirstChildElement;
//alert(a.nodeName);


        // tim crannigan : put no of rows found in autolist array (al) in case post autolist function wants to use it
        for(a=0;a<al.length;a++){
            if(al[a].id==alXML[alIndex].current_autolist_id){
                al[a].rowsFound = alXML[alIndex].nodeRows+1;
            }
        }
	if (alXML[alIndex].nodeRows!=-1){displayAutolist(alIndex)}
	
}



/*--------------------------------------------------------------------------------------------------
                                     COLLAPSIBLE SECTIONS
--------------------------------------------------------------------------------------------------*/						
var csAR = new Array();

function addCS(initstate){
	csAR[csAR.length]=initstate;
	return csAR.length-1;
}


function toggleCS(index){

	csAR[index]*=-1;
	csDIV = document.getElementById('csDIV'+index);
	if (csAR[index]==1){
		csDIV.style.display='';
	}else{
		csDIV.style.display='none';
      }
 
       setFooterPosition()

}





/*--------------------------------------------------------------------------------------------------
                                     MISC FUNCTIONS
--------------------------------------------------------------------------------------------------*/									 

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]}
                if(jQuery.trim(qspr[0].toUpperCase())==jQuery.trim(item.toUpperCase())){qi=jQuery.trim(qspr[1])}
	}
	return unescape(qi);
}

function debugal(){
   // for(dd=0;dd<alXML.length;dd++){
	//	alert(dd+'   '+alXML[dd].result);
	//	alert(dd+'   '+alXML[dd].current_autolist+'    '+dbg);
	//}
}

var AC1= 0;
var AC2= 0;
var AC3= 0;

function setAC(ac1,ac2,ac3){// store display for each area content
	AC1 = ac1;
	AC2 = ac2;
	AC3 =ac3;
}


function formSubmit(){
	
	doSearch();
	return false;
}



function forceRefresh(){
	// force refresh to avoid timeout
	//window.location = window.location;
//window.location.reload(true);
//	setTimeout('forceRefresh()',refreshTime);
}

function searchKey(evt){
	//window.status=evt.keyCode;
	if(evt.keyCode==13){
		doSearch();
	}
} 

function sendSystemError(errmsg){
    if (errmsg==''){errmsg='error not specified'}//callAjax doesn't pass empty params!
    callAjax("isiteError","'" + errmsg+ "'","sendError");
}

/*--------------------------------------------------------------------------------------------------
                                     VALIDATION FUNCTIONS
--------------------------------------------------------------------------------------------------*/									 
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isNumeric(nst) {
      return !isNaN(parseFloat(nst)) && isFinite(nst);
}


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 DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	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 setupPage(){
    
}

function bdfGrid2dataTable(){

}



function testpostLoad(){
  //  jQuery('#AREA_CONTENT_1').css('display','none')
    //jQuery('#AREA_CONTENT_1').html(' iljh clikjhsd cilusd ghcilushd cklhsdgjbsd vbjsdvbn');
      //  jQuery('#AREA_CONTENT_1').css('display','')
}




var tlMenuHighlightTop = -1;// last top level menu highlighted BY THE TOP LEVEL MENU
var tlMenuHighlightSub = -1;// last top level menu highlighted by pop out sub menu
//var tlMenuHighlightClass='';

function toplevelMenuHighlightT(m){
    tlMenuHighlightTop=m;
    tlMH(m);
}

function toplevelMenuHighlightS(m){
    tlMenuHighlightSub=m;
    tlMH(m);
}

function tlMH(m){

    tlMenuHighlightClass = jQuery('A.#top_megamenu_'+m).attr('class');
    //jQuery('A.#top_megamenu_'+m).removeClass('topmenustyle')
    //jQuery('A.#top_megamenu_'+m).addClass('megaTopSelected')

    jQuery('#td_top_megamenu_'+m).removeClass('topmenustyle')
    jQuery('#td_top_megamenu_'+m).addClass('megaTopSelected')
    
}


function toplevelMenuUnHighlightT(m){
    tlMenuHighlightTop=-1;
    mm = 'toplevelMenuUnHighlightGo('+m+')';
    setTimeout(mm,100);
}
function toplevelMenuUnHighlightS(m){
    tlMenuHighlightSub=-1;
    mm = 'toplevelMenuUnHighlightGo('+m+')';
    setTimeout(mm,100);
}


function toplevelMenuUnHighlightGo(m){
   
    //alert(tlMenuHighlightTop+'/'+tlMenuHighlightSub)
    if(m!=tlMenuHighlightTop&&tlMenuHighlightSub!=m){

      //  jQuery('A.#top_megamenu_'+m).removeClass('megaTopSelected')
       // jQuery('A.#top_megamenu_'+m).addClass(tlMenuHighlightClass)
        jQuery('#td_top_megamenu_'+m).removeClass('megaTopSelected')
        jQuery('#td_top_megamenu_'+m).addClass('topmenustyle')
    }
}

   var timeOut = null;
   var tim = 0;






function launchUITabs(tabname,defaultSelected){

      jQuery(function() {
          $('#'+tabname).tabs({
           });
      });
	


       jQuery( "#"+tabname ).bind( "tabsshow", function(event, ui) {
            setFooterPosition();
            });

       
}





function setFooterPosition(){
  // if(getQuerystring('crannigan')!='1'){
   //   return false;
  // }
  
  //return false;


   f = jQuery('#Area30039723');
 
 h = window.size().height;
 
  hTopbar = jQuery('#Area29862992').outerHeight();
  hMenu = jQuery('#Area29982642').outerHeight(); 
  hContent = jQuery('#Area29835432').outerHeight();
  //alert(hContent)
  hBody = hTopbar + hMenu + hContent;
  hFooter = jQuery('#Area30039723').outerHeight();
  //hFLeft = $('#Area30039723').position().left;
  try{
    hFLeft = jQuery('#Section30039738').position().left;//somehow causing an error sometimes - aynschronous javascript?

  }
  catch(e){
      return false;
  }

    _hContent = hContent + h - (hBody + hFooter) - 4


  if((hBody + hFooter) < h){
    newTop = h - hFooter;
    f.css('position','absolute')
    f.css('top',newTop)
    f.css('left',hFLeft)
 }else{
     f.css('position','absolute')
    f.css('top',hBody)
    f.css('left',hFLeft)
 }

 
  //alert(n + ' ' +hBody+'     '+newTop)
  clearTimeout(timeOut);
  return false;
}



var lhStatus=0;
var lhLink=0;
var lhSeconds=180
var pageLiveHelp=0;
function icConfigure(){
    lh = null;
    lhStatus=ssI1;
    lhLink=ssI2;
    lhSeconds = ssI3;

    if(pageLiveHelp!=1){
       
        
        return false;
    }


  
  if(lhStatus==1){
    icTimer = 1000 * lhSeconds;
    


    if(lhLink==1){
        jQuery('#livehelplinkimage').css('display','')
    }else{
        jQuery('#livehelplinkimage').css('display','none')
    }
    
    lh = setTimeout("liveHelpTrigger()",icTimer);

  }else{
      
      clearTimeout(lh);
       jQuery('#livehelplinkimage').css('display','none')
  }

}

function liveHelpTrigger(){
    if(pageLiveHelp!=1){
        return false;
    }

//return false;
if(lhStatus!=1){
    return false;
}
    //lcd=jQuery('#linkChatDialog').css('display');

    //if(lcd==undefined||lcd=='none'){
      //  return false;
    //}

    w = jQuery('#linkChatDialogOuter').attr("popWidth");
    if(w==undefined||w==""){
        w=300;
    }
    h = jQuery('#linkChatDialogOuter').attr("popHeight");
    if(h==undefined||h==""){
        h=300;
    }

 if(ie7==true){
     h = (1.0 * h)  + 32.0;
//     w = (1.0 * w)  + 20.0;
 }


    /* comment this out from A to Z to make live
    // A
    ext=jQuery('#linkChatDialogOuter').attr("external");
    if(ext==undefined||ext==""){
        ip = jQuery('#IPADDRESS').html();
        if(ip.substring(0,8)!='192.168.'){
            return false;
        }

    }
    //Z */


    lh = jQuery('#linkChatDialogOuter').html();
    lh = '<div style="padding:0px;" class="livehelppopup">'+lh+'</div>'
    //alert('pre')
    callPopupContent(lh,w,h,'','','fade','#ffffff',0,false)
    //alert('post')

}

function  liveHelpStart(){
    
   callPopdown();
   icLaunch()
   }

function  liveHelpCancel(){
   callPopdown();
}
/*--------------------------------------------------------------------------------------------------
                                     SEARCH
--------------------------------------------------------------------------------------------------*/




// tmc 21 oct 2010

function doSearch(){
        srchCount= getQuerystring('c')
       if(srchCount==''){
           srchCount=1;
       }else{
           srchCount= (srchCount * 1)+1;
       }

	var fm = document.forms[0];
	searchtext = fm.searchinput.value;
	if(searchtext==''){
		return false;
	}




       // special case : can't searcrh for text including '=' character as web page thinks this is a querystring separator,
       // so we convert it to {eq}

        searchtext = searchtext.replace(/=/gi,'{eq}')

         //searchtext = escape(searchtext)
	newurl = 'genericform.aspx?form=29848780&url=search&search=' + searchtext+'&c='+srchCount;

	window.location=newurl;
	//alert(searchtext);
}

var debugVAR='';

/*--------------------------------------------------------------------------------------------------
                                   MAIN LOAD FUNCTION
--------------------------------------------------------------------------------------------------*/

function postLoad(){
      // mod tmc 8 Aug 2011
   // if pages return value in , assume in JSON format
    //pResultHTML = jQuery.trim($('#PAGEPROCRESULT').html());
    pResultHTML = jQuery.trim(jQuery('#PAGEPROCRESULT').html());
  

    if(pResultHTML!=''&&pResultHTML!=undefined){
        // exception : if is standard HTML and starts with a tag
        if(pResultHTML.substring(0,1)!='<'){
            pResult = jQuery.parseJSON(pResultHTML);
        }
    }

   jQuery('.button').button();
   icConfigure();

  
}

jQuery(document).ready(function(){jqpostLoad()});



var plFunctions = new Array(); // list of functions from various script files, pages etc to be called once page is finished loading
function addplFunction(plF){
    plFunctions[plFunctions.length]=plF;
}

var pResult = null;
function jqpostLoad(){//runs after page load
   // jQuery('.searchbutton').button();

 


	// if not anonymous, cancel timeout
	if(GetUserID()!='27763092'){
            	//clearTimeout(timeOutID);
	}
	
	
	// hide collapsible sections that should be hidden (not set to display = none by default so
	// they can still be seen in iSite content management
	for(i=0;i<csAR.length;i++){
		if (csAR[i] == -1){
			document.getElementById('csDIV'+i).style.display='none';
		}
	}

	if(AC1==1){document.getElementById('outerAREA_CONTENT_1').style.display=''}
	if(AC2==1){document.getElementById('outerAREA_CONTENT_2').style.display=''}
	if(AC3==1){document.getElementById('outerAREA_CONTENT_3').style.display=''}
        // if(AC1==1){$('#outerAREA_CONTENT_1').css('display','');setFooterPosition()}
        // if(AC1==2){$('#outerAREA_CONTENT_2').css('display','');setFooterPosition()}
        // if(AC1==3){$('#outerAREA_CONTENT_3').css('display','');setFooterPosition()}


	// javascript run when the page has completed loading
	parseQuerystring(); // in case we need querystring
	// are we trying to search - if so, put the search querystring parameter in the 
	// searchbox as trigger autolists will look for it there
	if(getQuerystring('url')=='search'){
		srch = unescape(getQuerystring('search'));
                // special case : can't searcrh for text including '=' character as web page thinks this is a querystring separator,
                // so we convert it to {eq}
                srch = srch.replace(/{eq}/gi,"=")

		document.forms[0].searchinput.value = srch;
		document.getElementById('searchstring').innerHTML = srch;
	}
        //debug (al.length)
	 
	// run autolists
       
        
	if(al.length>0){
            
		runAutolists();
	}
	//debug(2220)
	 
	// run interactions
	if(ia.length>0){
		runInteractions();
	}
	
	//tmc 9 may 2011 add person data to divs
        cref =jQuery('#CUSTREF').html();
        mref =jQuery('#MEMREF').html();
        pfname =jQuery('#PERSONFIRSTNAME').html();
        psname =jQuery('#PERSONSURNAME').html();
        if(cref!='0'){
            jQuery('.sysFIRSTNAME').html(pfname)
            jQuery('.sysSURNAME').html(psname)
            jQuery('.sysCREF').html(cref)
            jQuery('.sysMREF').html(mref)
            jQuery('.sysLOGGEDIN_NO').css('display','none')
            jQuery('.sysLOGGEDIN_YES').css('display','')
        }else{
            jQuery('.sysFIRSTNAME').html('')
            jQuery('.sysSURNAME').html('')
            jQuery('.sysCREF').html('')
            jQuery('.sysMREF').html('')
            jQuery('.sysLOGGEDIN_YES').css('display','none')
            jQuery('.sysLOGGEDIN_NO').css('display','')
        }

            


	
	
	//setTimeout('debugal()',5000);
	document.forms[0].onsubmit=formSubmit;
	var tc=document.getElementById('TEMPLATECODE');
	
	if(tc){
	tc.innerHTML=document.getElementById('TEMPLATE').innerHTML;
	}

//document.getElementById('searchinput').onkeydown  = function(){alert.this.value}
	// suffix?
	
	
	
//	alert('ok');

	
	element = document.getElementById('searchinput');

	if (element!=null&&element!=undefined){
	if (element.addEventListener) {// firefox, w3c 
		element.addEventListener ( "keydown", searchKey, false); 
	} else {// ie 
		element.attachEvent ( "onkeydown", searchKey); 
	//a=1;
	}// 
}



      cA='<div id="cAlertdiv" style="display:none;">';
      cA+='<div id="cMessage"><div style="background-color:#aad0d6;width:100%;">- MESSAGE -</div><div style="font-size:4px;">&nbsp;</div><div id="cAlertmessage"></div><div style="font-size:4px;">&nbsp;</div><div id="cAlertbutton"></div></div>';
      cA+='<div id="cSite" style="display:none;height:297px;width:811px;background-image:url(/bookmark/web9/common/library/images/homepage/siteMessage.jpg);repeat:no-repeat;">';
      cA+='<div id="cSiteMessage" style="text-align:left;position:absolute;top:10px;left:10px;width:420px;height:282px;overflow:hidden;"></div>';
      cA+='<div style="position:absolute;top:0px;right:0px;width:20px;height:20px;"><a href="" onclick="cSitealertClose();return false;" style="font-size:22px;text-decoration:none;">X</a>';
      cA+='</div></div>';
      cA+='</div>'
      jQuery('#Area30039723').append(cA);
      jQuery('#Area30039723').append('<div style="display:none;" id="cisiAlert"></div>');

      //$('#blockuiAlertclosebtn').button();

    //if(getQuerystring('crannigan')=='1'){
        //crannigan();
    //}
//   setTimeout('forceRefresh()',refreshTime);
// call local postLoad ie one can be set up on page

    callIfFunctionExists('localpostLoad')
   




      window.onresize = function(){

          if(timeOut != null) clearTimeout(timeOut);
          timeOut = setTimeout('setFooterPosition()', 500)
          
      };
        // timtips
      timtip = '<div style="display:none;" id="timtip" onmouseover="clearTimeout(hideTimtip)" onmouseout="timerdismissTimtip()" ></div>'
      jQuery('#Area30039723').append(timtip);

loadTimtip();
setFooterPosition();
//alert('tim')

for (pf=0;pf<plFunctions.length;pf++){
    eval(plFunctions[pf])
}


}

//function localpostLoad(){
    // override this is needed on the local page

   
//}




// callPopup and related functions now in bdf_jslib.js as of 16 dec 2011


function callPopup_replaced20121212(divID,w,h,title){
    // $('#'+divID).css('display','block')


    $.fn.colorbox(
    
            {
                   
                    href:'#'+divID,
                    transition:'none',
                    width: w+'px',
                    height:h+'px',
                    interfaceMinWidth:50,  // Chrome / Safari get confused about border widths ie $leftBorder $rightBorder so force
                    interfaceMinHeight:50,// Chrome / Safari get confused about border heights ie $leftBorder $rightBorder so force
                    inline:true,
                    title:title,
                    overlayClose:false,
                    //close:'<img src="/bookmark/jquery/colorboxImages/images1/close.png" style="padding-right:0px;">',
                    close:'<img src="/bookmark/jquery/images/close_button.png" style="padding-right:0px;">',
                    onLoad:function(){
                             },
                    onComplete:function(){
                        
                             },
                    onCleanup:function()
                    {
                         
                         $('#'+divID).css('display','none')
                         cleanupPopup();
                     }

            });
            
     $('#'+divID).css('display','block')

}



function callPopupNoEscape_replaced20121212(divID,w,h,title){
    // $('#'+divID).css('display','block')

    // prevents user closing popup with escape or top right close option,
    // only with button or link provided in the popup itself
    $.fn.colorbox(

            {
                  escKey:false,
                    href:'#'+divID,
                    transition:'none',
                    width: w+'px',
                    height:h+'px',
                    interfaceMinWidth:50,  // Chrome / Safari get confused about border widths ie $leftBorder $rightBorder so force
                    interfaceMinHeight:50,// Chrome / Safari get confused about border heights ie $leftBorder $rightBorder so force
                    inline:true,
                    title:title,
                    overlayClose:false,
                    //close:'<img src="/bookmark/jquery/colorboxImages/images1/close.png" style="padding-right:0px;">',
                    close:'<img src="/bookmark/jquery/images/close_button.png" style="padding-right:0px;">',
                    onLoad:function(){
                         $('#cboxClose').remove();
                             },
                    onComplete:function(){
                    },
                    onCleanup:function()
                    {

                         $('#'+divID).css('display','none')
                         cleanupPopup();
                     }

            });

     //$('#'+divID).css('display','block')

}

function callPopdown_replaced20121212(){
      $.fn.colorbox.close();
}


function cleanupPopup(){
  
}
//shell - can be overridden on local page






/***********************************************
 *    tooltips
 **********************************************/




/***********************************************
 *    misc
 **********************************************/

function timeTo(localDate,UTCYear,UTCMonth,UTCDate,UTCHours,UTCMinutes,UTCSeconds){
// calculate the time from now to the specified date
// parameters should be UTC time ie GMT
// compareDate will be in local time

var tgt = new Date()
tgt.setUTCFullYear(UTCYear,UTCMonth-1);
tgt.setUTCMonth(UTCMonth,UTCDate);//months start at zero for January

tgt.setUTCHours(UTCHours,UTCMinutes,UTCSeconds);


diff = tgt - localDate;


if(diff<0){
    diffD=0;
    diffH=0;
    diffM=0;
    diffS=0;
}else{


diffD = Math.floor(diff / (24.0 * 60.0 * 60.0 * 1000.0))
diff-=(diffD * 24.0 * 60.0 * 60.0 * 1000.0);

diffH = Math.floor(diff / (60.0 * 60.0 * 1000.0))
diff-=(diffH * 60.0 * 60.0 * 1000.0);


diffM = Math.floor(diff / (60.0 * 1000.0))

diff-=(diffM * 60.0 * 1000.0);
diffS = Math.floor(diff / (1000.0))
}


//convert to 2 character strings
if(diffD<10){
    diffD='00'+diffD;
}else{
   if(diffD<100){
       diffD='0'+diffD;
   }
}
diffD+='';

if(diffH<10){
    diffH='0'+diffH;
}
diffH+='';

if(diffM<10){
    diffM='0'+diffM;
}
diffM+='';

if(diffS<10){
    diffS='0'+diffS;
}
diffS+='';

return({dd:diffD,hh:diffH,mm:diffM,ss:diffS})





}

var cTimeout=0;
var  cdTimer=0;


function cdtmr(yy,mm,dd,hh,mn,ss){
    this.yy=yy;
    this.mm=mm-1;//months begin at 0 (for January)
    this.hh=hh;
    this.dd=dd;
    this.mn=mn;
    this.ss=ss;
}

function initCountdowntimer(yy,mm,dd,hh,mn,ss){
    cdTimer= new cdtmr(yy,mm,dd,hh,mn,ss)

    cTimeout=setTimeout("countdownTimer()",1000)
}

function countdownTimer(){
cdT=new Date();


res=timeTo(cdT,cdTimer.yy,cdTimer.mm,cdTimer.dd,cdTimer.hh,cdTimer.mn,cdTimer.ss)
$('#tickerd1').html(res.dd.substring(0,1))
$('#tickerd2').html(res.dd.substring(1,2))
$('#tickerd3').html(res.dd.substring(2,3))
$('#tickerh1').html(res.hh.substring(0,1))
$('#tickerh2').html(res.hh.substring(1,2))
$('#tickerm1').html(res.mm.substring(0,1))
$('#tickerm2').html(res.mm.substring(1,2))
$('#tickers1').html(res.ss.substring(0,1))
$('#tickers2').html(res.ss.substring(1,2))
cTimeout=setTimeout("countdownTimer()",1000)
}

/*****************************
 * to use countdown timer, set up divs or table cells
 * that are to hold the remaining days, hours etc
 * ids are tickerd1 (1st char of days = tickerd1 etc)
 *****************************/



//*****************************************************************************
//                 QTIP TOOLTIPS
//*****************************************************************************
  // create a new style for the jquery qtip tooltips
    jQuery.fn.qtip.styles.cisiTooltips = { // Last part is the name of the style
          width:600,
          padding: 3,
          background: '#f3f3f3',
          color: 'black',
          textAlign: 'left',
          fontSize: '10px',
          border: {
             width: 1,
             radius: 3,
             color: '#c4c4c4'
          },
          tip: 'bottomLeft'
    }

     jQuery.fn.qtip.styles.dataTooltips = { // Last part is the name of the style
          width:300,
          padding: 3,
          background: '#f3f3f3',
          color: 'black',
          textAlign: 'left',
          fontSize: '10px',
          border: {
             width: 1,
             radius: 2,
             color: '#c4c4c4'
          }

         
    }
// make a tooltip for an element - pass '' to content and it will use the elements title instead
function qTooltip(elName, content)
{
   $('#' + elName).qtip({
        content:content,
        style:'cisiTooltips',
        position:
        {
            corner:
            {
                target: 'topMiddle',
                tooltip: 'bottomLeft'
            }
        }
    });
}


// same as above but not limited to passing a single id - requires #,.,etc at beginning of the name
function qTooltip2(elNames, content)
{
    // tim crannigan 24 aug 2010 - isite menus need title to be set to empty string to stop explorer showing default title
    // however, don't want to tooltip'

    // removed tim crannigan 13 sep 2010
   //if(content==''){
   //    return false;
  // }



   jQuery(elNames).qtip({
        content:content,
        style:'cisiTooltips',
        position:
        {
            corner:
            {
                target: 'topMiddle',
                tooltip: 'bottomLeft'
            }
        }
    });
}

function qTooltip_new(elNames, content,tStyle,tip2right)
{
    // tim crannigan 24 aug 2010 - isite menus need title to be set to empty string to stop explorer showing default title
    // however, don't want to tooltip'

    // removed tim crannigan 13 sep 2010
   //if(content==''){
   //    return false;
  // }
  if(tip2right==1){
    tPos ='bottomLeft';
  }else{
        tPos ='bottomRight';
  }

   jQuery(elNames).qtip({
        content:content,
        style:{name:tStyle,
         tip: tPos
        },
        position:
        {
            
            corner:
            {
                target: 'topMiddle',
                tooltip: tPos
            }
        }
    });
}





function cAlertcleanup(callback){
    if(typeof window[callback]!='undefined'){
          f = callback+"();"
         eval(f)
      }
    
}

function cConfirmcleanup(callback,ok){
    if(typeof window[callback]!='undefined'){
          f = callback+"(" + ok + ");"
          eval(f)
      }

}

function cAlertdone(callback){
   $.unblockUI({onUnblock:function (){cAlertcleanup(callback)}});
}

function cConfirmdone(callback,ok){
   
     $.unblockUI({onUnblock:function (){cConfirmcleanup(callback,ok)}});
}



function cAlert(message,callback){
    $('#cMessage').css('display','')
    $('#cSite').css('display','none')
    $('#cAlertmessage').html(message)
    btn='<input id ="btncAlert" type="button" value="close" onclick="cAlertdone(\'' + callback+'\');">'
    $('#cAlertbutton').html(btn)
    $('#btncAlert').button();
    $.blockUI.defaults.overlayCSS.backgroundColor = '#c4dde6';
    $.blockUI({message:$('#cAlertdiv')})
}


function cConfirm(message,callback){
    $('#cMessage').css('display','')
    $('#cSite').css('display','none')
    $('#cAlertmessage').html(message)
    btn='<input id ="btncConfirmy" type="button" value="yes" onclick="cConfirmdone(\'' + callback+'\',1);">'
    btn+='&nbsp;<input id ="btncConfirmn" type="button" value="no" onclick="cConfirmdone(\'' + callback+'\',0);">'
    $('#cAlertbutton').html(btn)
    $('#btncConfirmy').button();
    $('#btncConfirmn').button();
    $.blockUI.defaults.overlayCSS.backgroundColor = '#c4dde6';
    $.blockUI({message:$('#cAlertdiv')})
}


function cSitealert(msg){
    $.blockUI.defaults.overlayCSS.backgroundColor = '#c4dde6';
    $('#cMessage').css('display','none')
    $('#cSite').css('display','')
    $('#cSiteMessage').html(msg)
    $.blockUI({css:{borderColor:'#cddddd',borderWidth:'1px',width:'811px',marginLeft:'-250px',marginTop:'-80px'},message:$('#cAlertdiv')})

}

function cSitealertClose(){
    cAlertdone()
}

//'<div id="cAlertdiv" style="display:none;">
//<div style="background-color:#aad0d6;width:100%;">- MESSAGE -</div>
//<div style="font-size:4px;">&nbsp;</div>
//<div id="cAlertmessage"></div>
//<div style="font-size:4px;">&nbsp;</div>
//<div id="cAlertbutton"></div>
//</div>');
function crannigan(){

//cConfirm('test','timtest')

}



function ciAlert(ciTitle,ciMsg,ciHeight,ciWidth){
    jQuery('#cisiAlert').html(ciMsg)
    if(ciHeight==undefined){
        ciHeight=150;
    }

    if(ciWidth==undefined){
        ciWidth=300;
    }
     var buttons = {};
      buttons['Ok']= function(){jQuery(this).dialog("close")}
    jQuery('#cisiAlert').dialog({title:ciTitle,modal:"true",height:ciHeight,width:ciWidth,resizable:"false", buttons: buttons });
    jQuery('.ui-dialog-buttonpane').css('borderWidth','0px')
}


function ciOk(ciTitle,ciMsg,okFunction,ciHeight,ciWidth){

    jQuery('#cisiAlert').html(ciMsg)
    if(ciHeight==undefined){
        ciHeight=180;
    }

    if(ciWidth==undefined){
        ciWidth=300;
    }
    //title:ciTitle,modal:"true",height:ciHeight,width:ciWidth,

    var buttons = {};
    buttons['Ok']= function(){jQuery(this).dialog("close");if(okFunction!=''&&okFunction!=undefined){eval(okFunction)}}


    jQuery('#cisiAlert').dialog({title:ciTitle,modal:"true",height:ciHeight,width:ciWidth,resizable:"false", buttons: buttons  });
    jQuery('.ui-dialog-buttonpane').css('borderWidth','0px')
    return false;
}

function ciOkCancel(ciTitle,ciMsg,okFunction,cancelFunction,ciHeight,ciWidth){
    jQuery('#cisiAlert').html(ciMsg)
    if(ciHeight==undefined){
        ciHeight=150;
    }

    if(ciWidth==undefined){
        ciWidth=300;
    }
    //title:ciTitle,modal:"true",height:ciHeight,width:ciWidth,

    var buttons = {};
    buttons['Ok']= function(){jQuery(this).dialog("close");if(okFunction!=''&&okFunction!=undefined){eval(okFunction)}}
    buttons['Cancel']= function(){jQuery(this).dialog("close");if(cancelFunction!=''&&cancelFunction!=undefined){eval(cancelFunction)}}

    jQuery('#cisiAlert').dialog({title:ciTitle,modal:"true",height:ciHeight,width:ciWidth,resizable:"false", buttons: buttons  });
    jQuery('.ui-dialog-buttonpane').css('borderWidth','0px')
    return false;
}


function membersLogin(){
    // need to automatically add domain if external (not hard code in link)
    // so if external, force login to go to CISILOGIN
    //
    
    h = window.location.href+'                            ';

    h= h.toUpperCase();

    url='/BOOKMARK/genericform.aspx?form=29848780&url=memareafcsi';
    //if(h.substring(0,25)=='HTTP://WWW.SECINST.CO.UK/'||h.substring(0,26)=='HTTPS://WWW.SECINST.CO.UK/'){
    //    url='https://www.secinst.co.uk' + url;
   // }
    
    window.location = url;

}

function generalLogin(){
    
    h0 = window.location.href;

    //target = getQuerystring('url');// get initial page url of target
    target='memareafcsi'
    var qspr = new Array();


    for (q=0;q<qsar.length;q++){
        qspair = qsar[q];
        qspr = qspair.split('=')
        q0 = qspr[0];
        q0=q0.toUpperCase()
        
        if(q0!='URL'&&q0!='FORM'){
            target+='&'+qsar[q]
        }
    }
    
   
    h = h0+'                            ';

    h= h.toUpperCase();
    //url = '/bookmark/genericform.aspx?form=29848780&URL=CISILOGININTERNAL&TARGET='+target;
    
    //if(h.substring(0,25)=='HTTP://WWW.SECINST.CO.UK/'||h.substring(0,26)=='HTTPS://WWW.SECINST.CO.UK/'){

    
       // url = 'https://www.secinst.co.uk/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;
       // url = 'https://www.cisi.org/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;
    //}
    url = '/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;
    // added 4th August to keep session alive when logging in in case items already in basket for anonymous
    // taken out 8th August : if basket doesn't already exists, get Conversion from type 'DBNull' to type 'Integer' is not valid. error
    // however, this means if we use this login after creating a basket, basket is lost. Karu to fix!!
    //url+= '&AnonymousSessKey='+encodeURIComponent( GetUserSessionID())+'&ForceLogin=1&basketRequired=Yes';
    window.location = url;
   return false;
}


function timLogin(){
   
    h0 = window.location.href;

    //target = getQuerystring('url');// get initial page url of target
    target='memareafcsi'
    var qspr = new Array();


    for (q=0;q<qsar.length;q++){
        qspair = qsar[q];
        qspr = qspair.split('=')
        q0 = qspr[0];
        q0=q0.toUpperCase()

        if(q0!='URL'&&q0!='FORM'){
            target+='&'+qsar[q]
        }
    }


    h = h0+'                            ';

    h= h.toUpperCase();
    //url = '/bookmark/genericform.aspx?form=29848780&URL=CISILOGININTERNAL&TARGET='+target;

    //if(h.substring(0,25)=='HTTP://WWW.SECINST.CO.UK/'||h.substring(0,26)=='HTTPS://WWW.SECINST.CO.UK/'){


       // url = 'https://www.secinst.co.uk/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;
       // url = 'https://www.cisi.org/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;
    //}
    url = '/bookmark/genericform.aspx?form=29848780&URL=CISILOGIN&TARGET='+target;

     // url+='&AnonymousSessKey=' + GetUserSessionID() + '&ForceLogin=1&basketRequired=Yes'
      url+= '&AnonymousSessKey='+encodeURIComponent( GetUserSessionID())+'&ForceLogin=1&basketRequired=Yes';
//    url = '/bookmark/genericform.aspx?form=29848780&URL=42392386&AnonymousSessKey='+encodeURIComponent( GetUserSessionID())+'&ForceLogin=1&basketRequired=Yes';
   
alert(url)
    window.location = url;
   return false;
}




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();
}
function screenUnPause(){
    $.unblockUI();
}




function timerdismissTimtip(){
  hideTimtip = setTimeout("dismissTimtip()",1000)
}


function dismissTimtip(){
     jQuery('#timtip').css('display','none')
}
var hideTimtip;
function loadTimtip(){
    
    jQuery( ".timtip" ).mouseover( function(){
        clearTimeout(hideTimtip);
        ttoffset = 6;
        jQuery('#timtip').html($(this).attr('timtip'))

        st = $('html').scrollTop();
        h = window.size().height;
        w = window.size().width;
        dh = jQuery(this).height();
        dt = jQuery(this).offset().top - st;
        dl = jQuery(this).offset().left;
        th = jQuery('#timtip').height()
        tw = jQuery('#timtip').width()

        if ((dt + dh + ttoffset + th)<h){
            tt = dt + dh + ttoffset;
        }else{
            tt = dt - (dh + th + ttoffset);
        }

        if((dl + ttoffset + tw)<w){
            tl = dl + ttoffset;
        }else{
            tl = dl - (ttoffset + tw)
        }

       // alert(st+' '+ dt+' ' +dh+' '+th+'  '+tt+' '+h)
        jQuery('#timtip').css('top',tt)
        jQuery('#timtip').css('left',tl)

       
        jQuery('#timtip').css('display','block')
    })

     jQuery( ".timtip" ).mouseout( function(){
            timerdismissTimtip()
    })
}



/******************************************************
 *   PERSONAL FEATURES CODING
 */






function pfDragging(){
  
}

var timc = 0;

function pfFindOverColumn(cols,template,fset,f,dropID){
    // find which column we are dragging into


    dropE = $('#'+dropID)
    dropEleft = dropE.position().left;
    dropEwidth=dropE.width();
    dropEright = dropE.position().left + dropE.width();
    dropEtop = dropE.position().top;
      c = 0;
    for(i=1;i<=cols;i++){
        colDivID='#pfcol_'+template+'_'+fset+'_'+i;
        colDiv = $(colDivID);
        // right of this column's leftmost position

        colLeft = colDiv.position().left;
        colRight = colLeft + colDiv.width();

        // how much of the item being dropped is within this column?

       // any overlap at all?
       if(dropEright>=colLeft&&dropEleft<=colRight){
           if(dropEleft<colLeft){
               overlapLeft=colLeft;
           }else{
               overlapLeft=dropEleft;
           }

           if(dropEright>colRight){
               overlapRight=colRight;
           }else{
               overlapRight=dropEright;
           }

           // ok, is this more than 50% of the dropped element's width?
           if((overlapRight-overlapLeft)>=(dropEwidth * 0.51)){
               c = i
           }
       }

    }
   
    return c;

}


var lastInsertDiv=''
function pfDrag(cols,template,fset,f,dropID){

     dropE = $('#'+dropID)
    dropEleft = dropE.position().left;
    dropEwidth=dropE.width();
    dropEright = dropE.position().left + dropE.width();
    dropEtop = dropE.position().top;
    dropEbottom = dropEtop + dropE.height();

    c = pfFindOverColumn(cols,template,fset,f,dropID);
    if (c==0){return false;}
    // now find where in the column
     carst = 'pfcolAR_' + template+'_'+fset+'_'+c;
     colAR = eval(carst);

   
     // set the top of each widget
     cPos=colAR.length-1;

     dbg = '';
     var thisPos=-1;
     for(i=colAR.length-1;i>=0;i--){
        // find the top
        dbg+='   '+i
        if(colAR[i].active==1){
         if(colAR[i].f==f){
             thisPos=i;
         }
         //colAR[i].top = $('#pf_'+template+'_'+fset+'_'+colAR[i].f).position().top;
         //dbg+='('+i+','+colAR[i].top+')';
         colARHeight=$('#pf_'+template+'_'+fset+'_'+colAR[i].f).height();

          if (dropEtop<=colAR[i].top||dropEbottom<=(colAR[i].top+colARHeight)){
              cPos=i;
          }
        }
     }
     if (cPos==thisPos){
         // still over original position, so don't show insert div
         return false;
     }

    insertAfterDiv = 'pf_'+template+'_'+fset+'_'+colAR[cPos].f;
    pfHeight = dropE.height();
    $('#timc').html(colAR[cPos].f+','+pfHeight)
    insertDiv = 'pfInsert_'+template+'_'+fset+'_'+colAR[cPos].f;
    if (insertDiv!=lastInsertDiv&&lastInsertDiv!=''){
        $('#'+lastInsertDiv).css('display','none')
    }
    $('#'+insertDiv).height(pfHeight)
    $('#'+insertDiv).css('display','')
    lastInsertDiv = insertDiv;
    



 
}


function pfSetTops(cols,template,fset){
    // set intial top positions so we can compare top when dragging
    // just to show insert box : has no effect on final drop
    for(j=1;j<=cols;j++){
         carst = 'pfcolAR_' + template+'_'+fset+'_'+j;
         colAR = eval(carst);
          for(i=0;i<colAR.length;i++){
          // find the top
          if(colAR[i].active==1){
            colAR[i].top = $('#pf_'+template+'_'+fset+'_'+colAR[i].f).position().top;
          }
      }
    }
   
}
function pfDrop(cols,template,fset,f,dropID){

   
    

    // find which column it now belongs to
  
    c = pfFindOverColumn(cols,template,fset,f,dropID);

    // fail? should not happen
       if(c == 0){
           
            rebuildPF(template,fset,cols)
            return
       }

   // now deactivate from column array if it was on another column
   var thiscol = 0; // already in the right column
   for(j=1;j<=cols;j++){
       carst = 'pfcolAR_' + template+'_'+fset+'_'+j;
       colAR = eval(carst);
       for(k=0;k<colAR.length;k++){
           if(colAR[k].f==f){//&&colAR[k].active==1){  // found this feature
             if(j!=c){ // different column, so delete from that old column
                 colAR[k].active=-1;//deleted
             }else{
                 thiscol = 1;// found - already in this array
             }

          }
       }
   }

   carst = 'pfcolAR_' + template+'_'+fset+'_'+c;
   colAR = eval(carst);
   if(thiscol==0){
       //not in this col previously, so add
       colAR[colAR.length]=new pfColItem(f,1);
  }
  

for(i=0;i<colAR.length;i++){
    // find the top
    if(colAR[i].active==1){
        colAR[i].top = $('#pf_'+template+'_'+fset+'_'+colAR[i].f).position().top;
    }
}

var p = 'PRE '
for(i=0;i<colAR.length;i++){
    
    p += ','+colAR[i].f
}

// finally sort
for(i=0;i<colAR.length-1;i++){
    for(j=i+1;j<colAR.length;j++){
        if(colAR[i].top>colAR[j].top&&colAR[i].active==1){
            ijf = colAR[i].f;
            colAR[i].f = colAR[j].f;
            colAR[j].f = ijf;
        }
    }
}


// finally rebuild positional strings



rebuildPF(template,fset,cols)
return



}

function rebuildPF(template,fset,cols){
    flist = ""
 for(j=1;j<=cols;j++){
       carst = 'pfcolAR_' + template+'_'+fset+'_'+j;
       colAR = eval(carst);
       for(k=0;k<colAR.length;k++){
          // ignore active== -1 : deleted from one column and added to another
          if(colAR[k].active==1){
               if(flist!=''){flist+=','}
               flist+='+'+colAR[k].f+'*1*'+j
          
          }
          if(colAR[k].active==0){
               if(flist!=''){flist+=','}
               flist+='+'+colAR[k].f+'*0*'+j
               
          }
       }
   }


 p = template+","+fset+",'"+flist+"','"+jQuery('#IPADDRESS').html()+"'"

 screenPause();
callAjax('BDF_UPDATE_PFD',p,'updatePFD');

return

}




function pfColItem(f,active){
    this.f = f;
    this.top = 0;
    this.active = active;
 }




function pfAdd2Col(col,template,fset,f,active){

    // ADD TO COLUMN ARRAY
    carst = 'pfcolAR_' + template+'_'+fset+'_'+col;
  
    carAR = eval(carst);

   carAR[carAR.length] = new pfColItem(f,active);



}


function pfSave(template,fset,cols){
    
    // get number of features check boxes
    var addChecks = eval('pfFeatures_'+template+'_'+fset);
    // work through the check box
    for(l=1;l<=addChecks;l++){
        isChecked = $('#pfFCheckBox_'+template+'_'+fset+'_'+l).attr("checked")
        f = $('#pfFCheckBox_'+template+'_'+fset+'_'+l).val()
        // ok, so find out whether this is already on the list of features


       var f_fnd = 0;
      for(j=1;j<=cols;j++){
       carst = 'pfcolAR_' + template+'_'+fset+'_'+j;
       colAR = eval(carst);
       for(k=0;k<colAR.length;k++){
          if(colAR[k].f==f&&isChecked==true){
               colAR[k].active=1;
               f_fnd = 1;
          }
          if(colAR[k].f==f&&isChecked==false){
               colAR[k].active=0;
               f_fnd = 1;
          }
       }
    }
        if(f_fnd==0){
            alert(f)
            // not found, so add to column 1
      //  carst = 'pfcolAR_' + template+'_'+fset+'_'+1;
    //    colAR = eval(carst);
     //   colAR[colAR.length] = new pfColItem(f,1)
        }

    }


   rebuildPF(template,fset,cols)
    return
}


function pfDelete(template,fset,f,cols){



 for(j=1;j<=cols;j++){
       carst = 'pfcolAR_' + template+'_'+fset+'_'+j;
       colAR = eval(carst);
       for(k=0;k<colAR.length;k++){

          if(colAR[k].f==f){
               colAR[k].active=0;
          }
       }
   }



    rebuildPF(template,fset,cols)
    return
}


function fetchRSS(url,target,failMessage,linkCol,maxRows,deDuplicate,skipEmpty) {


    furl=url;
    // append date to force refresh
    if(url.indexOf('?')>-1){
        dd = new Date();
        furl+=dd.toString();
    }
    $.ajax({
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=999&callback=?&q=' + encodeURIComponent(furl),
        dataType: 'json',
       
        success: function(data) {
           if(data.responseData==null){
              $('#rss_'+target).html(failMessage)
           }else{
                outputRSS(data.responseData.feed,target,linkCol,maxRows,deDuplicate,skipEmpty);
           }
        }
    });
}



var rssdupeAR = new Array(); // array of dedupe values to check
function rssdupeFound(dedupevalue){
    df = false;
    for(dv=0;dv<rssdupeAR.length;dv++){
        if(rssdupeAR[dv]==dedupevalue){
            df = true;
        }
    }
    return df;

}



function outputRSS(rssData,target,linkCol,maxRows,deDuplicate,skipEmpty){
   

    
    colHAR = new Array();
    colAR = new Array();
    rssTemp = '';
    rowsOutput = 0;

    // deDuplicate?
    // should be in the format
    // n,ld,rd
    // ie column to dedupe, left delimiter , right delimiter (last two optional)
    // so it gets the value from that column, and if delimiters specified, a substring
    // and doesn't output that row if the dedupe valule already output
    if (deDuplicate==undefined){
        deDuplicate='0,,'
    }
    deDuplicate+=',,'// force empty left and right delims if not specified!

    dedupePAR = deDuplicate.split(',')
    
    dedupeValue = '';// value of deuplicating column or substring
    for(i=0;i<rssData.entries.length;i++){
        if(rowsOutput<maxRows||maxRows==0){
    //     for(i=0;i<2;i++){
          rssD =  rssData.entries[i];
          colcnt = -1;
         // do we output this row?
          outputRow = true;

          // work through columns
          // put in an array first not directly into rssTemp in case we need to find the link column!
          colAR = [];
          linkText = '';
          for (var name in rssD) {
            colcnt+=1;
            colHAR[colcnt]=name;
            v = rssD[name];
            
            if(name=='publishedDate'){
              colHAR[colcnt]='Date';
               d = new Date(v);
               rssVal=dateToExpandedText(d)
            }else{
               rssVal=v;
            }

      

            // link
            if(name=='link'){
                linkText = rssVal;
            }
              colAR[colcnt]=rssVal;

              // check for deduplicate value
               
              if(colcnt+2==dedupePAR[0]){
                 
                 dedupeValue = rssVal;
                 // are there delimiters?
                 ld = dedupePAR[1];
                 if (ld!=''){
                    ldi = dedupeValue.indexOf(ld)
                    if(ldi!=-1){
                        dedupeValue = dedupeValue.substring(1+ldi,dedupeValue.length)
                        rd = dedupePAR[2];
                        if(rd!=''){
                            rdi = dedupeValue.indexOf(rd)
                            if(rdi!=-1){
                                dedupeValue = dedupeValue.substring(0,rdi)
                            }
                        }
                      
                    }
                 } // if (ld!=''){


              }
              //
              if(skipEmpty!=undefined&&colcnt+2==skipEmpty){
                  // skip this row if this column is empty
                  if(rssVal==''){
                      
                      outputRow=false;
                  }
              }


          } // end of working through columns

          
          // duplicate?
          if(dedupePAR[0]!=0){
            if (rssdupeFound(dedupeValue)==true){
                  outputRow=false;
              }else{
                  rssdupeAR[rssdupeAR .length] = dedupeValue;
            }
          }


         if(outputRow==true){
         rowsOutput +=1;
          rssTemp+='<tr valign="top" class=" rss_'+target+'_ rss_'+target+'_'
          // odd or even rows?
          if(i%2==0){
              rssTemp+='e'
          }else{
              rssTemp+='o'
          }
          rssTemp+='">'
             // end of columns
             // first INSERT deupvalue as a column
               rssTemp+='<td';
                rssTemp+=' class="rss_' + target+'_c1 rss_'+target+'"  '
                rssTemp+='>'
                // link?
                if(1==linkCol&&linkText!=''){
                    rssTemp += '<a class="rss_' + target+'_link" href="' + linkText+'" target="blank">'
                }
                rssTemp += dedupeValue
                if(1==linkCol&&linkText!=''){
                    rssTemp += '</a>'
                }
                rssTemp +='</td>'
                // now add actual columns
                
            for(c=0;c<colAR.length;c++){
                rssVal = colAR[c];
                colno = c + 2; // just so column ids/classes start from 1 - easier to work with
                rssTemp+='<td';
                rssTemp+=' class="rss_' + target+'_c' + colno+'  rss_'+target+'"  '
                rssTemp+='>'
                // link?
                if(colno==linkCol&&linkText!=''){
                    rssTemp += '<a class="rss_' + target+'_link" href="' + linkText+'" target="_blank">'
                }
                rssTemp += rssVal
                if(colno==linkCol&&linkText!=''){
                    rssTemp += '</a>'
                }
                rssTemp +='</td>'

            }


          rssTemp+='</tr>'
         } // if(outputRow==true){

    }

    }
     rssHTML = '<TABLE cellpadding="0" cellspacing="0" class="rss' + target+'">';
     rssHTML += '<tr valign="top" class="rss_'+target+'_head">'
     // first insert dedupevalue
     rssHTML += '<th'
     rssHTML+=' class="rss_' + target+'_head_c1 rss_'+target+'"  '
     rssHTML +='>deDuplicate</th>';

     for(i=0;i<colHAR.length;i++){
          colno = i + 2; // just so column ids/classes start from 1 - easier to work with
         rssHTML += '<th'
         rssHTML+=' class="rss_' + target+'_head_c' + colno+'"  '
         rssHTML +='>' + colHAR[i] + '</th>';
     }
     rssHTML += '</tr>'
     rssHTML += rssTemp;
     rssHTML += '</TABLE>';

    $('#rss_'+target).html(rssHTML)


    rssPost = 'rssPost_'+target;

            if(typeof window[rssPost]!='undefined'){
                eval(rssPost+'();')
            }





}

function remoteScript(url){
    document.body.appendChild(
        (function() {
            var newScript = document.createElement("script");
            newScript.type = "text/javascript";
            newScript.src = url;
            return newScript;
        })
        ());
}

var themeAR = new Array();



function theme(themeName){

    this.themeName=themeName;
    
    this.themeCCAR = new Array();  // array of classes and attributes
    
 }

function themeCC(themeClasses,themeCSS){
    this.themeClasses = themeClasses;
    this.themeCSS = themeCSS;
}

function createTheme(themeName){
    themeAR[themeAR.length] = new theme(themeName);
}

function themeIndex(themeName){
    tFnd = -1;
    for(tI=0;tI<themeAR.length;tI++){
        if(themeAR[tI].themeName==themeName){
            tFnd=tI;
        }
    }
    return tFnd;
}

function setThemeClasses(themeName,themeClasses,themeCSS){
    tI = themeIndex(themeName);
    if(tI==-1){
        return false;
    }
    
    themeAR[tI].themeCCAR[themeAR[tI].themeCCAR.length] = new themeCC(themeClasses,themeCSS)
   return true;


}




function applyThemeCore(theme2Apply){
   // find theme
   //
//debug(theme2Apply)
  
   tI=themeIndex(theme2Apply);
   if(tI==-1){
       return false;
   }

   for(tcci=0;tcci<themeAR[tI].themeCCAR.length;tcci++){


   themeClasses = themeAR[tI].themeCCAR[tcci].themeClasses;
   themeCSS = themeAR[tI].themeCCAR[tcci].themeCSS;
  
  
//themeClasses may be space separated classes
  c2a = themeClasses.split(' ');
  //alert('core : ' + theme2Apply+'   '+tI+'   '+themeClasses+','+themeCSS)
  for(cai=0;cai<c2a.length;cai++){
      cl=c2a[cai];
      if(cl!=''){
          // now work through attributes
          a2a = themeCSS.split(';')
          for(aia=0;aia<a2a.length;aia++){
              att = a2a[aia];
              if(att!=''){
                  //split attributes
                  attAR = att.split(':')
                  attItem = attAR[0];
                  attValue = attAR[1];
                  if(attItem!=''&&attValue!=''){
                    //  $('.'+cl).css(attItem,attValue)
                     // alert(cl+','+attItem+'-'+attValue)
                      //themeChangeCSS(cl,attItem,attValue)
                      cssAlterClass(cl,attItem,attValue)
                  }
              }
          }
      }
    } // for(cai=0;cai<c2a.length;cai++){
   } // for(tcci=0;tcci<themeAR[tI].themeCCAR.length;tcci++){

   $('.themeselect').each(function (index,val){
       vi = val.id;

        t = vi.substring(6,vi.length)
        if(t==theme2Apply){
            $('#themeTick_'+t).css('display','')
        }else{
            $('#themeTick_'+t).css('display','none')
        }
   })

  
return true;
}


function applyTempTheme(theme2Apply){
   clearTimeout(themeTimer)
  
   applyThemeCore(theme2Apply)

}
var themeTimer;
var savedTheme = '';

function applyTheme(theme2Apply){


  $('#cisiThemen_'+savedTheme).removeClass('themeSelected')


   clearTimeout(themeTimer)
   applyThemeCore(theme2Apply)



   themeCookieString = JSON.stringify(themeAR);
   if (themeCookieString.length>20000){
       alert('Theme data too large to store in Cookie. Contact Systems')
       return false;
   }


   
  savedTheme = theme2Apply;

  // in case we are showing which theme is selected
  $('#cisiThemeSelection_'+theme2Apply).addClass('themeSelected')
   Set_Cookie('cisiThemeClass',theme2Apply,9999)
  return false;
   
}



function restoreSavedTheme(){
   applyTheme(savedTheme);
}

function restoreTheme(){

    themeTimer = setTimeout("restoreSavedTheme()",200)
}

function loadThemeFromCookie(){
    theme2Apply = Get_Cookie('cisiThemeClass')
    
    applyTheme(theme2Apply)

     $('BODY').css('display','')


    // if(getQuerystring('crannigan')=='1'){
     //        Delete_Cookie('cisiThemeClass');
     //}
    return false;
   

   
}



function themeChangeCSS(tClassName,tAttribute,tValue){}

function cssAlterClass(tClassName,tAttribute,tValue){
    tAtt=tAttribute;
    switch(tAttribute){
        case "background-color":tAtt='backgroundColor';
            break;
        case "background-image":tAtt='backgroundImage';
             break;
            case "border-left":tAtt='borderLeft';
            break;
            case "border-right":tAtt='borderRight';
            break;
            case "border-top":tAtt='borderTop';
            break;
            case "border-bottom":tAtt='borderBottom';
            break;
            		case "margin-left":tAtt='marginLeft';
            break;
            case "margin-right":tAtt='marginRight';
            break;
            case "margin-top":tAtt='marginTop';
            break;
            case "margin-bottom":tAtt='marginBottom';
            break;
            		case "padding-left":tAtt='paddingLeft';
            break;
            case "padding-right":tAtt='paddingRight';
            break;
            case "padding-top":tAtt='paddingTop';
            break;
            case "padding-bottom":tAtt='paddingBottom';
            break;



    }
    var ss = document.styleSheets;
    for (var i=0; i<ss.length; i++){
        var rules = ss[i].cssRules || ss[i].rules;
        for (var j=0; j<rules.length; j++) {
            if (rules[j].selectorText === "."+tClassName) {
                         rules[j].style[tAtt] = tValue;
                   
            }
        }
    }
}



function toggleShow(divID){
    
    tSdiv = $('#'+divID);
    if(tSdiv.hasClass('isiteHide')){
        tSdiv.removeClass('isiteHide')
    }else{
        tSdiv.addClass('isiteHide')
    }
}



function textWidth(text){
    var calc = '<span style="display:none">' + text + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};



function buildaBar(div,width,height,percent){

   percent= Math.round(percent)

    bst = '';

    bst += '<div style="width:' + width+'px;padding:0px;margin:0px;position:relative;">'
    divwidth = width+1;
    if (percent==0){
        bst+='  <div style="width:' + divwidth+'px;">'
        bst+='    <img src="web9/common/intranet/images/barbg.png" style="width:' + width+'px;height:' + height+'px;">';
        bst+='  </div>'
        w = textWidth('0%')
        l = (width - w) /2;
        bst+='<div class = "percentbarText" style="position:absolute;top:4px;left:' + l + 'px;">0%<div>'
    }
    if (percent==100){
        bst+='  <div style="width:' + divwidth+'px;">'
        bst+='    <img src="web9/common/intranet/images/red2green.png" style="width:' + width+'px;height:' + height+'px;">';
        bst+='  </div>'
        w = textWidth('100%')
        l = (width - w) /2;
        bst+='<div class = "percentbarText"style="position:absolute;top:4px;left:' + l + 'px;">100%<div>'
    }



  if (percent!=0&&percent!=100){

        bst+='  <div style="width:' + divwidth+'px;">'
        bl = Math.round(width * percent / 100);
        br = width - bl;
        bst+='<div style="width:'+bl+'px;overflow-x:hidden;float:left;margin:0px;border-right:1px solid #999999;">'
        bst+='<img src="web9/common/intranet/images/red2green.png" style="width:' + width+'px;height:' + height+'px;">'
        bst+='</div>';
        bst+='<div style="width:' + br+'px;overflow-x:hidden;direction:rtl;margin:0px;">'
        bst+='<img src="web9/common/intranet/images/barbg.png" style="width:' + width+'px;height:' + height+'px;direction:rtl;">'
        bst+='</div>'
        bst+='  </div>'
        w = textWidth(percent+'%')

        l = bl - (w/2);
        l = bl - (w + 10);
        bst+='<div class = "percentbarText" style="position:absolute;top:4px;left:' + l + 'px;">' + percent+'%<div>'
    }









    bst+='</div>'


    jQuery('#'+div).html(bst);

}


function storeSelect(selectID){
    docSel = document.getElementById(selectID)
    
    docSelVal = docSel.options[docSel.selectedIndex].value;
    Set_Cookie('selStore_'+selectID,docSelVal,9999)
   
}

function loadSelect(storeID){
   selVal = Get_Cookie('selStore_'+storeID);
  
   if(selVal==''||selVal == null){
       return false;
   }
  
  
   docSel = document.getElementById(storeID)
   if(docSel==undefined||docSel==null){
       return false;
   }

   for(i = 0 ; i<docSel.options.length;i++){
       if(docSel.options[i].value==selVal){
           docSel.selectedIndex=i;
       }
   }

}

function iFAQ(id){
    
    ifURL="/bookmark/genericform.aspx?form=29848780&url=iFAQ&ifaqid="+id
    window.open(ifURL,"_blank","titlebar=no,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,status=no,copyhistory=no, width=650, height=470");
}




function mouseoutSlide(e,elID,mouseoutClosediv,mouseoutCloseseconds){
    // first need to check the mouseout isn't being triggered by mousing over a div inside the outer div!
    //  (mouseout works this way)


    closeSlide(elID,mouseoutClosediv,mouseoutCloseseconds)
}



function toggleSlide(elID,mouseoutClosediv,mouseoutCloseseconds){
    sEL = jQuery('#'+elID);
    // is it already open?
    sELdisp = sEL.css('display')
    //alert(sELdisp)
    // currently open or closed
    if (sELdisp!='none'){
        // hide
         closeSlide(elID,"",0)
    }else{
        openSlide(elID,mouseoutClosediv,mouseoutCloseseconds)
     }
}


function openSlide(elID,mouseoutClosediv,mouseoutCloseseconds){
  
         sEL = jQuery('#'+elID);
         sEL.slideToggle("slow",function(){setFooterPosition()})

         if(mouseoutClosediv!=null&&mouseoutClosediv!=undefined&&mouseoutClosediv!=''){
             jQuery('#'+mouseoutClosediv).mouseleave(function(e){
                   mouseoutSlide(e,elID,mouseoutClosediv,mouseoutCloseseconds)
            })
         }
}


function closeSlide(elID,mouseoutClosediv,timer){
    
    // is it already closed?
    sEL = jQuery('#'+elID);
    sELdisp = sEL.css('display')
    // already closed?
    if (sELdisp=='none'){
        return false;
    }
  
  
    if(timer==undefined||timer==null||timer==0){
        
        sEL.slideToggle("slow",function(){setFooterPosition()})
         
    }else{
        clearTimeout(timerObjects[mouseoutClosediv]);
        jQuery('#'+mouseoutClosediv).unbind('mouseleave')
        tf = 'closeSlide("' + elID+'","",null);'

        timerObjects[mouseoutClosediv] = setTimeout(tf,timer*1000)

    }
   
}

