function fraction(decimal,base)
{
 if(!decimal) decimal=0;
 if(!base) base=0;
 whole = String(decimal).split('.')[0];
 decimal = parseFloat("."+String(decimal).split('.')[1]);
 num = "1";
 for(z=0; z<String(decimal).length-2; z++){
  num += "0";
 }
 decimal = parseInt(decimal*num);
 num = parseInt(num);
 for(z=2; z<decimal+1; z++){
  if(decimal%z==0 && num%z==0){
   decimal = decimal/z;
   num = num/z;
   z=2;
  }
 }
 if(isNaN(decimal))
  decimal ='';
 else 
 // get the gcd of the numbers 
 if(base > 0)
	{
  gcd = hcf(Math.round(decimal*base/num),base);
  decimal = Math.round(decimal*base/num)/gcd+" / "+base/gcd;
	}
 else
	{
  gcd = hcf(Math.round(decimal),num);
  decimal = Math.round(decimal/gcd)+" / "+num/gcd;
	}
 return ((whole==0)?"" : whole+" ")+decimal;
}

function hcf(x,y){
 var gcd=1;
 var w;
 while (y != 0) {
 w = x % y;
 x = y;
 y = w;
 }
  return x;
}

function trim(str)
{
 while (str.substring(0,1) == ' ')
  str = str.substring(1, str.length);
 while (str.substring(str.length-1, str.length) == ' ')
  str = str.substring(0,str.length-1);
 return str;
}

function sanitize(str)
{
 res = isFraction(str);
 if(isFraction(str) == 1)
  str = str.replace(/[^a-zA-Z 0-9\/]+/g,'');
 else
  str = str.replace(/[^a-zA-Z 0-9.]+/g,'');
 return str;
}

function get_act_val(str)
{
 if(!isNaN(str))
  return str;
 str = sanitize(str);

 // first trim the starting and trailing spaces.
 str = trim(str);
 // check if this is a valid fraction
 var num,rest,pos;
 if(str.indexOf(" ") > 0) // has a number
 {
  num = trim(str.substring(0,str.indexOf(" ")));
  // check if this is a fractio by any chance
  // eg: " 1/ 16 "
  if(String(num).indexOf("/") > 0) // has a fraction so input is actually a fraction
  {
   rest= str;
   num = 0;
  }
  // one more check for fractions
  // eg: " 1 / 16 "
  else{
  rest = trim(str.substring(str.indexOf(" "),str.length));
   if(rest[0] == '/')
   {
    num =0;
    rest = str;
   }
  }
 }
 else 
 {
  rest = str;
  num =0;
 }
 if(String(rest).indexOf("/") > 0) // has a fraction
 {
  nume = String(rest).split('/')[0];
  deno = String(rest).split('/')[1];
 }
 else
 {
  return num;
 }
 value1 = parseFloat(num) + parseFloat(nume)/parseFloat(deno);
 if(isNaN(value1))
  return parseInt(num);

  return value1;  
}

function isFraction(str)
{
 str = str.replace(/[^a-zA-Z 0-9.\/]+/g,'');
 if(str.indexOf("/") > 0) // has a fraction
  return 1;
 else
  return 0;
}

function store_units()
{
 if(isFraction(document.forms["sample"].height.value) == 1)
  document.forms["sample"].height_form.value = 1;
 else
  document.forms["sample"].height_form.value = 0;

 if(isFraction(document.forms["sample"].width.value) == 1)
  document.forms["sample"].width_form.value = 1;
 else
  document.forms["sample"].width_form.value = 0;
}

function restore_units()
{
 // find the unit
 for (var i=0; i < document.forms["sample"].dim_units.length; i++)
   if (document.forms["sample"].dim_units[i].checked)
       unit = document.forms["sample"].dim_units[i].value;
 if(document.forms["sample"].height_form.value == 1) // convert into fractions
  {
   if(unit=="mms")
   {
    document.forms["sample"].height.value = fraction(get_act_val(Math.round(document.forms["sample"].height.value*100000)/100000));
   }
   else
    document.forms["sample"].height.value = fraction(get_act_val(Math.round(document.forms["sample"].height.value*100000)/100000),64);
  }
 else
   document.forms["sample"].height.value = get_act_val(Math.round(document.forms["sample"].height.value*100000)/100000);

 // restore units for width
 if(document.forms["sample"].width_form.value == 1) // convert into fractions
  {
   if(unit=="mms")
    document.forms["sample"].width.value = fraction(get_act_val(Math.round(document.forms["sample"].width.value*100000)/100000));
   else
    document.forms["sample"].width.value = fraction(get_act_val(Math.round(document.forms["sample"].width.value*100000)/100000),64);
  }
 else
   document.forms["sample"].width.value = get_act_val(Math.round(document.forms["sample"].width.value*100000)/100000);
}

