// JavaScript Document
//ajax method to load all initial data

var ajaxurl = 'gg.php';
var levelsArr = null; //cache the gg levels
var curForm;
var http_request = false;
var numre = /^\d+$/;
var globalRegion,globalOutputId;

function sg_makePOSTRequest(url, parameters, processingFunction, async, isPost) {
	  if(isPost == undefined) { isPost = true; }
	  if(async == undefined) { async = true; }
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            http_request.overrideMimeType('text/xml');
            //http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            alert('e1'+e);
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { alert('e2'+e); }
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  //alert('params:'+parameters);
      http_request.onreadystatechange = processingFunction;
	  try{
	  if(isPost) {
      http_request.open('POST', url, async);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Content-Disposition", 'form-data; name="gg.php"');
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
	  } else {
		//alert('get params:'+parameters);

		http_request.open("GET", url+'?'+parameters, async);
        http_request.send(null);
	  }
	  } catch (e) {
		  alert(e);
	  }
   }
 
   function sg_processOutput() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           //alert(http_request.responseXML);
           var resultstr = http_request.responseText;
           //alert(resultstr);
           //result = http_request.responseXML;
           var groupAtts, groupTitle, groupId, el, i, j, k, txt, attids, subgroupsArr, elementsArr, docEl, questionTextAtt, subgroupAtts, answerGroupList,answerType, answerItemAtts, answerGroupItem, answerItem,answerItemText, answerList, subgroupType, subgroupId, subgroupFreeTextType, subgroupFreeTextLen, answerLen;
           var rXML = http_request.responseXML.documentElement;
           var groupsArr = rXML.getElementsByTagName('group');
           for(i=0;i<groupsArr.length;i++) {
             groupAtts=groupsArr[i].attributes;
             groupTitle=groupAtts.getNamedItem("title");      
             groupId=groupAtts.getNamedItem("id");           
             //alert('id:'+id.value);
             if((el = document.getElementById('q_'+groupId.value+'_title')) != null) {
              //alert('got one');
				  el.innerHTML = groupTitle.value; 
             }
             //for each group get a document element to hang the questons off
             if((docEl = document.getElementById('q_'+groupId.value+'tt'))!=null) {
               subgroupsArr = groupsArr[i].getElementsByTagName('subgroup');
               answerGroupList = document.createElement('ul');
               for(j=0;j<subgroupsArr.length;j++) {
				  pagesectionArr = subgroupsArr[j].getElementsByTagName('pagesection');
				  if(pagesectionArr.length>0) {
					  var pagesectionitem = document.createElement("h2");
					  txt = document.createTextNode(pagesectionArr[0].childNodes[0].data);
					  pagesectionitem.appendChild(txt);
					  answerGroupList.appendChild(pagesectionitem);
				  }
                  subgroupAtts=subgroupsArr[j].attributes;        
                  questionTextAtt=subgroupAtts.getNamedItem("question");
                  subgroupType=subgroupAtts.getNamedItem("type");
                  subgroupFreeTextType=subgroupAtts.getNamedItem("freetexttype");
                  subgroupFreeTextLen=subgroupAtts.getNamedItem("freetextlen");
				  subgroupId=subgroupAtts.getNamedItem("id");
                  answerGroupItem = document.createElement('li');
                  answerGroupItem.setAttribute("list-style-type","none");
                  answerGroupItem.className = "answergroup";
                  txt = document.createTextNode(questionTextAtt.value);
                  answerGroupItem.appendChild(txt);
                  answerGroupList.appendChild(answerGroupItem);
                  elementsArr = subgroupsArr[j].getElementsByTagName('element');
                  answerList = document.createElement('ul');
                  answerGroupList.appendChild(answerList);
				  //is there a page section

                  for(k=0;k<elementsArr.length;k++) {
                     answerItemText=elementsArr[k].childNodes[0].data;               
                     answerItemAtts=elementsArr[k].attributes;  
                     answerType = answerItemAtts.getNamedItem("type");
                     answerId = answerItemAtts.getNamedItem("id");
                     answerLen = answerItemAtts.getNamedItem("freetextlen");
                //answerType=answerItemAtts.getNamedItem("question");
                     answerItem = document.createElement('li');
                     answerItem.className = "answer";
                     //if the subgroup type is radio, and freetexttype is "" add radio here, else if freetexttype is numeric, make a short text input
                     if(answerType.value == "radio") {
					   //if(subgroupFreeTextLen.value == "2") {
					   if(subgroupFreeTextType.value == "numeric") {
                       try { 
                          txt = document.createElement('<input type="text" size="10" name="a.'+subgroupId.value+'" value="a+'+subgroupId.value+' r" />'); 
                       } catch(err) { 
                          txt = document.createElement("input"); 
                       }
                       txt.setAttribute('type','text');
                       //the name of the radio group should be the subgroup id
                       txt.setAttribute('name','r a.'+subgroupId.value);
                       txt.setAttribute('value','r a.'+subgroupId.value);  
					   txt.setAttribute('size','10'); 
                       answerItem.appendChild(txt);						   
						   
						   
					   } else {
                       try { 
                          txt = document.createElement('<input type="radio" name="a.'+subgroupId.value+'" value="a+'+subgroupId.value+'" />'); 
                       } catch(err) { 
                          txt = document.createElement("input"); 
                       }
                       txt.setAttribute('type','radio');
                       //the name of the radio group should be the subgroup id
                       txt.setAttribute('name','a.'+subgroupId.value);
                       txt.setAttribute('value','a.'+subgroupId.value);    
                       answerItem.appendChild(txt);
					  }
                      }
                      txt = document.createTextNode(answerItemText);
                      answerItem.appendChild(txt);
                      //is it radio or text
                      if(answerType.value == "text") {
						 if(answerLen.value == "2") {
                          try { 
                             txt = document.createElement('<input type="text" size="10" name="a.'+answerId.value+'" value="a+'+answerId.value+' t" />'); 
                          } catch(err) { 
                             txt = document.createElement("input"); 
                          }
                          txt.setAttribute('type','text');
                          //the name of the radio group should be the subgroup id
                          txt.setAttribute('name','t a.'+answerId.value);
                          txt.setAttribute('value','t a.'+answerId.value);  
					      txt.setAttribute('size','10');  
						 } else {
                          txt = document.createElement('textarea');    
                          //txt.setAttribute('type','textarea');
                          txt.className = "ta";
                          txt.setAttribute('name','a.'+answerId.value);
                          txt.setAttribute('value','a.'+answerId.value);  
						 }
                         answerItem.appendChild(txt);
                      } else {
                      }
                      answerGroupList.appendChild(answerItem);
                     }
                    }
					//submit button
					var submititem = document.createElement('div');
					submititem.setAttribute('align','center');
					txt = document.createElement('input');
					txt.setAttribute('type','submit');
                    txt.setAttribute('value','Submit your answers');
                    submititem.appendChild(txt);
					answerGroupList.appendChild(submititem);
                    docEl.appendChild(answerGroupList);
                   }
                  }
				  if((el = document.getElementById('next_url')) != null) {
					if(groupId.value == "10") {
                     el.value = 'gg.php?action=listOfQs&contentType=text/html'; 
					} else {
                     el.value = 'gg.php?action=displayQuestion&qe_num=1&q_group_num='+((groupId.value*1)+1); 
					}
                  }
                  if((el = document.getElementById('output')) != null) {
                    el.innerHTML = 'DEBUG: fit.php says POST data is: '+groupsArr.length+' long. results: <pre>'+resultstr+'</pre>. Data stored'; 
                  }
                  if((el = document.getElementById('taoutput')) != null) {
                    el.value = resultstr; 
                  }
         } else {
            alert('There was a problem with the request.');
         }
      }
   }

 function sg_retrieve(obj,qe_num,q_num) {
   //iterate the form - any selected radios, checkboxes, values in text or textarea fields
   curForm = obj;
   var poststr = "action=displayQuestions&contentType=text/xml&qe_num="+qe_num;
   if(q_num!=undefined) {
	  poststr += "&q_group_num="+q_num; 
   }
   sg_makePOSTRequest(ajaxurl, poststr, sg_processOutput);
}   

