var pageCount=2;
var ascending = true;
function smallprofile_init(count, asc)
{
	pageCount =count;
	acsending = asc;
}
function isValidForm1()
{
	var f = document.forms["fsignin"];	


	if(!pageCheck(f,63)) return false;
	
	turnPage(f,2);	

	return false;
}
function getGoal(f)
{
    //0 not set 1 = lose  2= maintain
    var isarray;
    try
    {
        isarray = f.optgoal.length;
    }
    catch(err) {}
    if(typeof(isarray)=="undefined") isarray=0;
    if(isarray==0)
    {
        return f.optgoal.value;
    }
    else
    {
        if (!(f.optgoal[0].checked || f.optgoal[1].checked))
        {
            return 0;
        }
        if(f.optgoal[0].checked) return 1;
        if(f.optgoal[1].checked) return 2;
    }
    return 0;

}
function pageCheck(f,flag)
{
	if((flag & 1) ==1)
		if(!checkAge(f)) return false;	
	if((flag & 2) ==2)
		if(!checkSex(f)) return false;		
	if((flag & 4) ==4)
    	if(!checkHtWt(f)) return false;		
	if((flag & 8) ==8)
		if(!checkGoal(f)) return false;
	if((flag & 16) ==16)
		if(!checkWeekly(f)) return false;
	if((flag & 32) ==32)
		if(!checkTarget(f)) return false;
	if((flag & 64) == 64)
		if(!checkEthnic(f)) return false;
	if((flag & 128) == 128)
		if(!checkCheck(f)) return false;

	return true;
	
}
function isValidFormP1(flag)
{
	var f = document.forms["fsignin"];	


	if(!pageCheck(f,flag)) return false;

	turnPage(f,2);

	return false;
}
function isValidFormP2(flag)
{
	var f = document.forms["fsignin"];	

	if(!pageCheck(f,flag)) return false;

	if(pageCount>2)
	{
		turnPage(f,3);	
		return false;
	}
	else
		return true;
}
function isValidFormP3(flag)
{
	var f = document.forms["fsignin"];	

	if(!pageCheck(f,flag)) return false;

	if(pageCount>2)
		turnPage(f,3);	
	else
		return true;
}
function turnPage(f,page)
{
	var obj = document.getElementById('page_' + (page -1));
	if(obj) obj.style.display = 'none';
	obj = 	document.getElementById('page_' + page)
	if(obj) obj.style.display = 'block';
	
	if(f.optsex)
	{
		if(f.optsex[1].checked)
		{
			obj = 	document.getElementById('page_2a')
			if(obj) obj.style.display = 'none';
	
		}
	}
}
function isValidForm1a()
{

	var height, weight;
	var f = document.forms["fsignin"];	
	
	if(!pageCheck(f,39)) return false;

	document.getElementById('page_1').style.display = 'none';
	document.getElementById('page_2').style.display = 'block';
	//document.getElementById('part1').style.visibility = 'hidden';
	//document.getElementById('part2').style.visibility = 'visible';
	return false;
}


function isValidForm1b()
{
	var f = document.forms["fsignin"];

	if(!pageCheck(f,48)) return false;

	turnPage(f);

	document.getElementById('page_1').style.visibility = 'hidden';
	document.getElementById('part1').style.visibility = 'hidden';
	document.getElementById('part2').style.visibility = 'hidden';
	document.getElementById('page_2').style.visibility = 'visible';
	return false;
}


