var error_msg = 'Wypełnij zaznaczone pola opowiednimi danymi.';
var Fields = [
   ['f_cours', 'NotEmpty', true],
   ['f_firstname', 'String', true],
   ['f_lastname', 'String', true],
   //['f_born_data', 'Date', true],
   ['f_born_data_year', 'DateYear', true],
   ['f_born_data_day', 'DateDay', true],
   ['f_born_data_month', 'DateMonth', true],
   ['f_born_city','String',false],
   ['f_born_state','String',false],
   ['f_born_country','String',false],
   ['f_school','String',false],
   ['f_finishschool','String',false],
   ['f_job','String',false],
   ['f_camera','String',false],



   ['f_reg_postcode', 'PostCode', true],
   ['f_reg_city', 'String', true],
   ['f_reg_state', 'String', true],
   ['f_reg_street', 'String', true],
   ['f_reg_home', 'Number', true],
   ['f_reg_plate', 'Number', false],
   ['f_reg_phone', 'Number', true],
   ['f_reg_email', 'Email', true],
   ['f_mail_postcode', 'PostCode', true],
   ['f_mail_city', 'String', true],
   ['f_mail_state', 'String', true],
   ['f_mail_street', 'String', true],
   ['f_mail_home', 'Number', true],
   ['f_mail_plate', 'Number', false],
   ['f_mail_phone', 'Number', true],
   ['f_mail_email', 'Email', true],
   ['f_bill_firn_name', 'String', false],
   ['f_bill_street', 'String', false],
   ['f_bill_postcode', 'PostCode', false],
   ['f_bill_city', 'String', false],
   ['f_bill_nip', 'NIP', false],
   ['f_agree','NotEmpty',true]
];
var Paterns = {
   'Date': 'rrrr-mm-dd',
   'PostCode': 'xx-xxx'
}