function init(f,qe_num,q_num) {
     //run the query
     sg_retrieve(f,qe_num,q_num);
}



   function sg_processRegionOutput() {
	  var el;
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           //alert(http_request.responseXML);
            //var resultstr = http_request.responseText;
            //alert('sg_processLoginOutput ok');		   
		    if((el = document.getElementById(globalOutputId)) != null) {
              //el.value = 'resultstr: '+resultstr; 
			  var rXML = http_request.responseXML.documentElement;
			  regionArr = rXML.getElementsByTagName(globalRegion);
			  if(regionArr != null && regionArr.length>0 && regionArr[0].childNodes[0] != undefined) {
              el.innerHTML = Math.floor(regionArr[0].childNodes[0].data); 
			  }
            } else {
             //alert('1There was a problem with the request.');
            }
		 } else {
             alert('2There was a problem with the request. http_request.status: '+http_request.status);
         }
      } else {
             //alert('3There was a problem with the request.');
      }
   }
      function sg_processSessionOutput() {
	  var el;
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           //alert(http_request.responseXML);
            //var resultstr = http_request.responseText;
            //alert('sg_processLoginOutput ok');		   
		    if((el = document.getElementById('sessionOutput')) != null) {
              //el.value = 'resultstr: '+resultstr; 
			  var rXML = http_request.responseXML.documentElement;
			  regionArr = rXML.getElementsByTagName('sessionoutput');
              el.innerHTML = regionArr[0].childNodes[0].data; 
            } else {
             //alert('1There was a problem with the request.');
            }
		 } else {
             alert('2There was a problem with the request. http_request.status: '+http_request.status);
         }
      } else {
             //alert('3There was a problem with the request.');
      }
   }

   function sg_processLoginOutput() {
	  var el;
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           //alert(http_request.responseXML);
            var resultstr = http_request.responseText;
            //alert('sg_processLoginOutput ok');		   
		    if((el = document.getElementById('output')) != null) {
              //el.value = 'resultstr: '+resultstr; 
              el.value = 'resultstr wd go ere '; 
            } else {
             //alert('1There was a problem with the request.');
            }
           //result = http_request.responseXML;
var groupAtts, groupTitle, groupId, el, i, j, k, txt, attids, subgroupsArr, elementsArr, docEl, questionTextAtt, subgroupAtts, answerGroupList,answerType, answerItemAtts, answerGroupItem, answerItem,answerItemText, answerList, subgroupType, subgroupId;
			var rXML = http_request.responseXML.documentElement;
			//var errArr = rXML.getElementsByTagName('Err');
			//alert('err: '+errArr[0].childNodes[0].data);
			levelsArr = rXML.getElementsByTagName('Level');
			alert('levels: '+levelsArr.length);
		 } else {
             alert('2There was a problem with the request. http_request.status: '+http_request.status);
         }
      } else {
             //alert('3There was a problem with the request.');
      }
   }
   