function isValidForm2()
{
	var f = document.forms["fsignin"];	

	if(f.txt_location){
		if (f.txt_location.options[f.txt_location.selectedIndex].value == ''){
            alert('Please state your main work location');
            return false;			
		}	
	}

	if(f.ethnic1){
		if (f.ethnic1.options[f.ethnic1.selectedIndex].value == ''){
            alert('Please state your ethinc origin');
            return false;			
		}
	}
	
		if(f.chkbreast.checked)
        {
                alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
                return false;
        }
        if(f.chkpregnant.checked)
        {
                alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
                return false;
        }
        

        if(f.eatingdisorder.checked)
        {
                alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
                return false;
        }
		return true;
}
function checkTarget(f){
	if(f.cmbtarget.length==1)
	{
		alert("Our system has been unable to calculate a target weight. This is usually due to you entering an incorrect weight/height or to your Body Mass Index being lower than the acceptable level for further weight loss to be recommended, hence why registration with our service is prevented. If you have an issue with your weight, please consult your doctor. ");
		return false;
	}
	if(f.cmbtarget.selectedIndex<=0)
	{
		alert('Please enter a target weight');
		return false;
	}
	var bmi,targetweight,targetbmi;
	targetweight = f.cmbtarget.value;
	if(!isMetric(f))
	{
		bmi = (weight * 703 * 10 / height/ height) / 10;	
		targetbmi = (targetweight * 703 * 10 / height/ height) / 10;	
	}
	else
	{
		bmi = (weight * 10) / (height * height);
		targetbmi = (targetweight * 10) / (height * height);
	}

	if(bmi<=18.5 || targetbmi<=18.5)
	{
		alert("Our system has calculated that your Body Mass Index is lower than the acceptable level for further weight loss to be recommended, hence why registration with our service is prevented. If you have an issue with your weight, please consult your doctor.");
		return false;
	}
	return true;
}
function checkGoal(f){
	if(getGoal(f)==0)
         {
            alert('Please enter your goal!'); 
         }
         
	return true;
}
function checkCheck(f)
{
	if(f.chkbreast)
	{
		if(f.chkbreast.checked)
		{
				alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
				return false;
		}
	}
	if(f.chkpregnant)
	{
        if(f.chkpregnant.checked)
        {
                alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
                return false;
        }
	}
	if(f.eatingdisorder)
	{
        if(f.eatingdisorder.checked)
        {
                alert('You are advised to consult your GP before starting any weight loss and/or exercise programme, therefore our system cannot allow you to continue with the registration process at this time.');
                return false;
        }
	}
	return true;
}
function checkEthnic(f)
{
	if(f.ethnic1){
		if (f.ethnic1.options[f.ethnic1.selectedIndex].value == ''){
            alert('Please state your ethnic origin');
            return false;			
		}
	}
	return true;
}
function checkWeekly(f){
	var maintain = false;
	if(getGoal(f)==2) maintain = true;
	
	if(!maintain)
	{
		if (!(f.C1[0].checked || f.C1[1].checked || f.C1[2].checked || f.C1[3].checked))
		{
				alert('Please enter your weekly weight loss!');
				return false;
		}
	}
	return true;
}


function checkAge(f){
	if (f.txtage.value=='')
	{
		alert('Please enter your age.');
		return false;
	}
	if(parseInt(f.txtage.value)<18)
	{
		alert('you must be over 18.');
		return false;
	}
	return true;
}
function checkSex(f){
	if(f.optsex[0]){
		if (!(f.optsex[0].checked || f.optsex[1].checked))
		{ 
			alert('Please enter your sex');
			return false;
		}
	}
	return true;
}
function isMetric(f)
{

	var obj =f.ismetric; 
	if (obj!=null)
	{
		if(obj.value=="1")
			return true;
		else
			return false;
	}
	alert("not found");
	return false;
}