function calculate(format_flag)
{
 unit="mms";
 for (var i=0; i < document.forms["sample"].dim_units.length; i++)
   {
   if (document.forms["sample"].dim_units[i].checked)
      {
       unit = document.forms["sample"].dim_units[i].value;
      }
   }
 if(format_flag != 1)
	store_units();
 for (var i=0; i < document.forms["sample"].matter.length; i++)
   {
   if (document.forms["sample"].matter[i].checked)
      {
       matter1 = document.forms["sample"].matter[i].value;
      }
   }
 // include the mortar dimensions
 mortarheight = get_act_val(sanitize(document.forms["sample"].ht_mortar.value) );
 mortarwidth = get_act_val(sanitize(document.forms["sample"].wd_mortar.value));
//alert("values are " + mortarheight + " and " + mortarwidth);
 matterheight = get_act_val(sanitize(document.getElementById('ht_mat2').innerHTML));
 matterwidth = get_act_val(sanitize(document.getElementById('wd_mat2').innerHTML));
 
  // first sanitise the values
 tot_ht = get_act_val(sanitize(document.forms["sample"].height.value));
 tot_wd = get_act_val(sanitize(document.forms["sample"].width.value));

 document.getElementById('ht_wall').innerHTML = unit;
 document.getElementById('wd_wall').innerHTML = unit;
 document.getElementById('mortar_height_unit').innerHTML = unit;
 document.getElementById('mortar_width_unit').innerHTML = unit;
 // calculate the rows
 nr = ( parseFloat(tot_ht) + parseFloat(mortarheight) )/ ( parseFloat(matterheight) + parseFloat(mortarheight) )
 nc = ( parseFloat(tot_wd) + parseFloat(mortarwidth) )/ ( parseFloat(matterwidth) + parseFloat(mortarwidth) )

 document.getElementById('numrows').innerHTML =Math.round(nr*100)/100; // Math.round(tot_ht/matterheight*100)/100 + 1;
 document.getElementById('numcols').innerHTML =Math.round(nc*100)/100; // Math.round(tot_wd/matterwidth*100)/100 + 1;
/*

 // assuming that the width and height will be more than the width and height of the brick or the matter
 // first sanitise the values
 tot_ht = get_act_val(sanitize(document.forms["sample"].height.value)) - matterheight;
 tot_wd = get_act_val(sanitize(document.forms["sample"].width.value)) - matterwidth;
// alert("values are " + tot_ht + " and " + tot_wd);
// include the mortar width and height
 matterheight = parseFloat(matterheight) + parseFloat(mortarheight);
 matterwidth = parseFloat(matterwidth) + parseFloat(mortarwidth);
// alert("values are " + matterheight + " and " + matterwidth);

 document.getElementById('numrows').innerHTML = Math.round(tot_ht/matterheight*100)/100 + 1;
 document.getElementById('numcols').innerHTML = Math.round(tot_wd/matterwidth*100)/100 + 1;
*/
 // now calculate the new dimensions
 num_rows = Math.floor(nr);
 num_cols = Math.floor(nc);
 document.getElementById('rowno').innerHTML = num_rows;
 document.getElementById('colno').innerHTML = num_cols;
 // now find the dims of the last row.
 lrh = tot_ht - ( parseFloat(num_rows)* (parseFloat(matterheight) + parseFloat(mortarheight)) ) + parseFloat(mortarheight);
 lrw = tot_wd - ( parseFloat(num_cols)* (parseFloat(matterwidth) + parseFloat(mortarwidth)) ) + parseFloat(mortarwidth);
 document.getElementById('adjheight').innerHTML = Math.round((parseFloat(matterheight) + parseFloat(lrh)/parseFloat(num_rows))*100000)/100000;
	 // Math.round((tot_ht+matterheight-(mortarheight*(num_rows-1)))/num_rows*10000)/10000;
 document.getElementById('adjheight2').innerHTML = fraction(get_act_val(Math.round((parseFloat(matterheight) + parseFloat(lrh)/parseFloat(num_rows))*100000)/100000),16);
 document.getElementById('adjwidth2').innerHTML = fraction(get_act_val(Math.round((parseFloat(matterwidth) + parseFloat(lrw)/parseFloat(num_cols))*100000)/100000),16);
	 // Math.round((tot_wd+matterwidth-(mortarwidth*(num_cols-1)))/num_cols*10000)/10000;
 document.getElementById('adjwidth').innerHTML = Math.round((parseFloat(matterwidth) + parseFloat(lrw)/parseFloat(num_cols))*100000)/100000;
 document.getElementById('adj_height_unit').innerHTML = unit;
 document.getElementById('adj_width_unit').innerHTML = unit;
 restore_units();
}

