$(function(){
    registration.init();
});
var registration = {
    init: function(){
        this.changeUnit();
        this.datePicker();
      
        //
        //let input only accept number
        $('#fHValue ,#sHValue, #weight, #targetweight').keypress(function(e){

          var code = (e.keyCode ? e.keyCode : e.which);
          if((code>=48 && code<=57)||code==8||code==9){
          }else{
            return false;
          }
        });
        //let datepicker cannot key-in
        $('#datepicker02').keypress(function(e){
            return false;
        });
       var tz_info = jzTimezoneDetector.determine_timezone();//for timezone
        
         $('#tz').val(tz_info.timezone.display2()) ; 

        /*
        $('#datepicker02, #resBirth_slim_datepicker_input').keypress(function(e){
            return false;
        });
        */
        
        //auto calculate birth
        /*$('#resAge').blur(function(){
          var d=new Date(),birth=''+(d.getMonth()+1)+'/'+d.getDate()+'/'+(d.getFullYear()-$(this).val());
          $('#resBirth_slim_datepicker_input').val(birth);
        });*/
        
    },
    /*
     * @deprecated
	*/
    ideal_BMI:function(){
      return 23.9;
    },
    showFtInRadioValue:function(){
      return'english';
    },
    changeUnit: function(){
        $('#fHValue, #sHValue, #weight').val('');//reset input
		all.resetValidAllInput();
    
        this.clearData();
        var measure = $("#resRadio01 input:radio:checked").val();
        var fHeight = $("#fHeight");
        var sHeight = $("#sHeight");
        var weight = $(".resWeight, #ideal_weight_unit");
        if(measure == this.showFtInRadioValue()){
            $('#fHValue, #fHeight').css('display','inline');
            fHeight.text("ft");
            sHeight.text("in");
            weight.text("lbs");
        } else {
            $('#fHValue, #fHeight').css('display','none');
            sHeight.text("cm");
            weight.text("kg");
        }
    },
    clearData: function(){
        //$('table input[type=text]').val('');
    },
    
    datePicker: function(){
        var d = new Date();
        /*
        $( "#resBirth_slim_datepicker_input" ).datepicker({
            dateFormat: 'mm/dd/yy',
            showButtonPanel: true,
            changeMonth: true,
            changeYear: true,
            yearRange: '1960:c',
            maxDate: d,
            defaultDate: '01/01/1980'

        });
        */
        $( "#datepicker02" ).datepicker({
            dateFormat: 'mm/dd/yy',
            showButtonPanel: true,
            changeMonth: true,
            changeYear: true,
            minDate: d

        });

        $("#datepickerBg").click(function() {
           $("#datepicker02").datepicker('show');
        });
        /*
        $("#datepickerBg").click(function() {
           $("#datepicker02").datepicker('show');
        });

        */
    },
    showALD: function(){
        if($(".actLevelAns")[0]){
            $(".actLevelAns").toggle();
        } else{
            var htmlCode = "<div class='actLevelAns'><a onclick='registration.closeALD();' class='closeBtn'></a><b class='actTitle'>Activity Level</b><div class='actLevelAnsInside'>"+
                            "<p>Little or no exercise</p>You work in an office and sit at your desk for most of the day. Or you sit at home and not walk around frequently. You don't do much exercise." +
                            "<br /><br /><p>Lightly active (exercise 1 to 3 days a week)</p>Your job requires you on your feet a lot, like teaching, childcare, retail sales. At home you occasionally do house chores like gardening, cleaning, vacuuming etc. You engage in low impact activities like walking, bowling, billiards, ballroom dancing once a while." +
                            "<br /><br /><p>Moderately active (exercise 3 to 5 days a week)</p>Your job demands lots of physical activities like delivery, waiting tables, etc. Or you spend more than 6 hours on housework. Or you routinely participate in higher impact activities like jogging, swimming, cycling, weight lifting, aerobics, etc." +
                            "<br /><br /><p>Very active (exercise 6 to 7 days a week)</p>You have a very labor intensive job - like construction worker or dock worker. You are extremely active at home performing heavy duty tasks. You're into extremely high impact activities like rock climbing, surfing, tennis, running, ballet dancing etc.</div></div>";
            $("#footer02").append(htmlCode);

            var mouse_is_inside03 = false;
            $('.actLevelAns').hover(function(){
                mouse_is_inside03=true;
            }, function(){
                mouse_is_inside03=false;
            });
            $("body").mousedown(function(){
                if(! mouse_is_inside03) {registration.closeALD()};
            });
            
        }
    },
    errmsg_cssclassname:function(){
      return 'errormsg';
    },
    closeALD: function(){
        $(".actLevelAns").hide();
    },
    registrationClearAllErr:function(){
      var me=this;  
      setTimeout(function(){
        $('.'+me.errmsg_cssclassname()).animate({opacity:0}).siblings('input').removeClass('inputErrStyle');
      },2000);
    },
    /*
    show every siblings() .errormsg 
    */
    showInputErrorMsg:function($element){
      var me=this;
      me.showInputErrorMsgOne($element,me.errmsg_cssclassname());
    },
    /*
    show only one .errormsg by errormsg's customize-cssClassName
    */
    showInputErrorMsgOne:function($element,errormsg_customize_cssclassname){
      var me=this;
      $element.addClass('inputErrStyle').parents("tr").find('.'+errormsg_customize_cssclassname).css('opacity','1');
      //$element.addClass('inputErrStyle').siblings('.'+errormsg_customize_cssclassname).css('opacity','1');
    },
    changePage: function(elm){
        var pageNum = Number($(elm).attr("value"));
		//alert(pageNum);
        var nextNum = pageNum + 1;
        //valid START
        var me=this,err;
        switch(pageNum){
            case 1:
                all.resetValidAllInput();
                var v='',$e,o={};
                if($('input[name=resRadio01]:checked').val()!=me.showFtInRadioValue()){
          		    o = {/*'resBirth_slim_datepicker_input':1,*/'sHValue':1,'weight':1};
          	    }else{
          		    o={/*'resBirth_slim_datepicker_input':1,*/'sHValue':1,'fHValue':1,'weight':1};
          	    }
                for(var k in o){
                    $e=$('#' + k);
                    v=$e.val();
                    if(!v.length||v<=0){
						if($e.attr("id") == 'sHValue' && $('#fHValue').val()){
							continue;
						}
                        me.showInputErrorMsg($e);
                        err=1;
                    }
                }
				
                break;
            case 2:
                /*
		        all.resetValidAllInput();

     		    var $e='',v='';

                $e=$('#targetweight'),v=$e.val();
                if(!v.length||v<=0){
                  me.showInputErrorMsg($e);
                  err=1;
                }

                $e=$('#datepicker02'),v=$e.val();
                if(!$e.val()){
                  me.showInputErrorMsg($e);
                  err=1;
                }
                */
                //ideal checking...
                //$('#targetweight').each(function(index,input){
                  //var $e=$('#targetweight'),v=$e.val();

                //});

                break;
        }
        if(err){
          //dont auto hide: me.registrationClearAllErr();
          return false;
        }
        //valid END
        $("#reaQu0" + pageNum).hide();
        $("#reaQu0" + nextNum).show();
        
        if(nextNum==2){
          //update idae weight
          var ideal_weight = '';
          if($('input[name=resRadio01]:checked').val()==me.showFtInRadioValue()){
            var inches_per_ft=12
                BMI_INCHES_CONVERT_CONST=703,
                inches = parseInt($('#fHValue').val())*inches_per_ft + parseInt($('#sHValue').val());
            ideal_weight=parseFloat(me.ideal_BMI()*inches*inches/BMI_INCHES_CONVERT_CONST);
          }else{
            var m=$('#sHValue').val()*0.01;
            ideal_weight=me.ideal_BMI()*m*m;
          }
          ideal_weight=Math.round(ideal_weight);
	  var _unitType=($('input[name=resRadio01]:checked').val()==me.showFtInRadioValue())?all.define_unitType('e'):all.define_unitType('m');
	  var _h1=parseInt($('#fHValue').val()),
	      _h2=parseInt($('#sHValue').val()),
	      weight=all.calcIdealWeight(_unitType,_h1,_h2);
          $('#ideal_weight').html(weight['min']+' ~ '+weight['max']);
        }
    },
    defaultErrormsgText4Required:function(){
					 return'Required field cannot be left blank';
    },
    checkSubmit: function(){
		var me=this;
		//valid START
		if(!all.validAllInput()){return false;}
		//all.validAllInput();
		 //return false...
		//valid END
        var d = new Date();
        d.setDate($("#birth_day").val());
        d.setMonth($("#birth_month").val() - 1);
        d.setFullYear($("#birth_year").val());
        //step1
        var $gender = $('input[name=resRadio02]:checked').val();
        var $weight = $('#weight').val();
        var $unit = $('input[name=resRadio01]:checked').val();
        var $fHValue = $('#fHValue').val();
        var $sHValue = $('#sHValue').val();
        //var $birth = $('#resBirth_slim_datepicker_input').val();
        var $birth = $("#birth_month").val() + "/" + $("#birth_day").val() + "/" + $("#birth_year").val();
        
        //step2
        var $targetweight = $('#targetweight').val();
		if($targetweight == '') $targetweight = $weight-1;
        var $reach_by = $('#datepicker02').val();
		
		var d= all.addDay(new Date(), 1),
			m = d.getMonth() + 1,
			nd = m + "/" + d.getDate() + "/" + d.getFullYear();
		
		if($reach_by == '') $reach_by = nd;
        //step3
    
        var $username = $('#resUsername').val();
        var $password = $('#resPassword').val();
        //var $checkcode = $('#check_code').val();
        var $activitylevel = $('#activitylevel').val();
    
        var $email = $('#email').val();

        var $tz= $('#tz').val();
	
    

        var d = new Date();
	
            var month=d.getMonth()+1; 
	
            var $computer_date = d.getFullYear()+'-'+month+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();

        var inch_per_ft=12;

	
        var $height=($unit==me.showFtInRadioValue())?$fHValue*inch_per_ft+parseInt($sHValue):$sHValue;
        
        /*
        alert("gender: " + $gender + ",weight: " + $weight + ",measurement_units: " + $unit + ",target_weight: " + $targetweight + ",activity_level: " + $activitylevel +
                ",username: " + $username + " ,password: " + $password + " ,email: " + $email + " ,computer_date: " + $computer_date +
                " ,height:" + $height + ",reach_date: " + $reach_by + ",birth_date: " + $birth)
        */
        $.ajaxSetup ({
            cache: false
        });

        $.ajax({
            url: '/users/register',
            type: 'POST',
            data:{data:{User:{gender:$gender,weight:$weight,measurement_units:$unit,target_weight:$targetweight,activity_level:$activitylevel,username:$username,password:$password,email:$email,tz:$tz/*,check_code:$checkcode*/,computer_date:$computer_date,height:$height,reach_date:$reach_by,birth_date:$birth}}
                
            },
            dataType: 'json',
            timeout: 5000,
            error: function(jqXHR, textStatus, errorThrown){
                //alert("error:" + textStatus);
				//alert(1)
            },
            success: function(data, textStatus, jqXHR){
				//alert(123)
                if(!data.error){
                    location=data.url;
                } else {
                    switch(data.error){
                      case 'username':
							//me.showInputErrorMsgOne($('#username'),'errormsg-js-beused');
							var $e=$('#resUsername');
							$e.siblings('.'+me.errmsg_cssclassname()).html('This username is taken. Please choose another one');
							break;
                      case 'email':
							//me.showInputErrorMsgOne($('#username'),'errormsg-js-beused');
							var $e=$('#email');
							$e.siblings('.'+me.errmsg_cssclassname()).html('This email is taken. Please choose another one');
                      break;
                      /*
                      case 'checkcode':
                      //me.showInputErrorMsgOne($('#username'),'errormsg-js-captcha');
		      var $e=$('#check_code');
	      $e.siblings('.'+me.errmsg_cssclassname()).html(ERRORMSG_CHECKCODE_INCORRECT);
                      break;
                      */
                    }
               me.showInputErrorMsg($e);
                }

                
            }
        });
        $.ajaxSetup ({
            cache: false
        });
    }
};