function loadTargetWeight()
{
	var f;
	var minTarget;
	var maxTarget;
    var numItems = 0; 
	var selectednum=-1;
	var weight, percentage;
	
	f = document.forms["fsignin"]
	listClear(f.cmbtarget) 

	if(!isDataOK(f)) 
	{
		addOption = new Option("Select Goal Weight" ,"Select Goal Weight" );
	    f.cmbtarget.options[numItems++] = addOption; 
		return;
	}

	minTarget=parseInt(minWeight(getHeight(f),isMetric(f)));
	
	maxTarget=parseInt(maxWeight(getHeight(f),isMetric(f)));
	
	
    addOption = new Option("Select Goal Weight" ,"Select Goal Weight" );
    f.cmbtarget.options[numItems++] = addOption; 
	
	if(minTarget==0||maxTarget==0) return;
	var i,kg,g;
	weight = getWeight(f);

	if(isMetric(f))
	{
		minTarget = minTarget * 1000;
		maxTarget = maxTarget * 1000;
		if((weight - weight/5)>minTarget)
		{
			minTarget = weight - weight/5;
			maxTarget = weight;
		}
		if((weight)<maxTarget)
			maxTarget = weight 

		if(ascending)
		{
			for (i = maxTarget; i >= minTarget; i=i-200){
				percentage = -Math.floor((weight-i) * 100 /weight);
				kg = i/1000;
				addOption = new Option(kg + ' Kg   (' + percentage + '% loss)',i );
				f.cmbtarget.options[numItems++] = addOption; 
				if(i==tweightg)
					selectednum = numItems-1
			}
		}
		else
		{
			for (i = minTarget; i <= maxTarget; i=i+200){
				percentage = -Math.floor((weight-i) * 100 /weight);
				kg = i/1000;
				addOption = new Option(kg + ' Kg   (' + percentage + '% loss)',i );
				f.cmbtarget.options[numItems++] = addOption; 
				if(i==tweightg)
					selectednum = numItems-1
			}
		}
		i--
	}
	else
	{		
		//minTarget = Convert_kg_lbs(minTarget);
		//maxTarget = Convert_kg_lbs(maxTarget);

		if((weight - weight/5)>minTarget)
		{
			minTarget = weight - weight/5;
			maxTarget = weight;
		}
		if((weight)<maxTarget)
			maxTarget = weight 
		minTarget = Math.floor(minTarget)
		maxTarget = Math.floor(maxTarget)
		
		if(ascending)
		{
			for (i = maxTarget; i >= minTarget; i--){
				percentage = Math.floor((weight - i) * 100 /weight );
				addOption = new Option(Math.floor(i/14) + 'st ' + (i % 14) + 'lbs   (' + percentage + '% loss)',i );
				f.cmbtarget.options[numItems++] = addOption; 
	
				if(i==tweightlbs)
					selectednum = numItems-1
			}	
		}
		else
		{
			for (i = minTarget; i <= maxTarget; i++){
				percentage = Math.floor((weight - i) * 100 /weight );
				addOption = new Option(Math.floor(i/14) + 'st ' + (i % 14) + 'lbs   (' + percentage + '% loss)',i );
				f.cmbtarget.options[numItems++] = addOption; 
	
				if(i==tweightlbs)
					selectednum = numItems-1
			}
		}
		i--;

	}
	f.min_weight.value=minTarget;
	f.max_weight.value=i;
	if(selectednum==-1) selectednum=0;
	f.cmbtarget.selectedIndex= selectednum;	
	
}
function listClear(cmb)
{
	for (var i = cmb.options.length - 1; i >= 0; i--){
    cmb.options[i] = null;
  	}
	cmb.selectedIndex = -1;

}


function minWeight(height, metric)
{
	/*height should be eith in inchs or cm */
	
	if(metric)
		return parseInt((18.5 * height * height /10000) + 0.99) /*1 added to protect rounding*/
	else
		return parseInt(((18.5 * Convert_in_cm(height) * Convert_in_cm(height) /10000 ) / 0.4536) + 0.99)
}
function maxWeight(height, metric)
{
	/*height should be eith in inchs or cm */
	if(metric)
		return parseInt(24.99 * height * height /10000)
	else
		return parseInt(24.99 * Convert_in_cm(height) * Convert_in_cm(height) /10000 / 0.4536)
}
function Convert_lbs_kg(lbs)
{
	return parseInt(lbs * 0.4536);
}
function Convert_kg_lbs(kg)
{
	return parseInt(kg / 0.4536);
}

function Convert_in_cm(inchs)
{
	return inchs * 2.54;
}
function changeMeasure(resetdata, imperial)
{
	var f;
	f = document.forms["fsignin"];
	
	if (imperial==null)
	{
		
		if(f.ismetric.value=="1")
			imperial=false;
		else
			imperial=true;
	}
	 
	
	nu_changeMeasure(f,imperial);
	if(resetdata)
	{
		if(imperial)
		{
			//imperial to metric 
			var h = parseInt(f.txtheight1.value) * 12 + parseInt(f.txtheight2.value==''?0:f.txtheight2.value);
			var w = parseInt(f.txtweight1.value) * 14 + parseInt(f.txtweight2.value==''?0:f.txtweight2.value);

			if(isNaN(h)) h=0;
			if(isNaN(w)) w=0;

			var mh1, mh2;
			h = h * 2.54;
			h = h +.5;
	
			mh1 = h / 100;
			mh2 = h % 100;
	
			w = w * 0.45359237;
			
			f.txtweight1.value=w;
			f.txtweight2.value="";		
			f.txtheight1.value=parseInt(mh1);
			f.txtheight2.value=parseInt(mh2);
		}
		
		else{
			//metric to imperial
			var h = parseInt(f.txtheight1.value) * 100 + parseInt(f.txtheight2.value);
			var w = f.txtweight1.value * 2.204622622 + .5;
			var ih1, ih2, iw1, iw2;

			if(isNaN(h)) h=0;
			if(isNaN(w)) w=0;

			
			h = (h * 0.393700787);
			ih1 = h / 12;
			ih2 = h % 12;
			iw1 = parseInt(w / 14);
			
			iw2 = w - (14 * iw1);
			
			f.txtheight1.value=parseInt(ih1);
			f.txtheight2.value=parseInt(ih2);
			f.txtweight1.value=parseInt(iw1);
			f.txtweight2.value=parseInt(iw2);
	
		}
	}
	loadTargetWeight();
	
}

