function archive_user(id) {
	if(confirm('Are you sure you wish to change this users archive status?')) {
		window.location = '/admin/select_user.php?archive_user='+id;
	}
	else {
		return false;
	}
}

/*****************************************************
Function: add/remove elements from the document
******************************************************/

function removeElement(parentID,elementID){
	var parent = document.getElementById(parentID);
	var child = document.getElementById(elementID);
	
	parent.removeChild(child);
}
function addElement(parentID,elementID,elementType,secondType){
	var newElement = document.createElement(elementType);
	newElement.setAttribute('id',elementID);
	var parent = document.getElementById(parentID);
	
	if(secondType){
		newElement.type = secondType;	
	}
	parent.appendChild(newElement);
}

function setElementAttribute(id,stype,text){
	var element = document.getElementById(id);
	
	element.setAttribute(stype,text);
}
/*****************************************************
Function: confirm delete
******************************************************/
function confirmDelete(delUrl) {
  if (confirm("Are you sure you want to delete?")) {
    document.location = delUrl;
  }
}

/*****************************************************
Function: redirect to page
*****************************************************/
function redirect(page){
	if(page) document.location.href = page;	
}
/*****************************************************
Function: check value agains regular expression
******************************************************/
function checkRegExpress(reg,id,format){
	var element = document.getElementById(id);
	
	if(!element.value.match(reg)){
		showError(format);
		return false;
	}else{
		return true;	
	}
}


/*****************************************************
Function: show/hide div
******************************************************/
function showHideElement(element,bstate){ //state: true = show ; false = hide
	var div = document.getElementById(element);
	
	if(bstate){
		div.style.display = 'block';
	}else{
		div.style.display = 'none';
	}
}

function showHideElementAuto(element){ //state: true = show ; false = hide
	var div = document.getElementById(element);
	
	if(div.style.display == 'none'){
		div.style.display = 'block';
	}else{
		div.style.display = 'none';
	}
}

