//at start up
$(document).ready(function(){
	//apply rounded corners to elements with rounded corners for non border-radius using browsers	
	if (!Modernizr.borderradius){		
		wbox();
		innerBox();
		dashBox();
		resultBox();
		topBottomBoxId('#contactbox','contactbox');
		leftRightBoxClass('#midarea:not(:has(#rightlinks)) .quickfact','qf');
		
		topBottomBoxClass('#rightlinks .quickfact', 'qft');
		topBottomBoxClass('.cbox','cbox');
		topBottomBoxClass('.events-box','events');
	}
	
	/*************************COUNTRY/PROVINCE******************************************/	
	$('#DemographicCountryId').change(function(){
		var url = checkUrlPath('/info/prov_json/') + $('#DemographicCountryId option:selected').val();
        $.getJSON(url,
                function(data){  
        			var str = '<option value="">Please Select</option>';
        			$.each(data, function(i,item){
        				str += '<option value="'+i+'">' + item + '</option>';
                    });
        			$('#DemographicProvId').html(str);
        			if ($('#provid').val() != ''){
        				$('#DemographicProvId').val($('#provid').val());
        				$('#provid').val('');
        			}
                });
	}).change();
	/*************************DIALOG*******************************/
	dialogWatch();
	/***************************Sidebar Accordion Menu********************************/	
	//initialize accordion
	$('#sidebarsection1').each(function(){
		$(this).accordion({
			collapsible:true,
			animated:'slide',
			header:'.secheader',
			navigation:true,			
			event:false,
			active:($('.grey-sel .expandcontrol').length > 0 ? Number($('.grey-sel').attr('id').replace('heading','')):false),
			change:function(event,ui){
				$('.secheader').removeClass('grey-sel').addClass('grey-unsel');				
				ui.newHeader.removeClass('grey-unsel').addClass('grey-sel');
			},
			autoHeight:false
		});
		//because otherwise the header links won't work
		$(this).find('.secheader a').click(function(){ 
			window.location.href = $(this).attr('href');
		});
		//select pane to open by default
		if ($('#sidebarsection1 .grey-sel .expandcontrol').length > 0){
			$(this).accordion('activate','#sidebarsection1 .grey-sel');
		}
		//activate actual control
		$(this).find('.expandcontrol').click(function(){ 
			var accordid = '#'+$(this).parent().attr('id');
			$('#sidebarsection1').accordion('activate', accordid);			
		});
		//remove empty sections
		$(this).find('.blankcontrol').parents('.secheader').next().remove();
	});
	/*************************Cake Session Flash****************************************/
	if ($('.session-flash').length){
		$('.contactform input[type="text"], .contactform textarea').val('');
	}
	/*************************GMAW WHAT Accordions**************************************/
	//initialize
	$('.res-inside').accordion({
		collapsible:true,
		animated:'slide',
		header:'h3',
		change:function(event,ui){
			ui.oldHeader.removeClass('res-what-minus').addClass('res-what-plus');
			ui.newHeader.removeClass('res-what-plus').addClass('res-what-minus');
		},
		active:false
	});
	/************************* EXPANDABLE BOXES **************************************/
	$('.expand').hide().prev().addClass('close');
	$('.expand-title', this).click(function(){
		if($(this).hasClass('open')){
			$(this).removeClass('open').addClass('close');
			$(this).next().slideUp();				
		}
		else{
			$('.expand').slideUp().prev().removeClass('open').addClass('close');
			$(this).removeClass('close').addClass('open').next().slideDown(function(){
				$('html, body').animate({scrollTop : Math.round($(this).position().top)-35});
			});
		}			
		return false;
	});	
	/*************************WHERE TO START TABS**************************************/
	$('#where-tab-container').tabs({
		selected:$('#tab-start-num').val()
	});
	$('.prev-step, .next-step').click(function(){
		var go = parseInt($(this).attr('title'), 10)-1;
		$('#where-tab-container').tabs('select',go);
		return false;
	});
	/*************************EVENTS EXPAND COLLAPSE***********************************/
	$('.description .viewmore').click(function(){
		$(this).hide();
		$(this).nextAll('.long, .viewless').show();
		return false;
	});
	$('.description .viewless').click(function(){
		$(this).hide();
		$(this).prevAll('.long').hide();
		$(this).prevAll('.viewmore').show();
		return false;
	});
	/*************************COLLAPSIBLE RESOURCE GROUPS*******************************/	
	$('div.resource-group').hide();
	$('div.res-group-label').click(function(){		
		if ($('body').hasClass('ie8')){
			$(this).find('span.res-group-head').toggleClass('plus minus');	
			if ($(this).next().css('display') == 'none'){
				$(this).next().css({'display':'block'});
				$('#res-box').css({'border':'0px solid white'});
			}else{
				$(this).next().css({'display':'none'});
			}
		}else{
			$(this).find('span.res-group-head').toggleClass('plus minus');	
			$(this).next().slideToggle();
		}
	});
    /*************************SCREENING WATCH**************************/
    $('#survey-progress-bar').progressbar({
    	'value':0
    });
    $('#psrquestion63 input[type="radio"]').each(concernTriggers);
    $('#psrquestion63 input[type="radio"]').click(concernTriggers);
    $('.radio-watch').each(screeningTriggers);
    $('.radio-watch').click(screeningTriggers);
    /*************************SURVEY PARTS*****************************/
    $('#questionpanel #demographic-questions, #questionpanel #screening-sections, #questionpanel .screen-section:not(:first), #screening-sections + #buttonarea, '+
    '#demographic-questions + #buttonarea, #questionpanel #scan-questions + #psr-questions, #questionpanel #scan-questions + #psr-questions + #buttonarea').hide();
    $('#questionpanel .section-next a').click(nextPage);
    $('#questionpanel .section-prev a').click(prevPage);
    
    $('#scan-questions .radioAnswers :radio, #psr-questions .radio :radio, .screen-section tr :radio, '+
    '#demographic-questions .dquestion select, #demographic-questions .dquestion input').change(checkProgress);
    
    //warning for survey exit
    if ($('#questionpanel').length && !$('#ispreview').length){
    	survey_complete = false;
    	$(window).bind('beforeunload', surveyUnload);
    }
    /*************************LIGHT BOXING*****************************/
    $('a[href $= ".jpg"]').click(lightBoxing);
	
});

