/**
 * Require: jquery.url.js
 */
var TextDeathClock = {

  clockId: 0,
  clockValue: 2080,
  selectedYear: (new Date()).getFullYear() - 18,
  inputName: '',
  alert_message_name: 'Please fill the Name field with at least 2 names!',
  alert_message_age: 'Please enter your current age!',
  alert_message_gender: 'Please enter your gender!',

  _complete_ckey: 'TextDeathClock_completed',

  getParamString: function() {
    var s = 'TextDeathClock_name=' + escape(this.inputName) + '&' + 'TextDeathClock_date=' + escape(this.selectedYear);
    return s;
  },

  // ---------------
  // --- i n i t ---
  // ---------------
  init: function() {
    try {
      if (jQuery.url.param('TextDeathClock_name')) this.inputName = jQuery.url.param('TextDeathClock_name');
      if (jQuery.url.param('TextDeathClock_date')) this.selectedYear = jQuery.url.param('TextDeathClock_date');
    }
    catch(e) {
      //alert(e.message);
    }

    if (typeof sc_sentinel == 'function') {
      if (! sc_sentinel()) {
        $('#stepindex').hide();
        $('#gravename').html(TextDeathClock.inputName);
        Set_Cookie('TextDeathClock_name', TextDeathClock.inputName);
        Set_Cookie('TextDeathClock_date', TextDeathClock.selectedYear);
        Set_Cookie(this._complete_ckey, 'true');
        TextDeathClock.displayGraveAge();
        return false;
      }
    }
    else if (Get_Cookie(this._complete_ckey) == 'true') {
      //- check cookie -----
      TextDeathClock.inputName = Get_Cookie('TextDeathClock_name');
      TextDeathClock.selectedYear = Get_Cookie('TextDeathClock_date');
      $('#gravename').html(TextDeathClock.inputName);
      TextDeathClock.displayGraveAge();
      $(Owlery).trigger('repopulate');
      return false;
    }
    else {
      $('#container').removeClass('imagestep1').addClass('imagestep0 imagestep_pre1');
      $('#inputzone').hide();
      $('#starttest').show();
      $('#name').val('').focus();

      //- start test -----
      $('#start_test_btn').click(function(e) {
        e.preventDefault();
        TextDeathClock.startTest();
      });

      $('#form1').submit(function(e) {
        TextDeathClock.startTest();
        return false;
      });

      $('#name').blur(function() {
        this.value = $('#gravename').html();
      });

      //- input name key press -----
      $('#name').keypress(function(e) {
        if (this.value.length < this.maxLength) {
          var keynum;
          if (window.event) { // IE
            keynum = e.keyCode;
          }
          else if (e.which) {// Netscape/Firefox/Opera
            keynum = e.which;
          }
          if (keynum != undefined)  {
            $('#gravename').html(this.value + String.fromCharCode(keynum));
          }
        }
      });

      //- input name keyup event -----
      $('#name').keyup(function(e) {
        var keynum;
        if (window.event) { // IE
          keynum = e.keyCode;
        }
        else if (e.which) {// Netscape/Firefox/Opera
          keynum = e.which;
        }
        if (keynum == 8 || keynum == 46) {
          $('#gravename').html(this.value);
        }
      });

      //- build date options -----
      TextDeathClock.buildDate();
    }

    return true;
  },

  //- start test
  startTest: function() {
    var status = true;
    var msg = '';
    if (!TextDeathClock.checkInputName()) {
      msg += TextDeathClock.alert_message_name;
      msg += "\n";
      status = false;
    }

    if (!TextDeathClock.checkDateofBirth()) {
      msg += TextDeathClock.alert_message_age;
      msg += "\n";
      status = false;
    }

    if (!TextDeathClock.checkGender()) {
      msg += TextDeathClock.alert_message_gender;
      msg += "\n";
      status = false;
    }

    if (! status) {
      alert(msg);
      return;
    }

    TextDeathClock.selectedYear = $('#bdayyy').val();
    Set_Cookie('TextDeathClock_name', TextDeathClock.inputName);
    Set_Cookie('TextDeathClock_date', TextDeathClock.selectedYear);

    $('#gravecounter').css({'top' : $('#gravename').position().top + $('#gravename').height() });

    TextDeathClock.displayGraveAge();

    $('#starttest').hide();

    $('#container').removeClass('imagestep0 imagestep_pre1').addClass('imagestep1');
    Set_Cookie(this._complete_ckey, 'true');
    $('#inputzone').fadeIn('slow');
    $(Owlery).trigger('showMin');
  },

  //- gen the day, month, year options
  buildDate: function() {
    var val = '';

    for (i = 1; i <= 31; i++) {
      val = (i < 10) ? ('0' + i) : i;
      $('#bdaydd').append('<option label="' + val + '" value="' + i + '">' + val + '</option>');
    }

    for (i = 1; i <= 12; i++) {
      val = (i < 10) ? ('0' + i) : i;
      $('#bdaymm').append('<option label="' + val + '" value="' + i + '">' + val + '</option>');
    }

    var currentYear = new Date().getFullYear();
    var maxYear = currentYear - 18;
    var minYear = currentYear - 80;
    for (; maxYear >= minYear; maxYear--) {
      $('#bdayyy').append('<option label="' + maxYear + '" value="' + maxYear + '">' + maxYear + '</option>');
    }
  },

  updateClock: function() {
    if (TextDeathClock.clockId) {
      clearTimeout(TextDeathClock.clockId);
      TextDeathClock.clockId = 0;
    }
    var tDate = new Date();
    $('#gravecounter').html(TextDeathClock.selectedYear + ' - ' + (TextDeathClock.clockValue--));
    if (TextDeathClock.clockValue == 2000) {
      TextDeathClock.clockValue = 2080;
    }
    TextDeathClock.clockId = setTimeout('TextDeathClock.updateClock(' + TextDeathClock.clockValue + ')', 50);
  },

  startClock: function() {
    TextDeathClock.clockId = setTimeout('TextDeathClock.updateClock(' + TextDeathClock.clockValue + ')', 0);
  },

  killClock: function() {
    if (TextDeathClock.clockId) {
      clearTimeout(TextDeathClock.clockId);
      TextDeathClock.clockId = 0;
    }
  },

  //- display grave age
  displayGraveAge: function() {
    TextDeathClock.startClock();
  },

  //- check an input name
  checkInputName: function() {
    TextDeathClock.inputName = $('#name').val();
    TextDeathClock.inputName = jQuery.trim(TextDeathClock.inputName);

    var inputStr = TextDeathClock.inputName.split(/[\s]+/);
    var gname = $('#gravename').html();

    gname = jQuery.trim(gname);
    return (inputStr.length >= 2 && gname.length >= 3);
  },

  //- check date of birth
  checkDateofBirth: function() {
    var maxDay = 0;
    var dayV   = parseInt($('#bdaydd').val());
    var monthV = parseInt($('#bdaymm').val());
    var yearV  = parseInt($('#bdayyy').val());

    switch(monthV) {
      case 2:
        maxDay = (((yearV % 4 == 0) && ((!(yearV % 100 == 0)) || (yearV % 400 == 0)))) ? 29 : 28;
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        maxDay = 30;
        break;
      default:
        maxDay = 31;
        break;
    }
    return (dayV >= 1 && monthV >= 1 && yearV >= 1900 && monthV <= 12 && dayV <= maxDay);
  },

  //- check the gender selected value.
  checkGender: function() {
    var gender = $('#gender').val();
    return (gender != -1);
  },

  //- at the end of questions
  end: function() {
    $('#q' + TextDeathClock.currentIndex).hide();
    $('#stepindex').hide();

    $('#container').removeClass('imagestep0 imagestep_pre2').addClass('imagestep1');
    Set_Cookie(this._complete_ckey, 'true');
    $('#inputzone').fadeIn('slow');
    $(Owlery).trigger('showMin');
  }
};

landingControlHolder['precontroller'] = TextDeathClock;