function toggleLayer( whichLayer ){
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
    elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function toggleLabel( whichButton ){
  var elem, label;
  elem = document.getElementById( whichButton );
  label = elem.value;
  if(whichButton == 'more'){
    if(label == 'List More'){
        elem.value = 'List Less';
    }else{
        elem.value = 'List More';
    }
  }
}


/*****************************************************
Function: page information
******************************************************/
if(document.all) { 
	document.onmousemove = UpdateCursorPositionDocAll; 
}else {
	document.onmousemove = UpdateCursorPosition; 
}

var cX = 0; var cY = 0;

function UpdateCursorPosition(e){
	cX = e.pageX; 
	cY = e.pageY;
}
function UpdateCursorPositionDocAll(e){
	cX = event.clientX; 
	cY = event.clientY;
}


function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

/*****************************************************
Function: check to see if an element is in an array
******************************************************/
function inArray(arr,value){
	var found = false;
	
	for(x in arr){
		if(arr[x] == value){
			found = true;
			break;
		}
	}
	
	return found;
}

/*****************************************************
Function: Macromedia functions
******************************************************/
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
/*****************************************************
Function: get vars from URL
******************************************************/
function getURLHash() {
	var q = document.location.hash;
	if(q) {
		alert(q.substring(1,q.length));
	}
	return "";
}

var radio_uncheck = new Array();
function radio_checked(input, value, q_id) {
	radio_uncheck.push(q_id+'_'+value);
	var radios = document.getElementsByName(input), i=0, last, now;
	//loop through the radios - if the input is checked and was clicked, uncheck it.
	for(i=0;i<radios.length;i++) {
		if(parseInt(radios[i].value) == parseInt(value) && radios[i].checked) {
			//check last check
			now = radio_uncheck.pop();
			last = radio_uncheck.pop();

			if(last != 'undefined' && last == now) {
				radios[i].checked = false;
				document.getElementById(q_id+'_'+value).setAttribute("class", "radio");
				document.getElementById(q_id+'_'+value).setAttribute("className", "radio");
			}
			else {
				if(last != 'undefined') {
					radio_uncheck.push(last);
				}
				radio_uncheck.push(now);
			}
		}
	}
}

function radio_out() {
	document.getElementById('empty_div').innerHTML = 'asdf';
}
function SubmitTemplateAndGoBack(templateId, min_options) {
	$('redirect').name = '';
	$('redirectback').name = 'redirectback';
	
	
	SubmitTemplate(templateId, min_options);
}
function SubmitTemplate(templateId, min_options) {
    var submit=false, error='';
	if(min_options == 'undefined' || min_options == '') {
		min_options = 99;
	}
	else {
		min_options = parseInt(min_options);
	}
    switch(templateId) {
        case 1:
        case 4:
            submit=CheckRadioInputs();
            if(!submit && min_options > 0) {
				error='An option must be selected for this question.';
                break;
            }
            else {
            	submit = true;
            }
            break;
        case 2:
            submit=true;
            break;
        case 3:
        case 7:
            var list=document.getElementsByTagName("input"),length=list.length;
            for(var i=0;i<length;i++) {
                var obj=list[i];
                if(obj.type=='checkbox'&&obj.checked) {
                    submit=true;
                    break;
                }
            }
            if(!submit && min_options > 0) {
                error='At least one option must be selected.';
            }
            else {
            	submit = true;
            }
            break;
        case 8:
            var list=document.getElementsByTagName("input"),length=list.length;
            var checkedCount=0,groupMinOptions=MM_findObj('groupMinOptions');
            for(var i=0;i<length;i++) {
                var obj=list[i];
                if(obj.type=='checkbox'&&obj.checked) {
                    checkedCount++;
                    submit=true;
                }
            }
            if(!submit) {
            	
            	alert("An option must be selected for this question");
            	
            	//removed min options alerts on 23/feb
            	//from email recieved wed 18th feb - list of changes from nick
            	
            	
                /*if(confirm('You have not selected any options.  Do you want to continue?')) {
                    submit = true;
                }
            } else if(checkedCount<groupMinOptions.value) {
                if(!confirm('You have only selected '+checkedCount+' qualities. Are you sure you want to proceed?')) {
                    submit = false;
                }*/
            }
            break;
		
		case 9:
			var list = document.getElementsByTagName("input");
			var list_textarea = document.getElementsByTagName("textarea");
			var length = list.length;
			var length_textarea = list_textarea.length;
			
			var groupMinOptions = MM_findObj('groupMinOptions').value;
			var i =0;
			var checkedCount = 0;
			submit = true;
			
			if(groupMinOptions != 0) {
				no_text = 1;
				for(i=0; i<length; i++) {
					if(list[i].type == 'text') {
						no_text = 0;
						if(list[i].value != '') {
							checkedCount++;
						}
					}
				}
				
				if(no_text) {
					for(i=0; i<length_textarea; i++) {
						if(list_textarea[i].value != '') {
							checkedCount++;
						}
					}	
				}
				
				if(checkedCount < groupMinOptions) {
					alert('You need to fill in text for '+groupMinOptions+' questions to proceed.');
					submit = false;
				}
			}
			break;

        case 10:
        	submit = true;
        	break;
    }
    if(error.length>0) {
    	
        alert(error);
    } else if(submit) {
    	
        var form=MM_findObj('template');
        form.submit();
    }
}
function CheckRadioInputs() {
    var list=document.getElementsByTagName("input"),length=list.length,checklist=new Array(),length2=checklist.length;
    var submit=true;
    for(var i=0;i<length;i++) {
        var obj=list[i];
        if(obj.type=='radio') {
            var doCheck=true;
            for(var j=0;j<length2;j++) {
                if(checklist[j]==obj.name) {
                    doCheck=false;
                    break;
                }
            }
            if(doCheck) {
                checklist[length2]=obj.name;
                var objlist=MM_findObj(obj.name),length3=objlist.length,checked1=false;
                if (length3>0) {
                    for(var k=0;k<length3;k++) {
                        if(objlist[k].checked) {
                            checked1=true;
                            break;
                        }
                    }	
                } else if (obj.checked) {
                    checked1=true;
                }
                if(!checked1) {
                    submit=false;
                    break;
                }
            }
        }
    }
    return submit;
}

function CheckCareerPlan1() {
    var list=document.getElementsByTagName("input"),length=list.length,checklist=new Array(),length2=checklist.length;
    var regexCareerPlan=new RegExp('^q[0-9]{1,2}','i');
    var submit=true;
    for(var i=0;i<length;i++) {
        var obj=list[i];
        if(obj.type=='radio') {
            var doCheck=true;
            var node = obj;
	        while(node!=null) {
		        if(node.tagName!=null && node.tagName=='DIV' && regexCareerPlan.test(node.id) && node.style.display=='none') {
			        doCheck=false;
			        break;
		        } else {
			        node = node.parentNode;
		        }
	        }
	        if(doCheck) {
                for(var j=0;j<length2;j++) {
                    if(checklist[j]==obj.name) {
                        doCheck=false;
                        break;
                    }
                }
                if(doCheck) {
                    checklist[length2]=obj.name;
                    var objlist=MM_findObj(obj.name),length3=objlist.length,checked1=false;
                    if (length3>0) {
                        for(var k=0;k<length3;k++) {
                            if(objlist[k].checked) {
                                checked1=true;
                                break;
                            }
                        }
                    } else if (obj.checked) {
                        checked1=true;
                    }
                    if(!checked1) {
                        submit=false;
                        break;
                    }
                }
            }
        }
    }
    return submit;
}

function SubmitForm(formId) {
    var submit=true, error='';
    switch(formId) {
        case 'careerready':
        case 'careerplan':
            submit=CheckCareerPlan1();
            if(!submit) {
                error='An option must be selected for each question.';
            }
            break;
    }
    if(submit) {
        var form=MM_findObj(formId);
        form.submit();
    } else if(error.length>0) {
        alert(error);
    }
}

function check(check) {
    var hidden=MM_findObj(check.name.replace('x','q'));
    if(!hidden) {
        hidden=MM_findObj(check.name.replace('x','qc'));
    }
    if(hidden) {
        hidden.value=check.checked?'1':'0';
    }
}
function check2(check) {
    check.value=check.checked?'1':'0';
}

function check3(check) {
    var hidden=MM_findObj('q' + check.value);
    
    if(hidden) {
        hidden.value=check.checked?'1':'0';
    }
}

var objInit=new Array();
function Initialise() {
    var len1=objInit.length;
    for(var i=0;i<len1;i++)
        eval(objInit[i]);
}

function InitAdd(fn1) {
    objInit[objInit.length]=fn1;
}

function checkxyz(checkElement,hiddenId) {
    var hiddenElement=MM_findObj(hiddenId);
    hiddenElement.value=checkElement.checked?'1':'0';
    var inputId=hiddenId.substring(0,hiddenId.lastIndexOf('_'));inputList=document.getElementsByTagName('input');inputListLength=inputList.length,criteriaGroupCount=0;
    for(var i=0;i<inputListLength;i++) {
        var input=inputList[i];
        if(input.name.length>=inputId.length) {
            if(input.name.substring(0,inputId.length)==inputId&&input.type.toLowerCase()=='hidden'&&parseInt(input.value)==1) {
                criteriaGroupCount++;
            }
        }
    }
    //alert(inputId);
    var inputElement=MM_findObj(inputId);
    inputElement.value=criteriaGroupCount;
}

var audio_on=true;
function toggle_imageaudio_alt(image) {
    if(audio_input_element==null) {
        audio_input_element=MM_findObj('audio');
        switch(audio_input_element.value) {
            case "0":
                audio_on=false;
                break;
            case "1":
                audio_on=true;
                break;
        }
        //alert(audio_input_element.value);
    }
    if(!audio_on) {
        image.src='/images/audio_on_trans.gif';
    } else {
        image.src='/images/audio_off_trans.gif';
    }
    audio_on=!audio_on;
    audio_input_element.value=audio_on?'1':'0';
}

function toggle_imageaudio(image,audio_name) {
    if(!audio_on) {
        image.src='/images/audio_on_trans.gif';
    } else {
        image.src='/images/audio_off_trans.gif';
    }
    audio_on=!audio_on;
    toggle_audio(audio_name);
}

function toggle_audio(audio_name) {
    var audio_id=get_audio_id(audio_name);
    if(audio_on) {
        soundManager.play(audio_id);
    } else {
        soundManager.stop(audio_id);
    }
    //alert(audio_input_element);
    if(audio_input_element==null) {
        audio_input_element=MM_findObj('audio');
        //alert(audio_input_element.value);
    }
    audio_input_element.value=audio_on?'1':'0';
}

var audio_sound_list=new Array();
function get_audio_id(audio_name) {
    var audio_id='',len1=audio_sound_list.length;
    for(var i=0;i<len1;i++) {
        if(audio_sound_list[i][1]==audio_name) {
            audio_id=audio_sound_list[i][0];
            break;
        }
    }
    if(audio_id=='') {
        audio_id='sound'+(len1+1);
        audio_sound_list[len1]=new Array();
        audio_sound_list[len1][0]=audio_id;
        audio_sound_list[len1][1]=audio_name;
        soundManager.createSound({id:audio_id,url:audio_name});
    }
    return audio_id;
}

var audio_input_element=null;

function page_tip(audio_name) {
    if(audio_input_element==null) {
        audio_input_element=MM_findObj('audio');
        switch(audio_input_element.value) {
            case "0":
                audio_on=false;
                break;
            case "1":
                audio_on=true;
                break;
        }
    }
    toggle_audio(audio_name);
}

function gov_tip(help_text) {
    var audio_image='';
    
    var close_button='<div style="float:right;"><img onclick="tt_HideInit();" src="/images/tip_balloon/close.gif"/></div>';
    var tip_html='<div style="display:blockl"><div style="padding-bottom:10px;">'+help_text+'</div>'+audio_image+close_button+'</div>';
    Tip(tip_html);    
}

function SubmitStartForm(formId) {
    var submit=ValidateStartForm();
    if(submit) {
        SubmitForm(formId);
    }
}

function ValidateStartForm() {
    var errors='';
//    errors=ValidateForm('yourName','Name','R','yourEmail','Email','RisEmail','yourEmailCheck','Re-enter Email','RisEmail','yourState','State','R');
    errors=ValidateForm('yourName','Name','R','yourState','State','R');
    var yourEmail=MM_findObj('yourEmail'),yourEmailCheck=MM_findObj('yourEmailCheck');
    if((trim1(yourEmail.value)!=''||trim1(yourEmailCheck.value)!='')&&yourEmail.value!=yourEmailCheck.value) {
        errors+='- Email does not match the confirmation Re-enter Email.\n';
    }
    if (errors) {
        alert('The following error(s) occurred:\n'+errors);
    }
    return (errors == '');
}

var regexR = new RegExp('^(\\s)?$','i');
var regexIsDateTime = new RegExp('^[0-9]{2}/[0-9]{2}/[0-9]{4}$','i');
var regexIsEmail = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$','i');
var regexIsPhone = new RegExp('^(\\(?\\+?[0-9]*\\)?)?[0-9_\\- \\(\\)]*$','i');
var regexIsURL = new RegExp('^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\'/\\\+&%\$#\\=~])*[^\\.\\,\\)\(\\s]$','i');

function ValidateForm() {
   var i,p,q,nm,test,num,min,max,errors='',args=ValidateForm.arguments;
   for (i=0; i<(args.length-2); i+=3) {
      test=args[i+2];
      val=MM_findObj(args[i]);
      if (val) {
         nm=args[i+1];
         if (nm=="")
            nm=val.name;
         if ((val=getInputValue(val))!="") {
            if (test.indexOf('isEmail')!=-1) {
               if (!regexIsEmail.test(val))
                  errors+='- '+nm+' must contain an e-mail address.\n';
            } else if (test.indexOf('isDateTime')!=-1) {
               if (!regexIsDateTime.test(val))
                  errors+='- '+nm+' must contain a datetime.\n';
            } else if (test.indexOf('isPhone')!=-1) {
               if (!regexIsPhone.test(val))
                  errors+='- '+nm+' must contain a phone number.\n';
            } else if (test.indexOf('isURL')!=-1) {
               if (!regexIsURL.test(val))
                  errors+='- '+nm+' must contain a url.\n';
            } else if (test!='R') {
               num = parseFloat(val);
               if (isNaN(val))
                  errors+='- '+nm+' must contain a number.\n';
               if (test.indexOf('inRange') != -1) {
                  p=test.indexOf(':');
                  min=test.substring(8,p);
                  max=test.substring(p+1);
                  if (num<min || max<num)
                     errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
               }
            }
         } else if (test.charAt(0) == 'R') {
            errors += '- '+nm+' is required.\n';
         }
      }
   }
    return errors;
}
function getInputValue(obj) {
    switch (obj.tagName) {
        case "INPUT":
            switch (obj.type) {
                case "radio":
                case "checkbox":
                    var len=obj.length;
                    if (len>0) {
                        for(var i=0;i<len;i++) {
		                    if(obj[i].checked) {
			                    return trim1(obj[i].value);
		                    }
	                    }	
                    } else if (obj.checked) {
                        return trim1(obj.value);
                    }
                    break
                default:
                    return trim1(obj.value);
                    break;
            }
        case "TEXTAREA":
            return trim1(obj.value);
            break;
        case "SELECT":
            return trim1(obj.options[obj.selectedIndex].value);
            break;
        default:
            var len=obj.length;
            if (len>0) {
                for(var i=0;i<len;i++) {
                    if(obj[i].checked) {
	                    return trim1(obj[i].value);
                    }
                }	
            } else if (obj.checked) {
                return trim1(obj.value);
            }
            break;
    }
    return '';
}
function trim1(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function checkClear(obj,i,j) {
    //alert('fucker');
    check(obj,i);
    clear(obj,j);
}
function clear(obj,val) {
    //alert('fucker');
}
function whynav(career_id, audio_name) {
    var audio_id = get_audio_id(audio_name);
    soundManager.stop(audio_id);
    
    var audio = MM_findObj('audio');
    var url = 'careerwhy.php?career_id='+career_id+'&audio='+audio.value;
    window.open(url,'Career','scrollbars=yes,width=1024,height=768,center=yes,directories=yes,status=yes,toolbar=yes,menubar=yes,resizable=yes,location=yes').focus();
}
function goonsubmit(form,url) {
    var audio = MM_findObj('audio');
    url += '?audio='+audio.value;
    form.action = url;
    //alert(form.action);
    form.submit();
}
function urlnav(url) {
    var audio = MM_findObj('audio');
    url += (url.indexOf('?') >= 0) ? '&audio='+audio.value : '?audio='+audio.value;
    document.location.href=url;
}
function DisplayFlash(name)
{
    document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="800" height="385">\n');
    document.write('<param name="movie" value="'+name+'">\n');
    document.write('<param name="quality" value="high">\n');
    document.write('<param name="menu" value="false">\n');
    document.write('<param name="BGCOLOR" value="#000000">\n');
    document.write('<param name="wmode" value="transparent">\n');
    document.write('<embed src="'+name+'" width="780" height="400" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#000000" wmode="transparent"></embed></object>\n');
}

function CheckEmail(sEmail){
	str = document.getElementById(sEmail).value;
	var Errors = false;
	var Emailerrors = false;
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if(str == ""){
		Emailerrors = true;	
	}
	if (str.indexOf(at)==-1){
	  Emailerrors = true;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   Emailerrors = true;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		Emailerrors = true;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		Emailerrors = true;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		Emailerrors = true;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		Emailerrors = true;
	 }
	
	 if (str.indexOf(" ")!=-1){
		Emailerrors = true;
	 }
	 if(Emailerrors){
		alert("Sorry, your email address is invalid!");
		return false;
	 }else{
		return true;	 
	 }
}

var q_id = '';
function populate_rto_dropdown(qualification_id, rto_id) {
	if(qualification_id && rto_id) {
		q_id = qualification_id;
		$(qualification_id+'_div').innerHTML = '<img src="/images/ajax-loader.gif" />';
		
		var vars = "action=RtoDropdown&qualification_id="+qualification_id+"&rto_id="+rto_id;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_rto_dropdown});
	}
}