function sg_retrieveLogin() {
   //iterate the form - any selected radios, checkboxes, values in text or textarea fields
   //curForm = obj;
   var poststr = "action=initLoginData&contentType=text/xml";
   //sg_makePOSTRequest('fit.php', poststr);
   sg_makePOSTRequest(ajaxurl, poststr, sg_processLoginOutput);
}  

function initLogin(f) {
	/*
	var ck = unescape(readCookie('gguk'));
	alert(ck);
	if(ck!=null) {
		var ckArr = ck.split("^");
		if(f.unitNumber!=undefined) { f.unitNumber.value = ckArr[1]; }
		if(f.unitSearch!=undefined) { f.unitSearch.value = ckArr[1]; }
	}
	*/
    //run the query
	if(levelsArr==null) {
      sg_retrieveLogin();
	} else {
	  alert('cached levels: '+levelsArr.length);
	}
}

function searchLogin(searchTerm) {
	//alert('search for:'+searchTerm);
	var i = 0, fullNameArr, idArr;
	if(searchTerm!=undefined && searchTerm!="") {
		if(levelsArr==null) {
               sg_retrieveLogin();
		} 
		if(searchTerm.match(numre)) {
			searchLoginByNumber(searchTerm);
			return;
		}
		var el = document.getElementById('output');
		el.value = '';
		var myregexp = new RegExp(searchTerm, "i");
		//alert('levelsArr:'+levelsArr.length);
		for(i=0;i<levelsArr.length;i++) {			
		   fullNameArr = levelsArr[i].getElementsByTagName('FullName');
           if(fullNameArr[0].childNodes[0].data.match(myregexp)!=null) {
			   idArr = levelsArr[i].getElementsByTagName('Level_no');
			   el.value += fullNameArr[0].childNodes[0].data+" - "+idArr[0].childNodes[0].data+"\n";
		   }
		}		
	}
}
function searchLoginByNumber(searchTerm) {
	//alert('search for:'+searchTerm);
	var i = 0, fullNameArr, idArr;
	if(searchTerm!=undefined && searchTerm!="") {
		if(levelsArr==null) {
               sg_retrieveLogin();
		} 
		var el = document.getElementById('output');
		el.value = '';
		var myregexp = new RegExp(searchTerm, "i");
		//alert('levelsArr:'+levelsArr.length);
		for(i=0;i<levelsArr.length;i++) {			
		   fullNameArr = levelsArr[i].getElementsByTagName('Level_no');
           if(fullNameArr[0].childNodes[0].data.match(myregexp)!=null) {
			   idArr = levelsArr[i].getElementsByTagName('FullName');
			   el.value += fullNameArr[0].childNodes[0].data+" : "+idArr[0].childNodes[0].data+"\n";
		   }
		}		
	}
}

