var contestLondon = {
  config : {
    container: $("#contest-london-container"),
  },
  init : function(){
    this.config.container = $("#contest-london-container");
    var c = this;
    $('#contest-londen-emailfield', this.config.container).each(function(){
      var val = $(this).val();
      $(this).val('');
      $(this).watermark(val, {useNative: false});
    });
    $('#contest-london-button', this.config.container).click(function(){
      var v = c.isValid();
      if(v && !$('#contest-londen-emailfield').hasClass("watermark"))
      {        
        var cult = $('#sendToFriend .culture').text();
        $.post("/base/LondonContest/Save/"+cult, 
               { email: $('#contest-londen-emailfield', $("#contest-london-container")).val()});
      }
      return v;
    });
  },
  isValid: function(){
    var valid = true;
    var cts = this;
    cts.clearValidation();
    
    // validation match email
    $('.matchemail', cts.config.container).each(function(){
      if(!$(this).hasClass("watermark")){
        var el = $(this);
        var val = el.val();
        var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
        if(val.match(re) == null)
        {
          el.addClass('error');
        }
      }
    });
    
    valid = $('.error', this.config.container).length == 0;
    $('.validationsummary', this.config.container).toggle(!valid);
    return valid;
  },
  
  clearValidation: function() {
    $('.validationsummary', this.config.container).hide();
    $('.error', this.config.container).removeClass('error');
  }
};
    
    