function populate_qualification_search(search_text, question_id) {
	$('qualification_search').innerHTML = '<img src="/images/ajax-loader.gif" />';
	if(search_text){
		var vars = "action=QualificationSearch&question_id="+question_id+"&search_text="+search_text;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_qualification_search});
	}
	else{
		$('qualification_search').innerHTML = '';	
	}
}

function populate_industry_dropdown(industry_id, no_all) {
	if(no_all == 'undefined') {
		no_all = 0;
	}
	
	$('industry_option_dropdown').innerHTML = '<img src="/images/ajax-loader.gif" />';
	if(industry_id){
		var vars = "action=IndustryDropdown&no_all="+no_all+"&industry_id="+industry_id;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_industry_dropdown});
	}
	else{
		return false;	
	}
}

function populate_qualification_dropdown(package_id) {
	$('industry_option_dropdown').innerHTML = '<img src="/images/ajax-loader.gif" />';
	if(package_id){
		var vars = "action=QualificationDropdown&package_id="+package_id;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_industry_dropdown});
	}
	else{
		return false;	
	}
}

function update_qualifications() {
	var vars = "action=Import";
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_update_qualifications});
}

function success_update_qualifications(t) {
	$('up_div').innerHTML = 'Done!!';
}

/**
SEARCH AND POPULATE REPORTS
**/
function populate_qualification_unit_search(search_text, onclick) {
	if(search_text) {
		var unit_search_vars = '';
		var search_type = document.getElementsByName('search_type');
		if(search_type != null) {
			var i = 0;
			for(i=0; i<search_type.length; i++) {
				if(search_type[i].checked) {
					unit_search_vars = '&' + search_type[i].value + '=1';
				}
			}
		}
		var action = "PopulateQualificationUnitSearch";
		
		$('qual_unit_search_div').innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "onclick="+onclick+"&action="+action+"&search_text="+search_text+unit_search_vars;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_qual_unit_search});
	}
}
function populate_qualification_unit_search2(search_text, onclick, library) {
	if(search_text) {
		var unit_search_vars = '';
		var search_type = document.getElementsByName('search_type');
		if(search_type != null) {
			var i = 0;
			for(i=0; i<search_type.length; i++) {
				if(search_type[i].checked) {
					unit_search_vars = '&' + search_type[i].value + '=1';
				}
			}
		}
		var action = "PopulateQualificationUnitSearch2";
		
		var islibrary = "";
		if(library != null && library != undefined && library == true) {
			islibrary = "&library=yes";
		}
		
		$('qual_unit_search_div').innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "onclick="+onclick+"&action="+action+"&search_text="+search_text+unit_search_vars+islibrary;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_qual_unit_search});
	}
}