var Form = {
   init: function(e){
      this.content = $('content');
      this.dForm = $('f_propagation');
      this.bSubmit = $('f_submit');

      this.labels = {};
      this.items = {};
      this.findElements();
      this.prepare();
   },
   prepare: function(){

      //dla dzienny i wieczorowych czesc o wku
      var el = $('f_cours');
      if (el) {
         dc.Event.addListener(el, 'change', this.toggleCourse, this);
         this.toggleCourse();
      }
      //vat
      el = $('f_bill');
      if (el) {
         dc.Event.addListener(el, 'click', this.toggleBill, this);
         this.toggleBill();
      }
      //copy adress
      el = $('f_copy_adres');
      if (el) {
         var a = document.createElement('a');
         a.innerHTML = '(przepisz)';
         a.setAttribute('href', '#back');
         el.appendChild(a);
         dc.Event.addListener(a, 'click', this.copyAdress,this);
      }
   },
   copyAdress: function(){
      if (!this.copy) {
         this.copy = {};
         var f, id;
         var from = 'f_reg', to = 'f_mail';


         for (var i = 0; i < Fields.length; ++i) {
            f = Fields[i];
            id = f[0];
            //to copy
            if (id.indexOf(from) > -1 || id.indexOf(to) > -1) {
               var p = id.lastIndexOf('_');
               if (p > -1) {
                  var sid = id.substr(p + 1);
                  if (sid) {
                     if (!this.copy[sid])
                        this.copy[sid] = {};
                     this.copy[sid][id.indexOf(from) > -1 ? 'from' : 'to'] = $(id);
                  }
               }
            }
         }
      }
      var f,t;
      for(var i in this.copy){
         f = this.copy[i].from;
         t = this.copy[i].to;
         if(f && t){
            t.value = f.value;
         }
      }
   },
   toggleCourse: function(){
      //var el = $('f_cours');
      //var army = $('f_army_part');
      //if (el)// && army)
      //   var v = el.options[el.selectedIndex].value;
      //army.style.display = (v == 0 || v > 2) ? 'none' : 'block';
   },
   toggleBill: function(){
      var el = $('f_bill');
      var bill = $('f_bill_part');
      if (el && bill) {
         bill.style.display = (el.checked) ? 'block' : 'none';
      }
   },
   findElements: function(){
      var ls = this.content.getElementsByTagName('label');
      var f, el, l;
      for (var i = 0; i < Fields.length; ++i) {
         f = Fields[i];
         el = $(f[0]);
         if (!el)
            continue;
         for (var j = 0; j < ls.length; j++) {
            if (el.parentNode == ls[j].parentNode) {
               l = ls[j];
               break;
            }
         }
         this.items[f[0]] = {
            dom: el,
            type: f[1],
            required: f[2],
            label: {
               dom: l,
               css: l.className
            }
         };

         if (Paterns[f[1]]) {
            var p = Paterns[f[1]];
            if (el.value == '' || (Form.Valid[f[1]] && !Form.Valid[f[1]](el)) )
               el.value = p;

            dc.Event.addListener(el, 'focus', this.focus, el, p);
            dc.Event.addListener(el, 'blur', this.blur, el, p);
         }
      }
   },
   focus: function(e, p){
      if (this.value == p) {
         this.value = '';
      }
   },
   blur: function(e, p){
      if (this.value == '') {
         this.value = p;
      }
   },
   showErrorMsg:function(toggle){
      var err = $('f_error_msg');
      if (err) {
         err.innerHTML = toggle ? error_msg : '';
      }
   },
   check: function(){
      this.showErrorMsg(false);

      var isError = false;
      var it, inp, v;
      for (var i in this.items) {
         it = this.items[i];
         inp = $(it.dom);
         if (!inp)
            continue;
            inp.value = this.trim(inp.value);
         v = inp.value;
         if(v == Paterns[it.type]){
            v = inp.value = '';
         }
         it.label.dom.className = '';
         if (it.required || v != '') {
            if( ! Form.Valid[it.type] || ! Form.Valid[it.type](inp)){
               it.label.dom.className = 'error';
               isError = true;
            }
         }
         if(inp.value == '' && Paterns[it.type]){
            inp.value = Paterns[it.type];
         }
      }
      if (isError) {
         window.scrollTo(0, 0);
      }
      else {
         for (var i in this.items) {
            var it = this.items[i];
            if (Paterns[it.type]) {
               if (it.dom.value == Paterns[it.type]) {
                  it.dom.value = '';
               }
            }
         }
      }
      this.showErrorMsg(isError);
      //return false;
      return !isError;
   },
   trim:function(s){
      return s.replace(/^\s|\s$/,'');
   }
};
Form.Valid = {
   NotEmpty: function(el){
      var tag = el.tagName.toLowerCase();

      switch(tag){
         case 'select': return el.options[el.selectedIndex].value > 0;
         case 'input':
            var s = el.getAttribute('type').toLowerCase();
            if(s == 'checkbox') return el.checked;
         default:
            return el.value != '';
      }
   },
   Email: function(el){
      var email = /^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*\.([A-Za-z]){2,4}$/i;
      return (email.test(el.value));
   },
   PostCode: function(el){
      var ZIP = /^[0-9]{2}[-]{1}[0-9]{3}$/i;
      return (ZIP.test(el.value));
   },
   Date: function(el){
      var date = /^(19|20[0-9]{2})-((?:[0][1-9])|([1][0-2]))-((?:[0-2][0-9])|(?:[3][0-1]))$/;
      var d = el.value.split('-');
      if (d.length == 3) {
         return (/^(19|20)[0-9]{2}$/.test(d[0]) && /^([0][1-9])|([1][1-2])$/.test(d[1]) && /^([0-2][1-9])|([3][0-1])$/.test(d[2]));
      }
      return false;
   },
   DateYear: function(el){
      var d = el.value;
      if (d>1900 && d < 2011) {
         return (/^(19|20)[0-9]{2}$/.test(d));
      }
      return false;
   },
   DateDay: function(el){
      var d = el.value;
      if (d > 0 && d < 32) {
         return (/^(0?[1-9])|([1][1-2])$/.test(d));
      }
      return false;
   },
   DateMonth: function(el){
      var d = el.value;
      if (d > 0 && d < 13) {
         return (/^([0-2]?[1-9])|([3][0-1])$/.test(d));
      }
      return false;
   },
   Int: function(el){
      var integer = /^[0-9]+$/;
      return (integer.test(el.value));
   },
   Number: function(el){
      var num = /^[0-9a-z\.\-\/\ ]+$/;
      return (num.test(el.value));
   },
   String:function(el){
      return true;
      var s = /^[a-zA-ZążśźęćńłóĄŻŚŹĘĆŃÓŁ0-9\;\'\"\,\/\.\ \-]+$/;
      return s.test(el.value);
   },
   NIP:function(el){
      var v = el.value.replace(/[^0-9]/g,'');
      if(v.length == 10){
         v = v.toString().split('');
         if(v.length > 0){
            var m = [6,5,7,2,3,4,5,6,7];
            var s =0;
            for(var i = 0;i< 9;i++){
              s+= m[i] * parseInt(v[i]);
            }
            return (s%11 != 10);
         }
      }
      return false;
   }
};
dc.Event.domReady(function(){
   Form.init();
})
