// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function createObjectCallback(obj, fn)
{
  return function() { fn.apply(obj, arguments); };
} 

/* AJAX stuff */
/* credit to Raj Shekhar for the basics of the AJAX code below
*/
function xml_req() {
   if(navigator.appName == "Microsoft Internet Explorer"){
       var http = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
       var http = new XMLHttpRequest();
   }
   return http;
}

function replace_innerHTML_handleResponse () {
  if( this.http && this.http.readyState == 4 ) {
    if ( this.http.status == 200 ) {
      this.innerHTML = this.http.responseText;
    } else {
      alert('ERROR: status code is ' + this.http.status );
    }
  }
}


// XmlHttpReq call to replace a tag's content with the result of an HTTP
// request
function replace_innerHTML(elt,url) {
  //alert("Call to replace text on " + elt.id);
  elt.http = xml_req();
  
 
  elt.http.open('get',url);
  elt.http.onreadystatechange = createObjectCallback(elt,replace_innerHTML_handleResponse);
  elt.http.send(null);
}

function repeat(thunk,delay) {
  var obj = new Object();
  obj.repeat = function () {
    thunk();
    setTimeout(createObjectCallback(obj,obj.repeat),delay*1000);
  }
  obj.repeat();
}

function insert_option_sorted(dst,opt) {
  for (var i=0;i<dst.options.length;i++) {
    if ( dst.options[i].id > opt.id ) {
      dst.insertBefore(opt,dst.options[i]);
      return;
    }
  }
  dst.appendChild(opt);
}

function move_selected(src_id,dst_id,callback) {
  var src = document.getElementById(src_id);
  var dst = document.getElementById(dst_id);

  //  alert("selectedIndex is " + src.selectedIndex );
  
  /* at least in firefox, we can get multiple selections by removing
     one at a time and FF will update selectedIndex to the next of a
     multiple selection */
  while ( src.selectedIndex >= 0 ) {
    var opt = src.options[src.selectedIndex];
    opt.parentNode.removeChild(opt);
    insert_option_sorted(dst,opt);
    if ( callback!=null ) {
       callback(opt.value);
    }
  }
}

function select_all(sel_id) {
  var sel = document.getElementById(sel_id);
  for(var i=0;i<sel.options.length;i++) {
    sel.options[i].selected = true;
  }
}

function check_times(start,end,msg) {
 var sel_start = $(start);
 var sel_end = $(end);

 
 if ( sel_start.options[sel_start.selectedIndex].value > sel_end.options[sel_end.selectedIndex].value ) {
   $(msg).show();
 } else {
   $(msg).hide();
 }
}

function updateCellEmail(obj,method) {
  var field = obj + '_' + method;
  var sel = $( field + '_provider');
  
  $(field).value = $(field + '_digits').value + sel.options[sel.selectedIndex].value;
}

function disable_children(container,disabled) {
  var clist = $A(container.childNodes);

  clist.each(function (child) {
    child.disabled=disabled;
     });
}

function limit_length(elt,max_len,status_id) {
  var remaining = max_len - elt.value.length;
  if ( remaining < 0 ) {
    $(status_id).style.color = "red";
    $(status_id).innerHTML = "Maximum length exceeded by " + (0-remaining) + " characters";
  } else {
    $(status_id).style.color = "black";
    $(status_id).innerHTML = remaining + " characters remaining";
  }
}

function select_radio_button(elem) {
  var radio = document.getElementById(elem);
  radio.checked = true;
}

function calculate(form) 
{
  // Get the fields
  //var init_property_value =  form.calc_property_value.value;
  var init_property_value =  form.calc_loanamount.value;
  var init_downpayment = form.calc_downpayment.value;
  var init_rate = form.calc_rate.value;
  var init_term = form.calc_loanterm.value;

  // Check the fields 
  init_downpayment = init_downpayment.replace(/[^0-9]/g, '');
  init_property_value = init_property_value.replace(/[^0-9]/g, '');

  if (init_property_value == '')
  {
    init_property_value = '0';
  }


  if (init_downpayment == '')
  {
    init_downpayment = '0';
  }

  // Operate on the data
  var newrate = init_rate/1200;
  var months = init_term*12;
  var principle = init_property_value - init_downpayment;
  monthly = Math.round((newrate + (newrate / (Math.pow(newrate+1,months) - 1)))*principle*100)/100;


  // Set the fields
  form.calc_loanamount.value = ' $ ' + addCommas(init_property_value);
  //form.calc_loanamount.value = ' $ ' + init_property_value;
  form.calc_downpayment.value = ' $ ' + addCommas(init_downpayment);
  //form.calc_downpayment.value = ' $ ' + init_downpayment;
  form.calc_payment.value = ' $ ' + addCommas(monthly);
  //form.calc_payment.value = ' $ ' + monthly;
}


function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}