var contest3x4 = {
  config : {
    useValidation: true,
    getType: function(el) {
      var types = this.fieldTypes;
      var t = '';
      
      if($(el).hasClass("textbox"))
      {
        t = types.txt;
      }
      if($(el).hasClass("radiobutton"))
      {
        t = types.rbt;
      }
      if($(el).hasClass("select"))
      {
        t = types.sel;
      }
      if($(el).hasClass("checkbox"))
      {
        t = types.chk;
      }
      if($(el).hasClass("selectgroup"))
      {
        t = types.selgroup;
      }
      if($(el).hasClass("radiobuttonlist"))
      {
        t = types.rbgroup;
      }
      return t;
    },
    
    fieldTypes : {
      txt: 'txt',
      sel: 'sel',
      chk: 'chk',
      rbt: 'rbt',
      selgroup: 'selgroup',
      rbgroup: 'rbgroup'
    }
  },
  container : $('.contest'),
  
  init: function(){
    this.container = $('.contest');
    this.fillBirthdaySelector();
    
    this.renderSelectboxes($('#ddlMonth, #ddlYear, #ddlDay'));
    this.routeFinishButton();
    this.loadStep(1);
  },
  
  routeFinishButton: function(){
    var href = $('#contest-3x4-finish').attr('href') + $('#sendToFriend .culture').text();
    $('#contest-3x4-finish').attr('href', href); 
  },
  
  fillBirthdaySelector: function(){
    var container = this.container;
    
    // years
    var now = new Date();
    for(i = now.getFullYear(); i >= 1900 ; i--)
    {
      var opt = $('<option value="' + i + '">' + i + '</option>');
      $('#ddlYear', container).append(opt);
    }
    
    // months
    for(i = 1; i <= 12 ; i++)
    {
      var opt = $('<option value="' + i + '">' + i + '</option>');
      $('#ddlMonth', container).append(opt);
    }
    
    //days
    for(i = 1; i <= 31; i++)
    {
      var opt = $('<option value="' + i + '">' + i + '</option>');
      $('#ddlDay', container).append(opt);
    }
  },
  
  showStep: function(step){
    $('.contest .step').hide();
    $('.contest #step'+step).show();
  },
  
  loadStep: function(step)
  {
    var cts = this;
    var currentStep = step-1;
    var currentStepEl = $('#step' + currentStep, cts.container);
    var stepEl = $('#step' + step, cts.container);
    var isFinal = stepEl.hasClass('final');
    
    if(currentStep > 0)
    {
      if(isFinal)
      {
        // get fields
        var sBirthday = $('#ddlDay').val() + '/' + $('#ddlMonth').val() + '/' + $('#ddlYear').val();
        var args = {
          firstname: $("#txtFirstname").val(),
          name: $("#txtName").val(),
          birthday: sBirthday,
          address: $('#txtAddress').val(),
          postalcode: $('#txtPostal').val(),
          city: $('#txtCity').val(),
          email: $('#txtEmail').val(),
          phone: $('#txtTel').val(),
          code: $('#txtCode').val(),
          newsletter: ($('#chkNewsletter:checked').length == 1) ? "true" : "false",
          answer: $('#rblQuestion input:checked').val(),
          bonus: $('#txtBonus').val()
        };
        
        // save (post) data
        var cult = $('#sendToFriend .culture').text();
        $.ajax({
          url: "/base/Contests/Save/" + cult,
          dataType: "json",
          data: args,
          type: 'POST', 
          success: function(data){
            // show next step
            cts.showStep(step);
          },
          error: function(data){
            // something went wrong saving your profile mate try again.
            alert('failed to save your entry please try again');
            
          }
        });   
      }
    }
    if(!isFinal)
    {
      stepEl.find('.btnConfirm').unbind('click').click(function(){
        $(this).blur();
        if(currentStep == 0 && !$('#contest-3x4-continue').hasClass('enabled'))
        {
          return false;
        }
        
        if(cts.isValidStep(stepEl) || !cts.config.useValidation)
        {
          cts.loadStep(step+1);
        }
        
        return false;
      });
    }
    
    stepEl.find('#txtCode').unbind('blur').blur(function(){
      var txt = $(this);
      if(txt.val() != "")
      {
        // get fields
        var args = {
          code: txt.val()
        };
        
        // save (post) data
        var cult = $('#sendToFriend .culture').text();
        $.ajax({
          url: "/base/Contests/IsValidCode/" + cult,
          dataType: "json",
          data: args,
          type: 'POST', 
          success: function(data){
            if(data.Status == 200)
            {
              stepEl.find('.btnConfirm').addClass('enabled');
              stepEl.find('#txtCode').removeClass('error');
            }
            if(data.Status == 500)
            {
              stepEl.find('#txtCode').addClass('error');
            }
          },
          error: function(data){
            // something went wrong saving your profile mate try again.
            //console.warn(data);
            
          }
        });
      }
    });
      
    if(!isFinal)
    {
      this.showStep(step);
    }
  },
  
  isValidStep: function(step){
    var valid = true;
    var cts = this;
    cts.clearValidation(step);
    
    // required validation...
    $('.required', step).each(function(){
      var el = $(this);
      var type = cts.config.getType(el);
      var types = cts.config.fieldTypes;
      
      switch(type)
      {
        case types.txt:
          if(el.val() == "")
          {
            el.addClass('error');
          }
          break;
        case types.rbt:
          // no validation on radio's atm.
          break;
        case types.chk:
          // no validation on checkbox atm.
          break;
        case types.sel:
          if(el.val() == $('option:first', el).attr('value'))
          {
            el.addClass('error');
          }
          break;
        case types.selgroup:
          var selects = $('select', el);
          
          for(j = 0; j < selects.length; j++)
          {
            var s = $(selects[j]);
            if(s.val() == $('option:first', s).attr('value'))
            {
              el.addClass('error');
            }
          }
          break;
        case types.rbgroup:
          var inpts = $('input[type="radio"]', el);
          if(inpts.length > 0)
          {
            var nm = $(inpts[0]).attr('name');
            var l = $('input:radio[name=' + nm + ']:checked', el).length;
            
            if(l==0){
              el.addClass('error');
            }
          }
          break;
        default:
          //console.warn('field skipped due to unknown field type', el);
      }
    });
    
    // validation match number
    $('.matchnumber', step).each(function(){
      var el = $(this);
      var val = el.val();
      var re = new RegExp("^[0-9]+$");
      if(val.match(re) == null)
      {
        el.addClass('error');
      }
    });
     
    // validation match all but numbers
    $('.matchallbutnumber', step).each(function(){
      var el = $(this);
      var val = el.val();
      var re = /^\D+$/;
      if(val.match(re) == null)
      {
        el.addClass('error');
      }
    });
     
    // validation match postal codes
    $('.matchpostalcode', step).each(function(){
      var el = $(this);
      var val = el.val();
      var re = /^\d{4}$/;
      if(val.match(re) == null)
      {
        el.addClass('error');
      }
    });
    
    // validation match email
    $('.matchemail', step).each(function(){
      var el = $(this);
      var val = el.val();
      var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
      if(val.match(re) == null)
      {
        el.addClass('error');
      }
    });
    
    valid = $('.error', step).length == 0;
    
    $('.validationsummary', step).toggle(!valid);
    return valid;
  },
  
  clearValidation: function(step) {
    $('.validationsummary', step).hide();
    
    $('.error', step).removeClass('error');
  },
  
  renderSelectboxes: function(els){
    $(els).filter('.selectbox').each(function(){
      $(this).selectBox();
    });
  }
};