function success_qual_unit_search(t) {
	$('qual_unit_search_div').style.height = '250px';
	$('qual_unit_search_div').style.overflowY = 'scroll';
	$('qual_unit_search_div').innerHTML = t.responseText;
}

var new_rel_type = '';
var new_rel_id = '';
var new_report_type_id = '';
function add_qualification_unit(rel_type, rel_id, report_type_id) {
	if(report_type_id == 'undefined') {
		var report_type_id = 1;
	}
	
	//populate the add button with the spinner
	$(rel_type+'-'+rel_id+'-div').innerHTML = '<img src="/images/ajax-loader.gif">';
	var question_id = $(rel_type+'-'+rel_id+'-dropdown').value;
	
	//set globals
	new_rel_type = rel_type;
	new_rel_id = rel_id;
	new_report_type_id = report_type_id;
	
	var vars = "action=AddQualificationUnit&report_type_id="+report_type_id+"&rel_type="+rel_type+"&rel_id="+rel_id+"&question_id="+question_id;
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_update_qual_unit});
}
function add_qualification_unit2(rel_type, rel_id, library) {
	
	//populate the add button with the spinner
	$(rel_type+'-'+rel_id+'-div').innerHTML = '<img src="/images/ajax-loader.gif">';
	
	var question_id = $('questionID').value;
	var response = $('response').value;
	var opt = $('questionoption_id');
	var extraParam = '';
	if(opt) {
		extraParam += '&optionID=' + opt.value;
	}
	
	var islibrary = "";
	if(library != null && library != undefined && library == true) {
		extraParam += "&library=yes";
	}
	
	var vars = "action=AddQualificationUnit2&question_id="+question_id+"&response="+response+"&rel_type="+rel_type+"&rel_id="+rel_id+extraParam;
	//alert(vars);
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess: function(transport) {
		//alert(transport.responseText);
		$(rel_type+'-'+rel_id+'-div').innerHTML = '<img src="/images/checkblacktick.gif">';
	}});
}

