function businessAccountChanged() {
  // Static var businessAccountChanged.timer
  if(typeof businessAccountChanged.timer == 'undefined' ) {
      businessAccountChanged.timer = null;
  }
  
  if(businessAccountChanged.timer!==null)
   clearTimeout(businessAccountChanged.timer);
  
  businessAccountChanged.timer=setTimeout(function () {
     updateBusinessAccount();
   }, 500); //Wait for checked status to settle (esp for IE)
}

function updateBusinessAccount() {
  var businessAccount=getBusinessAccountValue();
  
  if(!businessAccount) {
    $('wholesaler').setValue('0');
    $('multiple_outlets').setValue('0');
  }
  
  var rowDisplayValue = (businessAccount) ? '' : 'none';
  var rows = $$('.signup_business_only_row');
  for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
    row = rows[rowIndex];
    row.style.display = rowDisplayValue;
  }
}

function getBusinessAccountValue() {
  var businessAccount=null;
  for(var i=0; i<2; i++) {
    if($('business_account_'+i).checked) {
      businessAccount=($('business_account_'+i).value=='1');
      break;
    }
  }
  return businessAccount;
}

function emailFieldKeyUp() {
  if (!haveModifiedUsername) {
    // base default username off email address, removing the @ symbol and stripping illegal chars
    if($('username')) {
	    username = $('email').value.replace(/^([^@]*).*$/, '$1').replace(/[^a-zA-Z0-9-\._]/g, '');
	    username = username.toLowerCase();
	    $('username').value = username;
	  }
  }
}

var haveModifiedUsername = false;

function usernameFieldKeyUp() {
  haveModifiedUsername = true;
}

function passwordFieldKeyUp() {
  if ($('password_two').value == '') {
    $('invalid_passwords_msg').innerHTML = '';
    return;
  }
  
  var passwordsDontMatch = ($('password_one').value != $('password_two').value);
  
  $('invalid_passwords_msg').innerHTML = passwordsDontMatch ? '<em style="color: #a00;">Your passwords don\'t match</em>' : '<em style="color: #0a0;">Password accepted</em>';
}

function getNextAddressIdx() {
	var i=0;
	while($('idaccount_holder_address_'+i))
		i++;
	return i;	
}

function addAddress() {
  var maxBusinessOutlets=20;
	var i=getNextAddressIdx();
	if(i>(maxBusinessOutlets-1)) {
		alert('Sorry, the maximum number of outlets is '+maxBusinessOutlets);
		return;
	}
	
  new Ajax.Request('signup.addaddress.'+i, {
  method: 'get',
  onSuccess: function(i, transport) {
    if(transport.responseText=='')
      return;
    addAddressCallback(i,transport.responseText);
  }.bind(this,i)});
}

function addAddressCallback (id,html) {
	$('add_address_row').insert({ before: html});
}


function accountModifyMultipleOutletsChanged() {
	var value=$('multiple_outlets').getValue();
  switch(value) {
	  case '1':
		  $('add_address_row').show();
		  $('main_address_heading').show();
		  $('outlets-note-row').show();
		  if(getNextAddressIdx()==0)
		    addAddress();
		  break;
	  default:
		  $('add_address_row').hide();
		  $('main_address_heading').hide();
      $('outlets-note-row').hide();
		  break;
  }
  elements=$$('.account_holder_address_row');
	elements.each(function(el) {
		(value==1) ? el.show() : el.hide() ;
	});
}

function accountModifyWholesalerChanged() {
	var value=$('wholesaler').getValue();
	var businessAccount=getBusinessAccountValue();
	
	//Hide and disable multiple outlets if wholesaler is on, otherwise show
	if(value=='1') $('multiple_outlets').setValue(0);
	accountModifyMultipleOutletsChanged();
  elements=$$('.multiple_outlets');
	elements.each(function(el) {
		(value=='1' || !businessAccount) ? el.hide() : el.show() ;
	});
}

function getLocationIdx(element) {
  var idbits=/_([0-9]*)$/.exec(element.id);
	if(!idbits)
    return false;
  return idbits[1];
}


function updateListingNationalRegions(el) {
  el=$(el);
  var idx=getLocationIdx(el);
  var state = el.getValue();
  sendAjaxMessage('signup', 'fetchNationalRegions', {'state':state}, updateListingNationalRegionsCallback.bind(this,idx));
}

function updateListingNationalRegionsCallback(idx, response) {  
  // update idregion select
  var regionsEl = $('idnational_region_'+idx);
  regionsEl.options.length = 0;
  regionsEl.options[regionsEl.options.length] = new Option('- Please Select -', '');
  for (var i = 0; i < response.national_regions.length; i++) {
    var idnational_region = response.national_regions[i].idnational_region;
    var title = response.national_regions[i].name;
    
    regionsEl.options[regionsEl.options.length] = new Option(title, idnational_region);
    if (idnational_region == response.idnational_region)
      regionsEl.options[regionsEl.options.length-1].selected = true;
  }
}

function locationPostcodeChanged(el) {
  el=$(el);
  // do nothing if it isn't 4 characters
  if (el.getValue().length != '4')
    return;
    // update region selcet boxes based on the new postcode
  updateLocationRegions(el);
}

function updateLocationRegions(el) {
  //placeholder
}


function updateLocationRegionsVisible(idx) {
  if (document.getElementById('idregion_'+idx).length == 0) {
    x$(document).byClassName('valid_postcode_only_'+idx).hide();
  } else {
    x$(document).byClassName('valid_postcode_only_'+idx).show();
  }
}


function setupAccountModifyEvents() {
  $('wholesaler').observe('change', function(evnt) { accountModifyWholesalerChanged() } );
  $('multiple_outlets').observe('change', function(evnt) { accountModifyMultipleOutletsChanged() } );
  updateBusinessAccount();
  accountModifyMultipleOutletsChanged();
  accountModifyWholesalerChanged();
}

Event.observe(window, 'load', function() {
	setupAccountModifyEvents();
});

function businessNameFieldKeyUp() {
  //Placeholder - not used if Business/Private radio exists
}




