// Handlers
//
console.log("Loading register.js...");

function initRegister() {
     
}

function handleRegister(res) {
    initRegister();  

    $$('.RegStep1Form-formtable-error').invoke('hide');

    var errors = Try.these(
      function() { return $H(res['data'].errors); },
      function() { return $H(); }
    );

    errorColor = "#ff0000";

    errors.each(
      function(h){
        console.log(h.key);

        if (h.key == "username"){
         $('RegStep1Form-username-fieldname').setStyle({color:errorColor});
        }

        if (h.key == "security code"){
         $('RegStep1Form-security-code-fieldname').setStyle({color:errorColor});
        }

        if (h.key == "password"){
         $('RegStep1Form-password-fieldname').setStyle({color:errorColor});
         $('RegStep1Form-retype-password-fieldname').setStyle({color:errorColor});
        }

        if (h.key == "email"){
         $('RegStep1Form-email-fieldname').setStyle({color:errorColor});
         $('RegStep1Form-retype-email-fieldname').setStyle({color:errorColor});
        }

        $('register-error-msg').update(h.value);
      }
    )

    var username = $('RegStep1Form-text-username').value;

    $('RegStep1Form-text-username').ancestors()[0].update('<div id="RegStep1Form-background-username" class="RegStep1Form-background"><input type="text" name="RegStep1Form_username" id="RegStep1Form-text-username" class="RegStep1Form-text" value="'+username+'" /></div>');

    $('RegStep1Form-password-password').ancestors()[0].update('<div id="RegStep1Form-background-password" class="RegStep1Form-background"><input type="password" name="RegStep1Form_password" id="RegStep1Form-password-password" class="RegStep1Form-password" /></div>');

    $('RegStep1Form-password-retype-password').ancestors()[0].update('<div id="RegStep1Form-background-retype-password" class="RegStep1Form-background"><input type="password" name="RegStep1Form_retype password" id="RegStep1Form-password-retype-password" class="RegStep1Form-password" /></div>');


    var email = $('RegStep1Form-text-email').value;
    var retypeEmail = $('RegStep1Form-text-retype-email').value; 

    $('RegStep1Form-text-email').ancestors()[0].update('<div id="RegStep1Form-background-email" class="RegStep1Form-background"><input type="text" name="RegStep1Form_email" id="RegStep1Form-text-email" class="RegStep1Form-text" value="'+email+'" /></div>');

    $('RegStep1Form-text-retype-email').ancestors()[0].update('<div id="RegStep1Form-background-retype-email" class="RegStep1Form-background"><input type="text" name="RegStep1Form_retype email" id="RegStep1Form-text-retype-email" class="RegStep1Form-text" value="'+retypeEmail+'" /></div>');

    $('RegStep1Form-text-security-code').ancestors()[0].update('<div id="RegStep1Form-background-security-code" class="RegStep1Form-background"><input type="text" name="RegStep1Form_security_code" id="RegStep1Form-text-security-code" class="RegStep1Form-text" /></div>');

    $('RegStep1Form-submit-button').ancestors()[0].update('<input type="image" src="../../images/btn_upload_continue.gif" id="RegStep1Form-submit-button" class="continue-btn" />');

    init_btn_rollover('continue');

    var frm = 'RegStep1Form';
    Event.observe(frm, 'submit', function(event) { 
	Event.stop(event);
	FwDispatch.form(frm,'view-container',null,handleForm2);
    });

}

var regStep2Error;

function validateStep2() { 

    var foundError = false;

    var selectedCity = null;

    if($('RegStep2Form-select-country').value == ''){
      console.log("no country selected");

      $('register2-error-msg').update('Please select a country');
      foundError = true;
      regStep2Error = 'country';
      return;
    }

    if ($('RegStep2Form-select-state-or-province').value=='NA') {
      console.log("no state/province selected");

      $('register2-error-msg').update('Please select a state or province');
      foundError = true;
      regStep2Error = 'state';
      return;
    }

    var cities = Try.these(
      function() { return $('RegStep2Form').RegStep2Form_city; },
      function() { return null; }
    );

    if (cities) {
      if (cities.length > 1){
        for (var i=0; i < cities.length; i++) {
          if (cities[i].checked) {
            selectedCity = cities[i].getValue();
          }
        }
      } else if (cities.checked) {
        selectedCity = cities.getValue();
      }
    }

    if (!selectedCity) {
      $('register2-error-msg').update('Please select a city');
      foundError = true;
      regStep2Error = 'city';
      return;
    }

    if (foundError == false) {

      var frm = 'RegStep2Form';
  	  FwDispatch.form(frm,'view-container',null,handleForm3);

      return true;
    } else {
      return false;
    }
}