function success_update_qual_unit(t) {
	//check if we need to add an onunload event.
	if(t.responseText == 'onunload') {
		rto_report = true;
	}
	
	//populate the add button with a tick
	$(new_rel_type+'-'+new_rel_id+'-div').innerHTML = '<input type="button" value="Remove" onclick="remove_qualification_unit(\''+new_rel_type+'\', \''+new_rel_id+'\', \''+new_report_type_id+'\');">';
}

function success_update_qual_unit2(t) {
	
	//populate the add button with a tick
	$(new_rel_type+'-'+new_rel_id+'-div').innerHTML = '<img src="/images/checkblacktick.gif">';
}

function remove_qualification_unit(rel_type, rel_id, report_type_id) {
	if(report_type_id == 'undefined') {
		var report_type_id = 1;
	}
	
	//populate the add button with the spinner
	$(rel_type+'-'+rel_id+'-div').innerHTML = '<img src="/images/ajax-loader.gif">';
	var question_id = $(rel_type+'-'+rel_id+'-dropdown').value;
	
	//set globals
	new_rel_type = rel_type;
	new_rel_id = rel_id;
	new_report_type_id = report_type_id;
	
	var vars = "action=RemoveQualificationUnit&report_type_id="+report_type_id+"&rel_type="+rel_type+"&rel_id="+rel_id+"&question_id="+question_id;
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_remove_qual_unit});
}