//code for displaying and hiding question groups
var hicol = new Object();
hicol["q_1"] = "#CCFFFF";
hicol["q_2"] = "#CCFFeF";
hicol["q_3"] = "#CCFFdF";
hicol["q_4"] = "#CCFFcF";
hicol["q_5"] = "#CCFFbF";
hicol["q_6"] = "#CCFFaF";
hicol["q_7"] = "#CCFF7F";
hicol["q_8"] = "#CCFF6F";
hicol["tab1"] = "#CCFFFF";
hicol["tab2"] = "#CCFF6F";

var lastID = '';
function show (el) {
var thisID = el.id;
//alert(hicol[el.id]);
el.style.background = hicol[thisID];
//el.style.fontWeight = 'bold';
el.className = 'hiHeading';
//el.style.background = '#CCFFFF';
var textel = thisID+'t';
var closeel = thisID+'c';
var imgelid = thisID+'i';
var imgel;
if((imgel = document.getElementById(imgelid))!=null) {
imgel.src = 'minimize.gif';
}
if(lastID!='') {
var lastText = lastID+'t';
var lastClose = lastID+'c';
var lastImageId = lastID+'i';
document.getElementById(lastText).style.display = 'none';
document.getElementById(lastClose).style.display = 'none';
//document.getElementById(lastID).style.fontWeight = 'normal';
document.getElementById(lastID).className = 'normalHeading';
if((imgel = document.getElementById(lastImageId))!=null) {
imgel.src = 'maximize.gif';
}
}
if(lastID!=thisID) {
lastID = thisID;
//alert('lastID:'+lastID);
document.getElementById(textel).style.zIndex = '998';
document.getElementById(textel).style.display = 'block';
document.getElementById(textel).style.position = 'relative';
document.getElementById(textel).style.fontWeight = 'normal';
//document.getElementById(textel).style.fontWeight = 'normal';
document.getElementById(closeel).style.zIndex = '995';
document.getElementById(closeel).style.display = 'block';
document.getElementById(closeel).style.position = 'relative';
} else {
lastID = '';
}
}
function tclose (el) {
var closel = '', textel = '', lastImageId, imgel;
//alert('close lastID:'+lastID);
if(lastID!='') {
closel = lastID+'c';
textel = lastID+'t';
lastImageId = lastID+'i';
document.getElementById(textel).style.display = 'none';
document.getElementById(textel).style.zIndex = '-1';
document.getElementById(textel).style.position = 'relative';
//document.getElementById(lastID).style.fontWeight = 'normal';
document.getElementById(lastID).className = 'normalHeading';

document.getElementById(closel).style.display = 'none';
document.getElementById(closel).style.zIndex = '-1';
document.getElementById(closel).style.position = 'relative';
if((imgel = document.getElementById(lastImageId))!=null) {
imgel.src = 'maximize.gif';
}
}
lastID = '';
}
function hi (el) {
el.style.background = hicol[el.id];
}
function lo (el) {
el.style.background = 'white';
}
function goToPage (url) {
window.location = url;
}