function inches_to_mms(){
 set_base();
 store_units();
 tot_ht = get_act_val(sanitize(document.forms["sample"].height.value));
 document.forms["sample"].height.value =  Math.round(300/12 * parseFloat(tot_ht) *100000)/100000;
 tot_wd = get_act_val(sanitize(document.forms["sample"].width.value));
 document.forms["sample"].width.value =  Math.round(300/12 * parseFloat(tot_wd) *100000)/100000;
 val = get_act_val(sanitize(document.forms["sample"].wd_mortar.value));
 document.forms["sample"].wd_mortar.value = Math.round(300/12 * parseFloat(val) *100000)/100000;
 val = get_act_val(sanitize(document.forms["sample"].ht_mortar.value));
 document.forms["sample"].ht_mortar.value = Math.round(300/12 * parseFloat(val) *100000)/100000;
 calculate(1);
}

function mms_to_inches(){
 set_base();
 store_units();
 // take a back up of the input states decimals or fractions
 tot_ht = get_act_val(sanitize(document.forms["sample"].height.value));
// if(isNaN(tot_ht) || tot_ht == '') tot_ht = 0;
 document.forms["sample"].height.value =  Math.round(12/300 * parseFloat(tot_ht) *100000)/100000;
 tot_wd = get_act_val(sanitize(document.forms["sample"].width.value));
 document.forms["sample"].width.value = Math.round(12/300 * parseFloat(tot_wd) *100000)/100000;
 val = get_act_val(sanitize(document.forms["sample"].wd_mortar.value));
 document.forms["sample"].wd_mortar.value = Math.round(12/300 * parseFloat(val) *100000)/100000;
 val = get_act_val(sanitize(document.forms["sample"].ht_mortar.value));
 document.forms["sample"].ht_mortar.value = Math.round(12/300 * parseFloat(val) *100000)/100000;
 calculate(1);
}

function set_base(){
 // first set the base dimensions
 for (var i=0; i < document.forms["sample"].matter.length; i++)
  if (document.forms["sample"].matter[i].checked)
   material = document.forms["sample"].matter[i].value;

 unit="mms";
 for (var i=0; i < document.forms["sample"].dim_units.length; i++)
  if (document.forms["sample"].dim_units[i].checked)
   unit = document.forms["sample"].dim_units[i].value;

 if(material == 'stone')
 {
  height = 12; //431.8;
  width = 17; //304.8;
 }
 else
 {
  height = 2.25; //57.15;
  width = 8;//203.2;
 }

 if(unit == "mms")
 {
  document.getElementById('ht_mat').innerHTML = fraction(Math.round(height * 300 * 100000 / 12)/100000,64);
  document.getElementById('wd_mat').innerHTML = fraction(Math.round(width * 300 * 100000 / 12)/100000,64);
  document.getElementById('ht_mat2').innerHTML = Math.round(height * 300 * 100000 / 12)/100000;
  document.getElementById('wd_mat2').innerHTML = Math.round(width * 300 * 100000 / 12)/100000;
 }
 else
 {
  document.getElementById('ht_mat').innerHTML = fraction(Math.round(height*100000)/100000);
  document.getElementById('wd_mat').innerHTML = fraction(Math.round(width*100000)/100000);
  document.getElementById('ht_mat2').innerHTML = Math.round(height*100000)/100000;
  document.getElementById('wd_mat2').innerHTML = Math.round(width*100000)/100000;
 }
}
