//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);}
}


/*--------------------------------------------------------------------------------------------------
                                     AUTOLIST FUNCTIONS
--------------------------------------------------------------------------------------------------*/									 

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">';

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
}


function addAutolist(id,autofire){
	// 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;
	al[al.length]=new autoL(id,autofire);
	
	
}

function triggerAutolist(id,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10){
	//alert(getQuerystring('url'));
        //alert(id);

	
	// fire off a single autolist
	search = document.forms[0].searchinput.value;
	//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 + "'";
	
	
	//if(id==33){
	//a = prompt('tim',p);
        //}
        // KARU
        if (getQuerystring('KARU')==1){
            //a = prompt('tim','id = '+id + ',' + p);
           // alert(id+'   ' + param1)
        }
	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+'_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+'_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 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;


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;
            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'){
                        colcount+=1;
                        if (rowcount==0){res_head=res_head+'<TH class="autolist_'+rAID+'_c' + colcount+'">'+y[i].childNodes[z].nodeName+'</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
                            row_data+=' id="'+rowID+'_' + colcount+'"'
                            row_data+=' class="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="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;


}
	
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);
		
		document.getElementById('autolist_'+alXML[alIndex].current_autolist_id).innerHTML = alXML[alIndex].current_autolist;

                //debug(alXML[alIndex].current_autolist)
		
		//debug(alXML[alIndex].current_autolist);
		
		
	}

	
	

/*--------------------------------------------------------------------------------------------------
                                     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){
	
	ssT = '';
	ssT += '<table class="interaction_' + interaction_id+'">';
	ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><div class="interaction_' + interaction_id + '">' + header +'<br><br></td></tr>';
	if(multiple_choice==1){
		//alert('ok');
		if (mcopt1!=''){
		ssT += '<tr class="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+'"><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+'"><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+'"><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+'"><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 + '">' + free_text_preamble+'</td></tr>';
		}
		ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><textarea class="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">';
	ssT+='<tr class="interaction_' + interaction_id+'"><td class="interaction_' + interaction_id+'" colspan="2"><input  onclick="submitInteraction(' +real_id+','+ interaction_id+','+multiple_choice+','+free_text+',\'' + header + '\',' + response_action+',\'' + message + '\',\'' + redirect+'\',\'' + param1 + '\',\'' + param2 + '\',\'' + param3+'\',' + div+');" class="interaction_button_' + interaction_id + '" type="button" value="submit">';
	
	if(response_action==2){// show chart?
		ssT+='<input  onclick="fetchInteractionChart(' + real_id+','+div+');" class="interaction_button_' + interaction_id + '" 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);
	
	
}


function submitInteraction(real_id,interaction_id,multiple_choice,free_text,header,response_action,message,redirect,param1,param2,param3,div){
	// 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){
		ft = fm['interaction_input_'+interaction_id].value;
		ft = ft.replace(/'/gi,'`');
		if (ft.length>1000){
			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);
	
	callAjax('isite_ia_response',p,'interactionResponse_'+real_id);
	//alert(response_action);
	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;
			
	}
	
	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">	';
	
}


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){
	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
	
	
	/**********************************
	                   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':colour3;
		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':colour2;
		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 
	
	
} // if(chart_type==0){ // pie chart
	

//a=prompt('',ch);


	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);
}



function popupInteractionComments(interaction_id,header){
	// popup window to show the comments
	
	var popup = new Array();
	popupURL = 'genericform.aspx?form=31740187&ID='+interaction_id;
      //  if(getQuerystring('crannigan')=='1'){

      
                $('#scTitle').html(header)
                triggerAutolist(53,interaction_id)
                callPopup('survey_comments',700,600,'<b>Survey Comments</b>')
        //}

/*

	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');
}
*/
}

/*--------------------------------------------------------------------------------------------------
                                     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){
	//alert(result+','+userContext+','+methodName)

//debug (result)

    if (userContext){

        //if (getQuerystring('crannigan')=='1'){a=prompt('',result)}

//alert(result);
		
                                // 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.substring(0,alucl)==aluc){
                                	autolistQueue(result,alid);
				}
					
		// 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 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){
	
	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;
        
        //debug(alStatus);
        if (alStatus==''){
            if(typeof window[userALfunc]!='undefined'){
                eval(userALfunc+'();')
            }
          
        }
        
	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
		
		js = getNode(alXML[processNeeded].xmlDoc,'JS');
                //if (getQuerystring('crannigan')=='1'){alert(js)}
		//execute the javascript	
		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);
	}


	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+'();')
            }

        


	alActive=0;
	
}

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 ('',procTag);
        //}
	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;
	}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);
	
	// ok, now look for closing ]]
	m=inText.indexOf(embedScriptEnd);
	js = '';
	if(m!=-1){
		js=inText.substring(0,m);
	}
	if(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)}
	
}


/*--------------------------------------------------------------------------------------------------
                                     SEARCH
--------------------------------------------------------------------------------------------------*/						
function doSearch(){
	var fm = document.forms[0];
	searchtext = fm.searchinput.value;
	if(searchtext==''){
		return false;
	}
	newurl = 'genericform.aspx?form=29848780&url=search&search=' + searchtext;
	window.location=newurl;
	//alert(searchtext);
}

/*--------------------------------------------------------------------------------------------------
                                     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';
      }
 


}





/*--------------------------------------------------------------------------------------------------
                                     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]}
	}
	return 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')
    }
}




function postLoad(){

if(getQuerystring('crannigan')=='1'){
    //  alert(jQuery('DIV.#timdiv').outerWidth());
     
}

  



	// 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=''}
	
	// 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 = getQuerystring('search');
		document.forms[0].searchinput.value = srch;
		document.getElementById('searchstring').innerHTML = srch;
	}
	
	 
	// run autolists
	if(al.length>0){
		runAutolists();
	}
	
	
	 
	// run interactions
	if(ia.length>0){
		runInteractions();
	}
	
	
	
	
	//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;
	}// 
}


//   setTimeout('forceRefresh()',refreshTime);
}



function callPopup(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;">',
                    onLoad:function(){

                             },
                    onComplete:function(){

                    },
                    onCleanup:function()
                    {
                         
                         $('#'+divID).css('display','none')
                         cleanupPopup();
                     }

            });
     $('#'+divID).css('display','block')

}


function cleanupPopup(){}
//shell - can be overridden on local page



/***********************************************
 *    function called from jQuery $ ready
 **********************************************/

function bdfProcessing(){

}

/***********************************************
 *    tooltips
 **********************************************/