function changeTarget()
{
	var f;
	var height,weight;
	var ismaintain = false;
	
	f = document.forms["fsignin"]
	if(getGoal(f)==2) ismaintain = true;
	
	if(ismaintain)
	{
		listClear(f.cmbtarget) 
		addOption = new Option("Select Goal Weight" ,"Select Goal Weight" );
		f.cmbtarget.options[0] = addOption;
		weight= getWeight(f);
		if(weight!=0)
		{
			if(isMetric(f))
			{
				addOption = new Option(f.txtweight1.value + 'kg ',weight);
				f.cmbtarget.options[1] = addOption; 
			}
			else
			{
					addOption = new Option(f.txtweight1.value + 'st ' + f.txtweight2.value + 'lbs',weight);
					f.cmbtarget.options[1] = addOption; 
			}
			f.cmbtarget.selectedIndex=1;
		}
		else
			f.cmbtarget.selectedIndex=0;
		if(getGoal(f)==2){
		f.C1[0].disabled=true;
		f.C1[1].disabled=true;
		f.C1[2].disabled=true;
		f.C1[3].disabled=true;
		}
	}
	else
	{
		if(getGoal(f)==1){
		f.C1[0].disabled=false;
		f.C1[1].disabled=false;
		f.C1[2].disabled=false;
		f.C1[3].disabled=false;
		}
		loadTargetWeight()		
	}
}
function getWeight(f)
{
	
	if(isMetric(f))
	{
		if(f.txtweight1.value=='') return 0
		return (parseInt(f.txtweight1.value) * 1000) 
		
	}
	else
	{

		if(f.txtweight1.value=='') return 0
		return (parseInt(f.txtweight1.value) * 14) + parseInt(f.txtweight2.value==''?0:f.txtweight2.value);
	}
}
function getHeight(f)
{
	var h1 = f.txtheight1.value;
	var h2 = f.txtheight2.value;
	if(h1=='') h1="0";
	if(h2=='') h2="0";
		
	if(isMetric(f))
	{
		return (parseInt(h1) * 100) + parseInt(h2);
	}
	else
	{
		return (parseInt(h1) * 12) + parseInt(h2);
	}
}
function isDataOK(f)
{
	height= getHeight(f);
	weight = getWeight(f);
	if(!isMetric(f))
	{
		if(height<51 || height>94) return false;
		if(weight<88 || weight>560) return false;
	}
	else
	{
		if(height<130 || height>240) return false;
		if(weight<40000 || weight>254000) return false;
	}
	return true;
}
function checkHtWt(f){
	height= getHeight(f);
	weight = getWeight(f);
	if(!isMetric(f))
	{
		if((height <51)||(height>94))
		{
			alert("The minimum and maximum heights allowed are 4ft 3in and 7ft 10in. Please make sure you are within these bounds!");
			return false;
		}
		if(weight>560)
		{
			alert("Based on the targets you have entered, it is advisable to consult with your GP before starting a weight loss and/or exercise programme, therefore our system will not allow you to continue registering at this time.");			
			return false;
		}
		if(weight<88)
		{
			alert("The minimum and maximum weights allowed are 6st 4lbs and 40st. Please make sure you are within these bounds!");
			return false;
		}
	}
	else
	{
		if(f.txtheight1.value=="")
		{
			alert("Please re-enter height!");
			return false;
		}
		if((height<130)||(height>240))
		{
			alert("The minimum and maximum heights allowed are 1m 30cm and 2m 40cm. Please make sure you are within these bounds!");
			return false;
		}
		if((weight>254000))
		{
			alert("Based on the targets you have entered, it is advisable to consult with your GP before starting a weight loss and/or exercise programme, therefore our system will not allow you to continue registering at this time.");			
			return false;
		}

		if((weight<40000)||(weight>254000))
		{
			alert("The minimum and maximum weights allowed are 40kg and 254kg. Please make sure you are within these bounds!");
			return false;
		}

	}
	return true;
}
function populateEthnic(egroup, eval)
{
	var group;
	var preselected;
	
	group = document.fsignin.ethnic1.selectedIndex;

	var ethnicdiv=document.getElementById("ethnicdiv");
	var ethnic2=document.getElementById("ethnic2");
	
	if (ethnic2 != null){
		ethnicdiv.removeChild(ethnic2);
	}

	var ESelect = document.createElement("select");
	ESelect.id="ethnic2";
	ESelect.name="ethnic2";

	if(group>-1)
	{
		groupval = document.fsignin.ethnic1.options[group].value;
		group--;

		var eg = new Array(new Array("British","Irish","Any other White background"),new Array("White and Black Caribbean","White and Black African","White and Asian","Any other mixed background"),new Array("Indian","Pakistani","Bangladeshi","Any other Asian background"),new Array("Caribbean","African","Any other Black background"),new Array("Chinese","Any other ethnic group"));

		var egvals = new Array(new Array("11","12","13"),new Array("81","82","83","84"),new Array("51","52","53","54"),new Array("02","03","04"),new Array("06","07"));

	
		for (j=0;j<eg[group].length;j++)
		{
			option = document.createElement("option");
			txtNode = document.createTextNode(eg[group][j]);
			option.value = egvals[group][j];
			
			if(egroup!=null)
			{
				if(egvals[group][j] == egroup)
					preselected = j;
			}

			option.appendChild(txtNode);
			ESelect.appendChild(option);
		}
	
		ethnicdiv.appendChild(ESelect);
		document.fsignin.ethnic2.selectedIndex = 0;
		ethnicdiv.style.display = "block";
	}

}

