
////
//  Mouse over for logo
function logo_mouseover(div){
  div.setStyle({backgroundPosition: '-191px'});
}


////
//  Mouse over for logo
function logo_mouseout(div){
  div.setStyle({backgroundPosition: '0px'});
}


////
//  Handler for when the country select changes
function country_change(){

  var s = $('profile_country');
  var provinces;
  var id = s[s.selectedIndex].value;
  var province_select = $('profile_province');

  if($R(null, '').include(id)){
    provinces = [['Select Country First', null]];
  }else{
    provinces = enums.province.select(function(province){
        return(Math.floor(province.last() / 100) == id);
        });
  }

  // Remove all the options
  remove_options(province_select);

  // Add correct state/provinces for country
  provinces.each(function(p_array){
      opt = document.createElement('option');
      opt.text = p_array.first();
      opt.value = p_array.last();
      // province_select.appendChild(opt); WTF Internet Explorer?
      province_select.options.add(opt);
  });
}


////
//  Handler for when the gender select changes
function gender_change(){
  var s = $('profile_gender');
  var weights;
  var id = s[s.selectedIndex].value;
  var weight_select = $('profile_weight');
  var old_weight = weight_select[weight_select.selectedIndex].value;

  if($R(null, '').include(id)){
    weights = [['uhhhh not sure', null]];
  }else{
    weights = enums.weight.select(function(weight){
        var hundreds = Math.floor(weight.last() / 100);
        return(hundreds === 0 || hundreds == id);
        });
  }

  // Remove all the options
  remove_options(weight_select);

  //  Add correct weight options for the gender
  weights.each(function(w_array){
      opt = document.createElement('option');
      opt.text = w_array.first();
      opt.value = w_array.last();
      //weight_select.appendChild(opt);   WTF Internet Explorer?
      weight_select.options.add(opt);
  });

  //  Set the weight back to what it was, or to it's gender equivilant
  //  if it is < 100 it is already for both genders, otherwise they
  //  are paired in differences of 100 * gender_id.  Silly but it works.
  var new_weight = old_weight;
  if(new_weight >= 100){
    new_weight = Math.floor((new_weight % 100) + (id * 100));
  }

  // Set it
  var index = 0;
  weight_select.childElements().each(function(option){
      if(option.value == new_weight){
        weight_select.selectedIndex = index;
      }
      index += 1;
  });
}


////
//  Remove all the options from a select box
function remove_options(s){
  s.childElements().each(function(option){ option.remove(); });
}


stage1 = {login: false, password: false};

//// if the right conditions for stage 0 are present
// then enable the next button.
function enable_stage0_next() {
  var email = $('email0').value;
  var area_code = $('area_code0').value;
  if ((email.length > 0) && (area_code.length > 0)) {
    $('next').enable();
  }
  else {
    $('next').disable();
  }
}

function email0_change(){
  var email = $('email0').value;
  if (email.length > 0) {	
    $('spinner').src = '/images/check.png';
    $('spinner').show();
  } else {
    $('spinner').hide();
  }
  enable_stage0_next();
}

function area_code0_change(){
  var area_code = $('area_code0').value;
  if (area_code.length > 0) {
    $('spinner2').src = '/images/check.png';
    $('spinner2').show();
  } else {
    $('spinner2').hide();
  }
  enable_stage0_next();
}

////
//  if the right conditions are happening we should enable
//  the next button.
function enable_stage1_next(){
  var agreed = $('tos_age').checked == true && $('tos_terms_of_service').checked == true;
  if(stage1.login && stage1.password && agreed){
    $('next').enable();
  }else{
    $('next').disable();
  }
}


////
//  TOS stuff changed
function tos_change(){
  enable_stage1_next();
}


////
//  The login textbox has changed, lets see if the username was taken.
function login_field_change(){
  stage1.login = false;
  enable_stage1_next();

  var textbox = $('login');
  $('login_spinner').src = '/images/spinner.gif';
  $('login_spinner').show();

  //  See if the value matches my regex
  var re = /^[a-zA-Z0-9_]+$/;
  var name = textbox.value.strip();
  if(re.match(name)){
    if(name.length < 3){
      $('login_status').update('Nickname too short!');
      $('login_status').show();
      $('login_spinner').hide();
      return false;
    }else if(name.length > 20){
      $('login_status').update('Too long. 20 Chars max');
      $('login_status').show();
      $('login_spinner').hide();
      return false;
    }else{

      $('login_status').update('Checking availability...');
      $('login_status').show();

      new Ajax.Request('/users/available/' + escape(name), 
          { onSuccess: function(response){
            var parsed = response.responseText.evalJSON(true);
            if(parsed.available){
              $('login_status').update('Nickname is available');
              $('login_spinner').src = '/images/check.png';
              stage1.login = true;
              enable_stage1_next();
            }else{
              $('login_status').update('Nickname unavailable!');
              $('login_spinner').hide();
            }
          }, method: 'get'
          });
    }
  }else if(name != ''){
    $('login_status').update('Invalid characters!');
    $('login_status').show();
    $('login_spinner').hide();
  }else{
    $('login_spinner').hide();
  }

  enable_stage1_next();
}