//form must have numeric unitNumber
function validateRegistration (f) {
if(f.unitNumber != undefined && f.unitNumber.value.match(numre)) {
alert('validateRegistration ok');
return true;
}
return false;
}

/*
gguk cookie, values split by ^:
0 - sessid
1 - unitNumber
2 - unitName
3 - userName
4 - userPw
5 - lastLoginTime

initCookie($sessid)
modifyCookie(index,value)
function initCookie($v) {
 setcookie("gguk", "$v^^^^^, time()+3600*24*365);  
}
function modifyCookie($i,$v) {
 global $sessid;
 if (isset($_COOKIE["gguk"])) {
 } else {
  initCookie($sessid);
 }
 $cValues = explode("^",$_COOKIE["gguk"]);
 $cValues[$i] = $v;
 setcookie("gguk", implode("^",$cValues), time()+3600*24*365);
}
*/

function readCookie(name) {
	if(document.cookie!=undefined) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	}
	return null;
}

/* do this on any page
are they logged in - update the logged in thing
are they registered - update the registered thing
*/



function initFromCookie () {
	var ck,el;
    if((ck = unescape(readCookie('gguk3')))!=null  && ck != "null") {
	   ck = ck.replace(/\+/g," ");
	   if((el = document.getElementById('loginUnit'))!=null || (el = document.getElementById('fUsername2'))!=null) { 
		 if(el.type!=undefined && el.type == 'text' && ck != "null") { el.value = ck; }
	   }
	} else {
	}
	if((ck = unescape(readCookie('gguk4')))!=null  && ck != "null") {
	   if((el = document.getElementById('loginPassword'))!=null || (el = document.getElementById('fPassword2'))!=null) { 
		 if(el.type!=undefined && el.type == 'password' && ck != "null") { el.value = ck; }
	   }
	}
	if((ck = unescape(readCookie('ggukl')))!=null && ck != "null") {
	 if((el = document.getElementById('isLoggedIn'))!=null) { 
	   el.innerHTML = 'Logged In'; 
	  } else { 
	   el.innerHTML = 'Not logged in'; 
	  }
    } else if((el = document.getElementById('isLoggedIn'))!=null) {
	  el.innerHTML = 'Not logged in'; 
	}
}

//image
function promote(id) {
//alert('i promote');
//target feature-image-img
var targetEl, sourceEl, targetUrl;
if((targetEl = document.getElementById('feature-image-img'))!=null) {
 if((sourceEl = document.getElementById(id))!=null) {
	 if(sourceEl.src.indexOf('tn_118')!=-1) {
	 targetUrl = sourceEl.src.replace('tn_118','tn_320');
	 } else {
	 targetUrl = sourceEl.src.replace('tn_','tn_320');
	 }
	 targetEl.src = targetUrl;
     if((targetEl = document.getElementById('feature-image-alt'))!=null) {
	  targetEl.innerHTML = sourceEl.alt;
	 }
 }
}

}
var lastMaxHeight;