function handleForm2(res) {
    initRegister(); 

    if($('RegStep1Form-text-username')) {
	handleRegister(res);
	return false;
    }

    $('RegStep2Form-city-fieldname').update('');
    $('RegStep2Form-state-or-province-fieldname').update('');
    $('RegStep2Form-state-or-province-fieldname').setStyle({width:'126px'});

    $('RegStep2Form-text-first-name').ancestors()[0].update('<div id="RegStep2Form-background-first-name" class="RegStep2Form-background"><span id="first-name-optional">optional and private</span><input type="text" name="RegStep2Form_first_name" id="RegStep2Form-text-first-name" class="RegStep2Form-text" /></div>');

    $('RegStep2Form-text-last-name').ancestors()[0].update('<div id="RegStep2Form-background-last-name" class="RegStep2Form-background"><span id="last-name-optional">optional and private</span><input type="text" name="RegStep2Form_last_name" id="RegStep2Form-text-last-name" class="RegStep2Form-text" /></div>');

    $('RegStep2Form-textarea-address').ancestors()[0].update('<div id="RegStep2Form-background-address"><span id="address-optional">optional and private</span><textarea name="RegStep2Form_address" class="RegStep2Form-textarea" id="RegStep2Form-textarea-address" /></textarea></div>');

    $('RegStep2Form-select-state-or-province').ancestors()[0].update('<div id="reg-state-select"></div>');

    $('RegStep2Form-select-city').ancestors()[0].update('<span id="city-cell-text" class="field-label">City</span><input type="text" id="city-partial" /><div name="RegStep2Form_city" class="RegStep2Form-select" id="RegStep2Form-select-city"></div>');

    $('RegStep2Form-submit-button').ancestors()[0].update('<div id="register2-error-msg" class="formtable-error"></div><input type="image" src="../../images/btn_upload_continuetofinish.gif" alt="Continue to Finish" id="RegStep2Form-submit-button" onclick="javascript:validateStep2();return false;" class="finish-btn" />');

    init_btn_rollover("finish");

    $('RegStep2Form-state-or-province-data-cell').hide();
    $('RegStep2Form-city-data-cell').hide();
 
    var country;
    var state;

    Event.observe('RegStep2Form-select-country', 'change', function(event) { 
      country = encodeURIComponent($('RegStep2Form-select-country').getValue());
      if (regStep2Error == 'country'){
        $('register2-error-msg').update('');
      }

      $('city-partial').clear(); 
      if (state) {
        $('RegStep2Form-select-city').setStyle({display:'none'});
        state='';
      }

      $('RegStep2Form-state-or-province-fieldname').update('State Or Province');

      FwDispatch.content('auth/list_states_for_country_data.html?country='+country,'reg-state-select',null,changeState);
      $('RegStep2Form-state-or-province-data-cell').show();
    });


    Event.addBehavior({
	"#RegStep2Form-select-state-or-province": function() {
	    this.observe('change', function(event) {
		
		if (regStep2Error == 'state'){
		    $('register2-error-msg').update('');
		}
		
		console.log("got a state");
		
		state = encodeURIComponent($('RegStep2Form-select-state-or-province').getValue());
		$('city-partial').clear();
		FwDispatch.content('auth/list_cities_data.html?country='+country+'&state='+state,'RegStep2Form-select-city',null,null);
		$('RegStep2Form-city-data-cell').show();
	    });	
    }
    });

    new Form.Element.Observer(
      'city-partial',
      1,
      function(element,value){
        cityPartial = encodeURIComponent(value);
        if (cityPartial.length >= 3){ 
          $('RegStep2Form-select-city').setStyle({display:'block'});
          FwDispatch.content('auth/list_cities_data.html?country='+country+'&state='+state+'&city_partial='+cityPartial,'RegStep2Form-select-city',null,null);
        }
      }
    )


    var frm = 'RegStep2Form';
    Event.observe(frm, 'submit', function(event) { 
	Event.stop(event);
	FwDispatch.form(frm,'view-container',null,handleForm3);
    });
}

function changeState(res){
  console.log('change state');
}

function handleForm3(res) {
    
}