////
//  The login textbox has changed, lets see if the username was taken.
function password_field_change(){
  stage1.password = false;
  enable_stage1_next();
  var password = $('password').value;
  var password_confirmation = $('password_confirmation').value;


  if(password != ''){
    if(password.length < 6){
      $('password_spinner').hide();
      $('password_status').show();
      $('password_status').update('Password too short');
    }else if(password == password_confirmation && password.length >= 6){

      $('password_spinner').show();
      $('password_status').hide();
      $('password_status').update('matches');
      stage1.password = true;
    }else{
      $('password_spinner').hide();
      $('password_status').show();
      $('password_status').update('Passwords do not match');
    }
  }
  enable_stage1_next();
}



stage2 = {phone: false, validated: false};

////
//  if the right conditions are happening we should enable
//  the next button.
function enable_stage2_next(){
  //if(stage2.phone){
  if(stage2.validated){
    $('next').enable();
  }else{
    $('next').disable();
  }
}

////
//  the phone number field has changed
function phone_field_change(){
  stage2.phone = false;
  enable_stage2_next();

  var phone_number = $('phone_number').value.strip();
  phone_number = phone_number.gsub(/\./, '-');  // no likey dots

  var re = /^1?[\-\. ]?\(?\d\d\d\)?[\-\. ]?\d\d\d[\-\. ]?\d\d\d\d$/;

  $('submit_number').disable();

  if(phone_number != ''){
    if(re.match(phone_number)){
      $('spinner').show();
      $('phone_status').update('Checking availability...');

      new Ajax.Request('/users/phone_available/' + escape(phone_number), 
          { onSuccess: function(response){
            var parsed = response.responseText.evalJSON(true);
              if(parsed.available){
                $('phone_status').update('Phone # is available');
                $('spinner').src = '/images/check.png';
                stage2.phone = true;
                $('submit_number').enable();
                //enable_stage2_next();
              }else{
                $('phone_status').update('Phone # has been used');
                $('spinner').hide();
              }
          }, method: 'get'
          });

    }else{
      $('phone_status').update('Invalid phone number');
      $('spinner').hide();
    }
  }else{
    $('phone_status').update('');
    $('spinner').hide();
  }
  enable_stage2_next();
}

////
//  Validation field has changed
function validation_field_change(){
  stage2.validated = false;
  enable_stage2_next();
  var validation_code = $('validation_code').value.strip();

  if(validation_code.length == 4){
    $('spinner2').src = '/images/spinner.gif';
    $('spinner2').show();

    new Ajax.Request('/users/verify_code/' + escape(validation_code), 
        { onSuccess: function(response){
            var parsed = response.responseText.evalJSON(true);
            if(parsed.valid){
              $('validation_status').update('Correct');
              $('validation_status').show();
              $('spinner2').src = '/images/check.png';
              stage2.validated = true;
              enable_stage2_next();
            }else{
              $('validation_status').update('Invalid code!');
              $('validation_status').show();
              $('spinner2').hide();
            }
          }, method: 'get'
        });
  }else{
    $('validation_status').hide();
    $('spinner2').hide();
  }
  enable_stage2_next();
}

////
//  About me text box has changed
function about_field_change(){
  box = $('about_me');
  $('char-count').update('(' + (250 - box.value.length) + ' characters left)');
  var maxlength = 250;
  if(box.value.length > maxlength){
    box.value = box.value.substring(0,maxlength);
  }
  if(box.value.length > 0){
    $('next').enable();
  }else{
    $('next').disable();
  }
}

////
// Stage 4
////

stage4 = {postal: false, city: false};

function city_field_change(){
  stage4.city = $('profile_city').value.strip() != '';
}

function enable_stage4_next(){
  if(stage4.postal && stage4.city){
    $('next').enable();
  }else{
    $('next').disable();
  }
}

function postal_code_is_valid(postal_code){
  var zip_re = /^\d\d\d\d\d$/;
  var postal_re = /^([A-Za-z]\d[A-Za-z]) ?(\d[A-Za-z]\d)$/;
  return(zip_re.match(postal_code) || postal_re.match(postal_code));
}

////
//  The postal code box has changed
function postal_field_change(){
  var postal = $('profile_postal').value;

  var valid = postal_code_is_valid(postal);
  stage4.postal = postal.strip() != '' && valid;

  if(postal.length >= 5 && valid){
    $('spinner').show();
    new Ajax.Request('/users/location_from_postal/' + escape(postal), 
        { onSuccess: function(response){
          var parsed = response.responseText.evalJSON(true);
          if(parsed.found){
            var index = 0;

            $('profile_city').value = parsed.city;
            country_enum = parsed.country.last();
            province_enum = parsed.province.last();

            $('profile_country').childElements().each(function(option){
                if(option.value == country_enum){
                  $('profile_country').selectedIndex = index;
                }
                index += 1;
            });


            country_change();

            index = 0;

            $('profile_province').childElements().each(function(option){
                if(option.value == province_enum){
                  $('profile_province').selectedIndex = index;
                }
                index += 1;
            });

            city_field_change();

            $('postal_status').update('Found');

            $('spinner').hide();
          }else{
            $('spinner').hide();
          }
          }, method: 'get' 
        });
  }else if(! valid){
    $('postal_status').update('Invalid');
  }else{
    $('postal_status').update('Too short');
  }

  enable_stage4_next();
}