function success_remove_qual_unit(t) {
	$(new_rel_type+'-'+new_rel_id+'-div').innerHTML = '<input type="button" value="Add" onclick="add_qualification_unit(\''+new_rel_type+'\', \''+new_rel_id+'\', \''+new_report_type_id+'\');">';
}

var rto_report = false;
function body_onunload() {
	if(rto_report) {
		if(!confirm('Are you sure you wish to discard the generated qualifications and units?')) {
			if(navigator.appName != 'Netscape') {
				document.execCommand("Stop");
			}
			else {
				window.stop();
			}
			document.getElementById('qual_rto').submit();
		}
	}
	
	return true;
}

function nothing() {
	return true;
}

/**
SEARCH AND POPULATE REPORTS
**/

function unit_search(search_text, qualification_id) {
	if(search_text) {
		$('qual_unit_search_div').innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "action=PopulateUnitSearch&qualification_id="+ qualification_id+"&search_text="+search_text;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_qual_unit_search});
	}
}

function add_unit(qualification_id, unit_id) {
	//populate the add button with the spinner
	$(unit_id+'-div').innerHTML = '<img src="/images/ajax-loader.gif">';
	
	//set globals
	new_rel_id = unit_id;
	
	var vars = "action=AddUnit&unit_id="+unit_id+"&qualification_id="+qualification_id;
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_add_unit});
}