function expand (id) {
 var el;
 var textid = id+'text';
 if((el = document.getElementById(id))!=null) {
	 if(el.style.overflow=='hidden') {
	  el.style.overflow='visible';
	  lastMaxHeight = el.style.maxHeight;
	  el.style.maxHeight='none';
	  if((el = document.getElementById(textid))!=null) {
		  el.innerHTML = el.innerHTML.replace('more&gt;&gt;','&lt;&lt;less');
	  }
	 } else {
	  el.style.overflow='hidden';
	  el.style.maxHeight=lastMaxHeight;
	  if((el = document.getElementById(textid))!=null) {
		  el.innerHTML = el.innerHTML.replace('&lt;&lt;less','more&gt;&gt;');
	  }
	 }
 }
}

//line break to <br> conversion utils for textarea elements Chrisg 19.02.04
//Now generic to any field regards of name where output should be XHTML
function addBRtags(selObj){
    for (i=0; i < selObj.elements.length; i++){
    if (selObj.elements[i].type=="textarea"){
        if(selObj.elements[i].value.indexOf("<br />")==-1){
            selObj.elements[i].value = selObj.elements[i].value.replace(new RegExp("[\n\r]","g"),"<br />")
        }
    }
 }
 return true;
}

function removeBRtags(selObj){
    if(selObj){
        selObj.value = selObj.value.replace(new RegExp("<br />","g"),"\r");
        selObj.value = selObj.value.replace(new RegExp("<br>","g"),"\r");
    }
}

/*
<li><label for="patrol1">Patrol 1:</label> 
<input type="text" class="text" name="fPatrol1" id="patrol1" value="{$fPatrol1}" />
<label for="patrol1num">Number of girls in patrol:</label> 
<input type="text" class="tinytext" name="fPatrol1Num" id="patrol1num" value="{$fPatrol1Num}" />
</li>
*/
			
function addPatrolInput() {
  var ulel, el, txt, item, label, input, label2, input2, maxPatrols = 6;
  if((ulel = document.getElementById('patrollist'))!=null) {
	    //how many children
		//var children = ulel.childNodes;
		var children = ulel.getElementsByTagName('li');
		//alert(children.length);
		initialNum = children.length;
		nextNum = initialNum + 1;
		if(nextNum <= maxPatrols) {
        try { 
            item = document.createElement('<li>'); 
        } catch(err) { 
            item = document.createElement("li"); 
        }		
        try { 
            label = document.createElement('<label for="patrol'+nextNum+'">'); 
        } catch(err) { 
            label = document.createElement("label"); 
        }
		label.setAttribute('for','patrol'+nextNum);
		var txt = document.createTextNode('Patrol '+nextNum+': ');
        label.appendChild(txt);
		item.appendChild(label);
        try { 
            input = document.createElement('<input type="text" class="text" name="fPatrol'+nextNum+'" id="patrol'+nextNum+'" value="" />'); 
			//input.className = 'text';
        } catch(err) { 
            input = document.createElement("input"); 
        }
		input.setAttribute('type','text');
		input.setAttribute('class','text');
		input.setAttribute('name','fPatrol'+nextNum);
		input.setAttribute('id','patrol'+nextNum);
		input.setAttribute('value','fPatrol'+nextNum);
        item.appendChild(input);
        try { 
            label2 = document.createElement('<label for="patrol'+nextNum+'Num">'); 
        } catch(err) { 
            label2 = document.createElement("label"); 
        }
		label2.setAttribute('for','patrol'+nextNum+'num');		
		var txt2 = document.createTextNode(' Number of girls in patrol: ');
        label2.appendChild(txt2);
        item.appendChild(label2);
        try { 
            input2 = document.createElement('<input type="text" class="tinytext" name="fPatrol'+nextNum+'Num" id="patrol'+nextNum+'num" value="" />'); 
			//input2.className = 'text';
        } catch(err) { 
            input2 = document.createElement("input"); 
        }
		input2.setAttribute('type','text');
		input2.setAttribute('class','tinytext');
		input2.setAttribute('name','fPatrol'+nextNum+'Num');
		input2.setAttribute('id','patrol'+nextNum+'num');
		input2.setAttribute('value','fPatrol'+nextNum+'Num');
        item.appendChild(input2);
        ulel.appendChild(item);	 
		} else {
			if((el = document.getElementById('patroladvice'))!=null) {
			 el.innerHTML = 'Sorry, ' +maxPatrols +' is the maximum number of patrols you can register';
			}
		}
  }
}