//put in a 'wbox'
function wbox(){	
	var wbox_top = '<div class="wbox-TL"><div class="wbox-TR"><div class="wbox-T"><!--stuff--></div></div></div>';	
	var wbox_wrap = '<div class="wbox-L"><div class="wbox-R"><div class="wbox-M"></div></div></div>';
	var wbox_bottom = '<div class="wbox-BL"><div class="wbox-BR"><div class="wbox-B"><!--stuff--></div></div></div>';
	
	$('.wbox').wrapInner(wbox_wrap).prepend(wbox_top).append(wbox_bottom);	
}
//put in a 'inner-box'
function innerBox(){	
	var wbox_top = '<div class="inb-TL"><div class="inb-TR"><div class="inb-T"><!--stuff--></div></div></div>';	
	var wbox_wrap = '<div class="inb-L"><div class="inb-R"><div class="inb-M"></div></div></div>';
	var wbox_bottom = '<div class="inb-BL"><div class="inb-BR"><div class="inb-B"><!--stuff--></div></div></div>';
	
	$('.inner-box').wrapInner(wbox_wrap).prepend(wbox_top).append(wbox_bottom);	
}
//put in a 'dashbox'
function dashBox(){	
	var wbox_top = '<div class="dashb-TL"><div class="dashb-TR"><div class="dashb-T"><!--stuff--></div></div></div>';	
	var wbox_wrap = '<div class="dashb-L"><div class="dashb-R"><div class="dashb-M"></div></div></div>';
	var wbox_bottom = '<div class="dashb-BL"><div class="dashb-BR"><div class="dashb-B"><!--stuff--></div></div></div>';
	
	$('.dashb').wrapInner(wbox_wrap).prepend(wbox_top).append(wbox_bottom);	
}
//wrap result panel
function resultBox(){
	var wbox_wrap = '<div class="inb-L"><div class="inb-R"><div class="inb-M"></div></div></div>';
	var wbox_bottom = '<div class="inb-BL"><div class="inb-BR"><div class="inb-B"><!--stuff--></div></div></div>';
	
	$('.resultpanel #dashtabs').nextAll().wrapInner(wbox_wrap).append(wbox_bottom);
}
//round a box that has just top/bottom/middle classes rather than 9 part classes
function topBottomBoxId(element, classname){	
	var top = '<div id="'+classname+'-T"><!--stuff--></div>';
	var bottom = '<div id="'+classname+'-B"><!--stuff--></div>';
	var middle = '<div id="'+classname+'-M"></div>';
	$(element).wrapInner(middle).prepend(top).append(bottom);
}
//round a box that has just top/bottom/middle classes rather than 9 part classes
function topBottomBoxClass(element, classname){
	var top = '<div class="'+classname+'-T"><!--stuff--></div>';
	var bottom = '<div class="'+classname+'-B"><!--stuff--></div>';
	var middle = '<div class="'+classname+'-M"></div>';
	$(element).wrapInner(middle).prepend(top).append(bottom);
}
//round a box that has just left/right/middle classes rather than 9 part classes
function leftRightBoxId(element, classname){	
	var left = '<div id="'+classname+'-L"><div id="'+classname+'-R"><div id="'+classname+'-M">';
	var right = '</div></div></div>';
	$(element).wrapInner(left + right);	
}
//round a box that has just left/right/middle classes rather than 9 part classes
function leftRightBoxClass(element, classname){
	var left = '<div class="'+classname+'-L"><div class="'+classname+'-R"><div class="'+classname+'-M">';
	var right = '</div></div></div>';

	$(element).wrapInner(left + right);	
}
//watch dialog
function dialogWatch(){
	$('.dialog').dialog({
		modal:true,
		autoOpen:false,
		width:400,
		buttons:[]
	});
	$('#cancel-button, #missing .btn, #reportchecker .btn, .cancel, .cancel-button, .ok-close').click(function(){
		$('.dialog').dialog('close');
		return false;
	});
}
/*Checks url*/
function checkUrlPath(path){
	var pathstring = path;
	if(location.href.indexOf('/GM') != -1){
		pathstring = '/GM' + pathstring;
	}
	return pathstring;
}
//For the Signup form toggle the appearance of the othersizepanel
function toggleOtherSize(checkbox){
	var id = '#'+checkbox.id;
	var checked = $(id).is(':checked');
	if(checked){
		$('#othersizepanel').slideUp(500);
	}else{
		$('#othersizepanel').slideDown(500);
	}
}
//validate Signup form
function validateSignup(){	
	//reset everything
	var noerrors = true;
	var messages; 
	if (lang == 'fre'){
		message = {
			required:'Requis',
			password:'Les mots de passe ne correspondent pas!',
			number:'Doit &ecirc;tre un nombre!', 
			email:'Adresse de courriel invalide!', 
			above:'Requis si diff&eacute;rent de ci-dessus!'
		};
	}else{
		message = {
			required:'Required',
			password:'Passwords don\'t Match!',
			number:'Must be a Number!', 
			email:'Not a valid email!', 
			above:'Required if not same as above!'
		};
	}
	$('.validator').remove();
	$('.req, .match, .integer, .email-input, .check-req').removeClass('errorField');
	//check required fields
	$('.req').each(function(){
		if ($(this).val() == ''){
			$(this).addClass('errorField').after('<span class="validator">*'+message.required+'</span>');
			noerrors = false;
		}
	});
	//check passwords match
	if ($('.match:eq(0)').val() != $('.match:eq(1)').val()){
		$('.match').addClass('errorField');
		$('#passwordsMatch').html('<span class="validator">*'+message.password+'</span>');
		noerrors = false;
	}
	//check radiobutton list
	$('.dash-rlist').each(function(){
		if ($(this).find('input:checked').length == 0){
			$(this).append('<span class="validator">*'+message.required+'</span>');
			noerrors = false;
		}
	});
	//integer test
	var digitonly = /^\d+$/;
	$('.integer').each(function(){
		if (!digitonly.test($(this).val()) && $(this).val() != ''){
			$(this).addClass('errorField').after('<span class="validator">*'+message.number+'</span>');
			noerrors = false;
		}
	});
	//email test
	$('.email-input').each(function(){
		if (!validateEmail($(this).val()) && $(this).val() != ''){
			$(this).addClass('errorField').after('<span class="validator">*'+message.email+'</span>');
			noerrors = false;
		}
	});
	//if checked 'same as above' then required
	$('.check-req').each(function(){
		var checked = $(this).parents('.misc-formField').find('input[type="checkbox"]').is(':checked');
		
		if (!checked && $('#DemographicEmpNum').val() != '' && $(this).val() == ''){
			$(this).addClass('errorField').after('<span class="validator">*'+message.above+'</span>');
			noerrors = false;
		}
	});
	
	return noerrors;
}
//validates an email using unicode characters
function validateEmail(email){
	var emailreg = /^((([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/; 
	if (!emailreg.exec(email))
		return false;
	else
		return true;
}
//Validate a PSR
function validateSubmit(){
	//remove error markers
	removeErrorMarks(null);	
	
	var missing = new Array();
	var surveyresults;
	
	surveyresults = validateSurvey('#scan-questions .question1, #scan-questions .question2', '.questionlabel', missing);
	missing = surveyresults.missing;
	
	surveyresults = validateSurvey('#psr-questions .question1, #psr-questions .question2', '.questionlabel', missing);
	missing = surveyresults.missing;

	//validate demographic questions
	var demoresults = validateDemographics(missing);
	missing = demoresults.missing;	
	
	//validate screening questions	
	$('.screen-section').each(function(n){
		var screeningresults = validateScreening((n+1), missing);
		missing = screeningresults.missing;
	});	
	
	//alert(output);	
	if(missing.length == 0){
		survey_complete = true;
		return true;
	}else{
		if ($('.screen-section').length > 0){
			outputMissing(missing, true);
		}else{
			outputMissing(missing, false);
		}
		$(window).bind('beforeunload',surveyUnload);
		return false;
	}
}
function removeErrorMarks(section){
	if (section == null){
		section = '';
	}else{
		section = section+' ';
	}
	$(section+'.error2').removeClass('error2');
	$(section+'.error').remove();	
}
//validates a survey
function validateSurvey(surveySearch, questionclass, missing){
	var group, question;
	var n=0;
	var pass = true;
	
	var psrgroups = new Array();
	
	for (var i=0; i<13; i++){
		psrgroups[i] = new Array();
	}	
	$(surveySearch).each(function(){		
		//questions 1 to 60 are of the 12 PSR's, 61 to 64 are the areas of concerns
		if(n<60){
			group = n%12 + 1;
			question = parseInt(n/12,10) + 1;			
		}else{
			group = 13;
			question = n-60;			
		}
		if ($(this).find('input:checked').length > 0){
			psrgroups[group-1].push($(this).find('input:checked').val());
		}else{
			//psrgroups[group-
			if (n!=63 || ($('#psrquestion'+n+' input:checked').val() == '1' && n == 63)){ //if it's not concern 3a or if concern 3 is 1
				if (n < 60){
					missing.push($(this).attr('id').replace(/psrquestion|scanquestion/,''));
				}else if (n == 63){
					missing.push('c3a');
				}else{
					missing.push('c'+(parseInt($(this).attr('id').replace('psrquestion',''),10)-60));
				}
				pass = false;
				$(this).find(questionclass).addClass('error2').prepend('<span class="error">*</span>');
			}
		}		
		n++;
	});	
	var results = {
		missing:missing,
		psrgroups:psrgroups,
		pass:pass
	};
	return results;
}
//validates demographic questions
function validateDemographics(missing){
	var pass = true;
	var message = (lang == 'fre' ? 'Choisissez une r&eacute;ponse svp':'Please Select an Answer');
	var errormessage = '<span class="error">*'+message+'</span>';
	$('.dquestion').each(function(){
		
		$(this).find('select').each(function(){
			if ($(this).val() == ''){
				$(this).after(errormessage);
				pass = false;
				missing.push($(this).attr('id').replace('demographic_question',''));
			}
		});
		if ($(this).hasClass('multiple') && $(this).find('input:checked').length == 0){
			$(this).append(errormessage);
			pass = false;
			missing.push($(this).find('label').attr('for').replace('demographic_question',''));
		}
	});
	var results = {
		missing:missing,
		pass:pass
	};
	return results;
}
//validates a screening sections
function validateScreening(secnum, missing){
	var s=0;
	var pass = true;

	$('#sectionpage'+secnum).find('tbody tr').each(function(){
		s++;
		//miss += o+($(this).parents('.section-hidden').length == 0 ? 'vis':'hid')+', ';
		if ($(this).find('input:checked').length == 0 && $(this).parents('.section-hidden').length == 0){
			var questiontext = $(this).find('th span').text();
			questiontext = questiontext.substring(0,100);			
			questiontext = (questiontext.length < 100 ? questiontext:questiontext.substring(0,questiontext.lastIndexOf(' ')));
			missing.push(questiontext);	
			pass = false;
			$(this).find('th span').addClass('error2').prepend('<b class="error">*</b>');
		}
	});
	var results = {
		missing:missing,
		pass:pass
	};
	return results;
}
//next page being clicked
function nextPage(){	
	var title = $(this).attr('title');
	var missing = new Array();

	var ispreview = $('#ispreview').val();
	
	if (title == 'demographics'){
		var search, panel, survey, lastscreening = false, pagenumber;
		
		if ($(this).parents('#psr-questions').length > 0){
			search = '#psr-questions .question1, #psr-questions .question2';			
			panel = '#questionpanel #psr-questions';
			removeErrorMarks(panel);
			survey = validateSurvey(search,'span',missing);
		}else if ($(this).parents('#scan-questions').length > 0){
			search = '#scan-questions .question1, #scan-questions .question2';			
			panel = '#questionpanel #scan-questions';
			removeErrorMarks(panel);
			survey = validateSurvey(search,'span',missing);
		}else{
			var screenid = $(this).parents('.screen-section').attr('id');			
			var pagenum = Number(screenid.replace('sectionpage',''));
			
			lastscreening = true;
			removeErrorMarks('#'+screenid);
			survey = validateScreening(pagenum, missing);
		}
		
		if (survey.pass || ispreview){
			if (lastscreening){
				$('#screening-sections').hide();
			}else{				
				$(this).parents(panel).hide();
				$('#survey-instructions').hide();
			}			
			$('#demographic-questions').show();
			$('#buttonarea').show();

			surveyScrollOffset();
		}else{
			outputMissing(missing,lastscreening);
		}
	}else if (title == 'screening'){
		var search, panel, result, pagenumber;
		if ($(this).parents('#psr-questions').length){
			search = '#psr-questions .question1, #psr-questions .question2';
			panel = '#questionpanel #psr-questions';
			removeErrorMarks(panel);
			result = validateSurvey(search,'span',missing);
		}else if ($(this).parents('#scan-questions').length){
			search = '#scan-questions .question1, #scan-questions .question2';
			panel = '#questionpanel #scan-questions';
			removeErrorMarks(panel);
			result = validateSurvey(search,'span',missing);
		}
		if (result.pass || ispreview){		
			$('#screening-sections').show();
			$(this).parents(panel).hide();
			$('#survey-instructions').hide();
			if ($('#screening-sections .section-next').length == 0){
				$('#buttonarea').show();
			}
			surveyScrollOffset();
		}else{
			outputMissing(missing,false);
		}
	}else if (title == 'PSR-12'){
		search = '#scan-questions .question1, #scan-questions .question2';
		panel = '#questionpanel #scan-questions';
		removeErrorMarks(panel);
		var survey = validateSurvey(search,'span',missing);
		
		if (survey.pass || ispreview){
			$('#psr-questions').show();
			$(this).parents(panel).hide();
			$('#survey-instructions').hide();
			
			if ($('#psrpagenum').val() == $('#totalpages').val()){
				$('#buttonarea').show();
			}

			surveyScrollOffset();
		}else{
			outputMissing(missing,false);
		}
	}else{
		var pagenum = parseInt(title.replace('page ',''),10);
		
		removeErrorMarks('#sectionpage'+(pagenum-1));
		var result = validateScreening((pagenum-1), missing);
		if (result.pass || ispreview){
			$('#sectionpage'+pagenum).show();
			$('#sectionpage'+(pagenum-1)).hide();
			if ($('#sectionpage'+pagenum+' .section-next').length == 0){
				$('#buttonarea').show();
			}
			surveyScrollOffset();
		}else{
			outputMissing(missing,true);
		}
	}
	checkProgress();
	return false;
}
//prev page being clicked
function prevPage(){
	var ispreview = $('#ispreview').val();
	
	if (ispreview){
		removeErrorMarks(null);	
	}
	var title = $(this).attr('title');
	$('#buttonarea').hide();
	if (title == 'PSR-12'){
		$(this).parents('#questionpanel #demographic-questions, #questionpanel #screening-sections').hide();
		$('#psr-questions').show();
	}else if (title == 'Initial Scan'){
		$(this).parents('#questionpanel #demographic-questions, #questionpanel #screening-sections, #questionpanel #psr-questions').hide();
		$('#scan-questions').show();
	}else if (title == 'demographics'){
		$(this).parents('#questionpanel #screening-sections').hide();
		$('#demographic-questions').show();
	}else{
		var pagenum;
		if ($(this).parents('#demographic-questions').length > 0){
			$('#demographic-questions').hide();
			$('#screening-sections').show();
			pagenum = $('.screen-section:last').attr('id').replace('sectionpage','');
		}else{
			pagenum = parseInt(title.replace('page ',''),10);		
			$('#sectionpage'+pagenum).show();
			$('#sectionpage'+(pagenum+1)).hide();
		}
	}	
	surveyScrollOffset();
	checkProgress();
	return false;
}
function outputMissing(missing,paragraphs){
	if (paragraphs){
		$('#missing-questions').html('<p>'+missing.join('...</p><p>')+'...</p>');
	}else{
		$('#missing-questions').html(missing.join(', '));
	}
	$('#missing').dialog('open');
}
function surveyUnload(){
	var message = (lang == 'fre' ? "Cette enqu\u00eate n\u2019est pas encore termin\u00e9e.":"This survey is not complete yet.");
	if (!survey_complete){
		return message;
	}
}
//fill in PSR
var opensection;
function testPSR(search){
	var range, rand;
	$(search).each(function(){
		range = $(this).find('input[type="radio"]').length;
		if ($(this).find('input[type="radio"]').hasClass('radio-watch')){
			rand = Math.floor(Math.random()*range);
			opensection = null;
			$(this).find('input[type="radio"]:eq('+rand+')').attr('checked','checked');
			$(this).find('input[type="radio"]:eq('+rand+')').each(screeningTriggers);
			if (opensection != null){
				testPSR('#'+opensection+' tr');
			}
		}else if ($(this).attr('id') == 'psrquestion63'){
			rand = Math.floor(Math.random()*range);
			opensection = null;
			$(this).find('input[type="radio"]:eq('+rand+')').attr('checked','checked');
			$(this).find('input[type="radio"]:eq('+rand+')').each(concernTriggers);
			if (opensection != null){
				testPSR('#'+opensection+' .radio');
			}
		}else if ($(this).parents('.section-hidden').length == 0){
			$(this).find('input[type="radio"]:eq('+Math.floor(Math.random()*range)+')').attr('checked','checked');
		}
	});
	$('select').each(function(){		
		range = $(this).find('option[value!=""]').length;
		rand = Math.floor(Math.random()*range);
		if ($(this).find('option[value=""]').length > 0) rand++;
		$(this).find('option:eq('+rand+')').attr('selected','selected');
	});
	$('.multiple').each(function(){
		$(this).find('input[type="checkbox"]').removeAttr('checked');
		var number = Math.floor(Math.random()*4)+1; //random number to select
		range = $(this).find('input[type="checkbox"]').length;
		var n=0;
		while (n < number){
			rand = Math.floor(Math.random()*range);
			var randpick = 'input[type="checkbox"]:eq('+rand+')';
			if (!$(randpick).is(':checked')){
				$(randpick).attr('checked','checked');
				n++;
			}
		}
	});
	//remove hidden radio select
	$('.section-hidden input[type="radio"]').each(function(){
		$(this).removeAttr('checked');
	});
	return false;
}
//triggers from PSR-12 question 63
function concernTriggers(){
	//add/remove class used instead of hide/show for validation purposes	
	if ($(this).parent().parent().find('#psrtrigger').length > 0 && $(this).is(':checked')){
		
		var instruct = $.parseJSON($(this).parent().parent().find('#psrtrigger').val());
		var n=0;
		var ch = $(this).val();

		//find checked value in relation to json object
		while(n < instruct.choices.length && instruct.choices[n].id != ch){    			
			n++;
		}		
		if (instruct.choices[n].action == 'show'){
			$('#psrquestion64').removeClass('section-hidden');
			opensection = 'psrquestion64';
		}else{
			//hide trigger
			$('#psrquestion64').addClass('section-hidden').find('input[type="radio"]').removeAttr('checked'); //reset radios being hidden			
		}
		checkProgress();
	}
}
//triggers from the screening
function screeningTriggers(){
	//add/remove class used instead of hide/show for validation purposes	
	if ($(this).parent().parent().find('th input[type="hidden"]').length > 0 && $(this).is(':checked')){
		
		var instruct = $.parseJSON($(this).parent().parent().find('th input[type="hidden"]').val());
		var n=0;
		var ch = $(this).val();
		
		//find checked value in relation to json object
		while(n < instruct.choices.length && instruct.choices[n].id != ch){    			
			n++;
		}		
		//show trigger		
		if (instruct.choices[n].show != null){
			$('#'+instruct.choices[n].show).removeClass('section-hidden');
			opensection = instruct.choices[n].show;
		}
		//hide trigger
		var hide = instruct.choices[n].hide;
		if (hide != null){
			$('#'+hide).addClass('section-hidden').find('input[type="radio"]').removeAttr('checked'); //reset radios being hidden
		}			
		//hide combine: requires all related radios checked to hide 
		var hidecombine = instruct.choices[n].hidecombine;
		if (hidecombine != null){			
			var hcombo = true;
			var c=0;
			while(c < hidecombine.id.length && hcombo){    				
				hcombo = ($('.screen-section input[value="'+hidecombine.id[c]+'"]').is(':checked'));    				
				c++;
			}
			if (hcombo){
				$('#' + hidecombine.div).addClass('section-hidden').find('input[type="radio"]').removeAttr('checked');
			}
		}
		//hide any: requires at least one of the radios checked to hide
		var hideany = instruct.choices[n].hideany;
		if (hideany != null){
			var hcombo = false;
			var c=0;
			while(c < hideany.id.length){    				
				hcombo = ($('.screen-section input[value="'+hideany.id[c]+'"]').is(':checked'));
				if (hcombo) break;
				c++;
			}
			if (hcombo){
				$('#' + hideany.div).addClass('section-hidden').find('input[type="radio"]').removeAttr('checked');
			}
		}
		checkProgress();
	}
}
/*light box a full-size image*/
function lightBoxing(){
	var alt = $(this).children('img').attr('alt');
	var fullpic = $(this).attr('href');
	var fullsize = 
		'<div id="full-size"><div id="full-pic-holder">'
			+'<div id="full-pic-top"><a id="close-pic">Close</a></div>'
			+'<img src="'+fullpic+'" alt="'+alt+'" />'
		+'</div></div>';
	$('body').append(fullsize);
	$('#close-pic').click(function(){
    	$('#full-size').remove();
    });
	positionFullsize();
	return false;
}
/*Vertically positions a full-size image*/
function positionFullsize(){
	var offset = $(window).scrollTop();
	var docheight = $(document).height();
	$('#full-size').css('height',docheight+'px');
	var winheight = $(window).height();
	var img = '#full-size img';
	var top = '#full-pic-top';
	var holder = '#full-pic-holder';
	var picheight;
	$(img).load(function(){
		var picheight = $(this).height();
		var pictop = $(top).outerHeight();
		var padtop = parseInt($(holder).css('padding-top'),10);
		var padbottom = parseInt($(holder).css('padding-bottom'),10);
		var pos;
		var picbottom = offset + picheight + pictop + padtop + padbottom;		

		if (picbottom<=docheight){
			pos = winheight/2 - picheight/2 + offset;
		}else{
			pos = docheight - picheight - pictop - padtop - padbottom;		
		}
		$(holder).css({'margin-top':pos+'px'});		
	});	
}
/*Checks total progress through survey*/
function checkProgress(){
	var totalquest = $('#scan-questions .radioAnswers, #psr-questions div:not(.section-hidden) .radio, .screen-section table:not(.section-hidden) tbody tr, '+
		'#demographic-questions .dquestion').length;
	var answered = $('#scan-questions .radioAnswers :checked, #psr-questions .radio :checked, .screen-section table:not(.section-hidden) tr :checked, '+
		'#demographic-questions .dquestion select[value!=""], #demographic-questions .dquestion:has(input:checkbox:checked)').length;
	$('#survey-progress-bar').progressbar('option','value',answered/totalquest*100);
}
/*Adjust the offset of scrolling to*/
function surveyScrollOffset(){
	var progtitle;
	if ($('h4 + #survey-progress-bar').length){
		progtitle = $('#survey-progress-bar').prev('h4').offset().top;
	}else{
		progtitle = $('#survey-progress-bar').offset().top;
	}
	$('html, body').animate({scrollTop:progtitle});
}