function success_add_unit(t) {
	$(new_rel_id+'-div').innerHTML = '<img src="/images/checkblacktick.gif">';
}

function success_add_qual_unit(t) {
	//populate the add button with a tick
	$(new_rel_type+'-'+new_rel_id+'-div').innerHTML = '<img src="/images/checkblacktick.gif">';
}

function success_rto_dropdown(t) {
	$(q_id +'_div').innerHTML = 'rto link updated!';
	setTimeout($(q_id +'_div').innerHTML = '', 2000);
}

function success_industry_dropdown(t) {
	$('industry_option_dropdown').innerHTML = t.responseText;
}

function success_qualification_search(t) {
	$('qualification_search').innerHTML = t.responseText;
}

function validate_new_user_form() {
	if($('industry_id').value == 'Please Select') {
		alert('Please select an industry.');
		return false;
	}
	//valid email
	if(!CheckEmail('user_email')) {
		return false;
	}
	//re-enter password
	if($('password').value != $('reenter_password').value){
		alert('Passwords do not match.');
		return false;
	}
	
	if($('password').value == '' && $('reenter_password').value == '') {
		alert('Enter a password.');
		return false;
	}
	
	if($('user_firstname').value == '') {
		alert('Please enter your first name.');
		return false;
	}
	if($('user_lastname').value == '') {
		alert('Please enter your last name.');
		return false;
	}
	
	
	return true;
}

function formError(field,msg){
	field.style.backgroundColor = 'yellow';
	alert(msg);
	field.focus()
}

function questiongroup_form() {
	if($('questiongroup_shortdescription').value == '') {
		formError($('questiongroup_shortdescription'), 'Please enter a short description for this question.');
		return false;
	}
	return true;
}

function show_hide(div_id) {
	if(document.getElementById(div_id).style.display == 'none') {
		document.getElementById(div_id).style.display = 'block';
	}
	else {
		document.getElementById(div_id).style.display = 'none';
	}
}

var delete_array = new Array();
function check_all_deletes() {
	var i = 0;
	while(i < delete_array.length) {
		delete_array[i].checked = !delete_array[i].checked;
		i++;
	}
}

function submit_answers(industry_id, industry_option_id, user_id) {
	$('submit_answers').innerHTML = '<img src="/images/ajax-loader.gif">';
	var vars = "action=SubmitAnswers&industry_id="+industry_id+"&industry_option_id="+industry_option_id+"&user_id="+user_id;
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_submit_answers});
}

function success_submit_answers(t) {
	$('submit_answers').innerHTML = '<font color="Red">Thank you for submitting your answers!</font>';
}

function delete_recommendation(recommendation_id) {
	$('recommendation_loader').innerHTML = '<img src="/images/ajax-loader.gif">';
	var vars = "recommendation_id="+recommendation_id+"&action=DeleteRecommendation";
	new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_delete_recommendation});
}

function success_delete_recommendation(t) {
	window.location.reload();
}


function go(url,w,h) {
	var dim = eval('"width=' + w + ',height=' + h + ',toolbar=0, location=0,directories=0,status=0, menubar=0,scrollbars=0,resizable=0"');
	Npop = window.open(url,"instruct",dim);
	Npop.moveTo(0,0);
	oldWin = Npop.opener;
}

function max_chars(input, max_chars, event) {
	if(event.keyCode == 46 || event.keyCode == 8) {
		return true;
	}
	var cur_value = input.value;
	if(cur_value.length >= max_chars) {
		return false;
	}
	else {
		return true;
	}
}

var ss_id = '';
var us_id = '';
function save_notes(user_id, survey_id) {
	if(survey_id) {
		ss_id = survey_id;
		$('save_' + survey_id).innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "action=SaveNotes&survey_id="+survey_id+"&notes="+$('notes_'+survey_id).value;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_save_notes_survey});
	}
	if(user_id) {
		us_id = user_id;
		$('save_' + user_id).innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "action=SaveNotes&user_id="+user_id+"&notes="+$('notes_'+user_id).value;
		new Ajax.Request('/includes/handler.php', {parameters:vars, onSuccess:success_save_notes_user});
	}
}

function success_save_notes_survey() {
	$('save_' + ss_id).innerHTML = 'saved!';
}

function success_save_notes_user() {
	$('save_' + us_id).innerHTML = 'saved!';
}

function questiontype_hide(value) {
	if(value == 9) {
		$('text_options').style.display = 'block';
	}
	else {
		$('text_options').style.display = 'none';
	}
}