function get_region_stats (region, elid, token) {
  if(region!=undefined && region!='') {
   globalOutputId = elid;
   globalRegion = region;
   var poststr = "action=get_region_stats&contentType=text/xml&token="+encodeURI(token);
   //sg_makePOSTRequest('fit.php', poststr);
   sg_makePOSTRequest(ajaxurl, poststr, sg_processRegionOutput);
 }
}

function setSessionValue ( name, val, async, token) {
   var poststr = "action=set_session_val&contentType=text/xml&name="+name+"&val="+encodeURI(val)+"&token="+encodeURI(token);
   //sg_makePOSTRequest('fit.php', poststr);
   sg_makePOSTRequest(ajaxurl, poststr, sg_processSessionOutput, async, false);
}
function setPatrolSessions ( list, token ) {
   var patrol_name, loc;
   if(list!=undefined) {
    setSessionValue('patrol_number',list[list.selectedIndex].value, false, token);
	if(list[list.selectedIndex].value == '') { patrol_name = ''; } else { patrol_name = list[list.selectedIndex].text; }
    setSessionValue('patrol_name',patrol_name, false, token);
	loc = window.location.href;
	loc = loc.replace(/fPatrolNumber=\d+/,'fPatrolNumber='+list[list.selectedIndex].value)
	loc = loc.replace(/u?n?skip/,'display');
	//alert(loc)
	window.location = loc;
   }
}

function initHome () {
	var el;
	if((el = document.getElementById('homepagequote'))!=null) {
		if(el.innerHTML == '') {
			if((el = document.getElementById('homepagequotebox'))!=null) {
				el.style.display = 'none';
			}
		}
	}
}

function challengeTweaks () {
	var loc = window.location.href;
	var qnumRegex = /question_group_number=(\d+)/;
	var m = loc.match(qnumRegex);
	var labels, i, labtext, boldMatcher1, boldMatcher2;
	if(m) {
		if(m[1] == 9) {
         labels = document.getElementsByTagName('label');
		  boldMatcher1 = /(some low\-energy bulbs)/;
		  boldMatcher2 = /(no low\-energy bulbs)/;
		  for(i=0;i<labels.length;i++) {
			labtext = labels[i].innerHTML;
			if(m = labtext.match(boldMatcher1)) {
				labels[i].innerHTML = labtext.replace(m[1],"<b>"+m[1]+"</b>");						
			} else if(m = labtext.match(boldMatcher2)) {
				labels[i].innerHTML = labtext.replace(m[1],"<b>"+m[1]+"</b>");	
			}
		  }			
		} else if(m[1] == 6) {
          labels = document.getElementsByTagName('label');
		  boldMatcher1 = /(double\-glazing in some rooms)/;
		  boldMatcher2 = /(no double\-glazing at all)/;
		  for(i=0;i<labels.length;i++) {
			labtext = labels[i].innerHTML;
			if(m = labtext.match(boldMatcher1)) {
				labels[i].innerHTML = labtext.replace(m[1],"<b>"+m[1]+"</b>");						
			} else if(m = labtext.match(boldMatcher2)) {
				labels[i].innerHTML = labtext.replace(m[1],"<b>"+m[1]+"</b>");						
			}
		  }
		}
	}
}


  function sg_processGSI() {
	  //alert('sg_process_get_session_info');
	  var el, i = 0, unitArr, frag;
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           //alert(http_request.responseXML);
            var resultstr = http_request.responseText;
            //alert('sg_process_get_session_info ok');		   
		    if((el = document.getElementById(globalOutputId)) != null) {
			  var rXML = http_request.responseXML.documentElement;
			//var errArr = rXML.getElementsByTagName('Err');
			//alert('err: '+errArr[0].childNodes[0].data);
			  var sessionsArr = rXML.getElementsByTagName('session');
			  for(i=0;i<sessionsArr.length;i++) {
				  frag = '';
				  unitArr = sessionsArr[i].getElementsByTagName('unit_name');
				  if(unitArr[0]!=undefined) {
				   frag += unitArr[0].childNodes[0].data+' ';
				  }
				  unitArr = sessionsArr[i].getElementsByTagName('ip_address');
				  if(unitArr[0]!=undefined) {
				   frag += unitArr[0].childNodes[0].data+' ';
				  }
				  if(frag!='') {
					  el.innerHTML += frag+'<br />';
				  }
			  }
			  el.style.display = 'block';
              //el.value = 'resultstr: '+resultstr; 
              //el.innerHTML = 'resultstr wd go ere '; 
            } else {
             //alert('1There was a problem with the request.');
            }
           //result = http_request.responseXML;
		 } else {
             alert('2There was a problem with the request. http_request.status: '+http_request.status);
         }
      } else {
             //alert('3There was a problem with the request.');
      }
   }
   