function selectEthnic(ethnicgroup, ethnicvalue){
	
	var group = 0;
	var preselected = 0;
	var ethnicdiv=document.getElementById("ethnicdiv");
	var ethnic2=document.getElementById("ethnic2");
	
	if (ethnic2 != null){
		ethnicdiv.removeChild(ethnic2);
	}
	
	var ESelect = document.createElement("select");
	ESelect.id="ethnic2";
	ESelect.name="ethnic2";

	if(ethnicgroup!=null){
		group = ethnicgroup;
	}
	else{
		group = document.fsignin.ethnic1.selectedIndex;
		groupval = document.fsignin.ethnic1.options[group].value;
		group--;
		
		if (groupval == '' || groupval == '99'){
			group = 'ns';	
		}
	}
	
	var ethnicvals = new Array("01","08","05","04","07","99");
	
	if(ethnicvalue!=null){
		
		for(v=0;v<ethnicvals.length;v++){
			if (ethnicvals[v] == ethnicvalue){
				group = v;
			}
		}
	}
	
	
	var eg = new Array(new Array("British","Irish","Any other White background"),new Array("White and Black Caribbean","White and Black African","White and Asian","Any other mixed background"),new Array("Indian","Pakistani","Bangladeshi","Any other Asian background"),new Array("Caribbean","African","Any other Black background"),new Array("Chinese","Any other ethnic group"));

	var egvals = new Array(new Array("11","12","13"),new Array("81","82","83","84"),new Array("51","52","53","54"),new Array("02","03","04"),new Array("06","07"));

	
	if(group != 'ns' || group !='')
	{
		for (j=0;j<eg[group].length;j++)
		{
			option = document.createElement("option");
			txtNode = document.createTextNode(eg[group][j]);
			opval = egvals[group][j];	
			option.value = opval;
			
			if(opval == ethnicgroup)
				preselected = j;
			

			option.appendChild(txtNode);
			ESelect.appendChild(option);
		}
	
		ethnicdiv.appendChild(ESelect);
		document.fsignin.ethnic2.selectedIndex = preselected;
		ethnicdiv.style.display = "block";
	}
}