function add_survey(survey_id, company) {
	//display
	$('button_div_' + survey_id).innerHTML = '<img src="/images/ajax-loader.gif">';
	if(company == 1) {
		//post form
		$(survey_id + '_company_button').disabled = true;
		var form = $('add_company_survey_' + survey_id);
		var params = form.serialize();
	    new Ajax.Request(form.action, {method:'post', postBody:params, onSuccess:add_survey_success});
	}
	else {
		//post form
		$(survey_id + '_user_button').disabled = true;
		var form = $('add_survey_' + survey_id);
		var params = form.serialize();
	    new Ajax.Request(form.action, {method:'post', postBody:params, onSuccess:add_survey_success});
	}
}

function add_survey_success(t) {
	$('button_div_' +  t.responseText).innerHTML = '<img src="/images/checkblacktick.gif">';
	$('users_surveys').innerHTML = '<img src="/images/ajax-loader.gif">';
	new Ajax.Request('/includes/handler.php', {method:'post', postBody:'action=ShowUserPlans', onSuccess:show_plans_success});
}

function show_plans_success(t) {
	$('users_surveys').innerHTML = t.responseText;
}

function confirm_save(link, question_type, minoptions) {
	if(confirm('Do you want to save your answers?')) {
		$('redirect').value = link;
		sleep(1000);
		SubmitTemplate(parseInt(question_type), parseInt(minoptions));
	}
	else {
		window.location = link;
	}
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function rto_eoi() {
	var rtos = document.getElementsByName('is_rto');
	if(rtos[0].checked) {
		if(rtos[0].value == 1) {
			$('rto_div').style.display = 'block';
		}
		else {
			$('rto_div').style.display = 'none';
		}
	}
	if(rtos[1].checked) {
		if(rtos[1].value == 1) {
			$('rto_div').style.display = 'block';
		}
		else {
			$('rto_div').style.display = 'none';
		}
	}
}

function process_new_user(ref, user_id) {
	var vars = "action=ProcessBatchUser&user_id=" + user_id + "&ref=" + ref;
	new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:process_new_user_success, onFailure:process_new_user_success});
}

function process_new_user_success(t) {
	window.location.reload();
}

function generate_link(sub_company_id) {
	$('generate_button').disabled = true;
	var vars = "action=GenerateLink&sub_company_id=" + sub_company_id;
	new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:gen_link_success});
}

function gen_link_success(t) {
	window.location = '/user/company_generate.php?success=1';
}

function ajax_show_answers(user_id) {
	var vars = "action=UserAnswers&user_id=" + user_id;
	new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:show_answers_success});
}

function show_answers_success(t) {
	$('ajax_user_answers').innerHTML = t.responseText;
	$('print_button').disabled = false;
}

function hide_all_answers(div_id) {
	//var answers = document.getElementsByClassName('answer_div');
	var answers = $$('div.answer_div');
	
	for(i=0;i<answers.length;i++) {
		if(answers[i].id != div_id) {
			answers[i].style.display = 'none';
		}
	}
}

function duplicate_survey(survey_id) {
	var new_survey_name = prompt("Enter a new survey name.");
	if(new_survey_name != null) {
		var vars = "action=DuplicateSurvey&survey_id=" + survey_id + '&survey_name=' + new_survey_name;
		new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:dup_surveys_success});
	}
}

function copy_lib_question(lib_question_id, survey_id, lib_question_title, survey_title) {
	var continueornot = confirm('Copy "' +lib_question_title+'" to survey "'+survey_title+'"?');
	
	if(continueornot == true) {
		var thediv = $(survey_id+'_survey');
		if(thediv == null) {
			thediv = $(lib_question_id+'_question');
		}
		thediv.innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "action=CopyLibQuestion&survey_id=" + survey_id + '&lib_question_id=' + lib_question_id;
		new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:function(file_row_result) {
			thediv.innerHTML = file_row_result.responseText;
		}
	 });
	}
}
function copy_question(question_id, survey_id, question_title, survey_title) {
	var continueornot = confirm('Copy "' +question_title+'" to survey "'+survey_title+'"?');
	
	if(continueornot == true) {
		$(survey_id+'_copy').innerHTML = '<img src="/images/ajax-loader.gif">';
		var vars = "action=CopyQuestion&survey_id=" + survey_id + '&question_id=' + question_id;
		new Ajax.Request('/includes/handler.php', {method:'post', postBody:vars, onSuccess:function(file_row_result) {
			$(survey_id+'_copy').innerHTML = file_row_result.responseText;
		}
	 });
	}
}

function noLogout() {
	new Ajax.Request('/includes/handler.php', {method:'post', postBody:'action=noLogout'});
}

function dup_surveys_success() {
	window.location = '/admin/surveys.php';
}