function gsi (id, token) {
 globalOutputId = id;
 //alert('gsi');
 var poststr = "action=get_sessions&contentType=text/xml&token="+encodeURI(token);
 //sg_makePOSTRequest('fit.php', poststr);
 sg_makePOSTRequest(ajaxurl, poststr, sg_processGSI);
 //sg_makePOSTRequest(ajaxurl, poststr, sg_processRegionOutput);
}


  function sg_processGRU() {
	  var el, i = 0, unitArr, levArr, frag;
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            var resultstr = http_request.responseText;
            //alert('sg_process_get_session_info ok');		   
		    if((el = document.getElementById(globalOutputId)) != null) {
			  var rXML = http_request.responseXML.documentElement;
			//var errArr = rXML.getElementsByTagName('Err');
			//alert('err: '+errArr[0].childNodes[0].data);
			  var sessionsArr = rXML.getElementsByTagName('unit');
			  //alert('got '+sessionsArr.length+' units sg_processGRU');
              frag = '';
			  for(i=0;i<sessionsArr.length;i++) {
				  
				  unitArr = sessionsArr[i].getElementsByTagName('unit_name');
				  if(unitArr[0]!=undefined) {
				   frag += unitArr[0].childNodes[0].data+' ';
				  }
				  levArr = sessionsArr[i].getElementsByTagName('level_number');
				  if(levArr[0]!=undefined) {
				   frag += levArr[0].childNodes[0].data+'<br />';
				  }

			  }
			  if(frag!='') {
				//alert('frags '+frag+' globalOutputId'+globalOutputId);

				el.innerHTML = frag;
				el.style.display = 'block';
			  }

			  
              //el.value = 'resultstr: '+resultstr; 
              //el.innerHTML = 'resultstr wd go ere '; 
            } else {
             //alert('1There was a problem with the request.');
            }
           //result = http_request.responseXML;
		 } else {
             alert('2There was a problem with the request. http_request.status: '+http_request.status);
         }
      } else {
             //alert('3There was a problem with the request.');
      }
   }
function gru (id, token) {
 globalOutputId = id;
// alert('gru');
 var poststr = "action=get_registered_units&contentType=text/xml&token="+encodeURI(token);
 //sg_makePOSTRequest('fit.php', poststr);
 sg_makePOSTRequest(ajaxurl, poststr, sg_processGRU);
 //sg_makePOSTRequest(ajaxurl, poststr, sg_processRegionOutput);
}

function hilite(id) {
 if((el = document.getElementById(id)) != null) {
	 el.style.backgroundColor = '#ffc';
 }

}
   
//initFromCookie();


