$(function(){
    all.init();
    myProgress.init();
    $('.login').nyroModal({
        closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton nmReposition closeBtn" title="close"></a>',
        showCloseButton: true
    });
});

var errormsgClass = {
    slim_instruction_keyname:'data-init_instruction',
    slim_instruction_htmltag_keyname:'data-instruction_htmltag',
    slim_instruction_cssclass_keyname:'data-instruction_cssclass',
    init:function(){
        var me=this;
        $('.errormsg').each(function(){
          var $instruct = $(this).find('.slim_instruction').eq(0);
          if($instruct.length){
              $(this).css('opacity',1);//if there is .slim_instruction_keyname, then show .errormsg
              $(this).attr(me.slim_instruction_keyname,$instruct.html())
                     .attr(me.slim_instruction_htmltag_keyname,'span')//TODO dynamic getter
                     .attr(me.slim_instruction_cssclass_keyname,'slim_instruction');//TODO dynamic getter
        }
        });
    }
};
var all = {
    cloudPosition: 0,
    cloudPosition2: 250,
    init: function(){
        //
        this.moveCloud();
        //
        $('.element_slim_datepicker img').click(function(){
          $(this).siblings('input').datepicker('show');
        });
        //errormsg init
        errormsgClass.init();

    },
    define_unitType:function(key){
      var o = {e:'eng',m:'met'};
      return o[key];
    },

    /*
    @params String ui
    @return Boolean
    */
    validationRule:function(ui){
      switch(ui){
        case'username':
          break;
        case'password':
          break;
        case'':
          break;
      }

    },
    /*
     * @return Object
    */
    calcIdealWeight:function(unitType,height1,height2){
        var idealbmi = {min:18.5,max:24.9},
            idealweight = {},
            height,
            inch_per_ft = 12,
            me = this;
        height1 = parseInt(height1);
        height2 = parseInt(height2);

        for(var k in idealbmi){
            var cur_bmi = idealbmi[k];
                if(unitType==me.define_unitType('e')){
                    height=height1*inch_per_ft+height2;
                    var tmp=cur_bmi*height*height/703;
                }else if(unitType==me.define_unitType('m')){
                    height=height2*0.01;//cm to m
                    var tmp=cur_bmi*height*height;
                }
            idealweight[k] = Math.round(tmp);
        }
        return idealweight;
    },
    /*[copy code from registration.js]*/
    errmsg_cssclassname:function(){
      return 'errormsg';
    },
    showFtInRadioValue:function(){
      return'english';
    },
    resetValidAllInput:function(){
        var me=this;
        $('.inputErrStyle').removeClass('inputErrStyle').siblings('.'+me.errmsg_cssclassname()).css('opacity',0);//reset valid ui
        //me.showInputInstruction($(me));
        $("input[type=text], input[type=password]").each(function(){
            $(this).attr("hasError", "");
            all.showInputInstruction($(this));
        })
    },
    /**
     *
     * @param tag, the parent of all input(s)
     * @author V
     * @authro H
     * @reutrn null
     */
    validAllInput:function(tag){
        if(tag){
            tag = tag + " ";
        } else{
            tag = "";
        }
        var me=this,err=0;
        me.resetValidAllInput();
/*end reset*/
  /*try to refactor            for(var k in {'js_required':1,'js_minLength':1,'js_maxLength':1,'js_equal_id':1,'js_onlyNumAndChar':1,'js_firstOnlyChar':1,'js_isemail':1}){
            switch(k){
              case 'js_required':
                break;
            }
          }
*/
	//required  checking...
    $(tag + '[data-js_required=1]').each(function(index,input){
        var $e=$(this),v=$e.val();
        if($e.attr("hasError") == 1){
            return;
        }
        if(!v.length||v<=0){
			me.showInputErrorMsg($e);
	        $e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_requiredtext'));
      		err=1;
      		$e.attr("hasError", 1);
        }
        //else{ me.showInputInstruction($e); }
     });
	 
	//min checking...
	 $( tag + '[data-js_minlength]').each(function(index,input){
		var $e=$(this),v=$e.val();
		if($e.attr("hasError") == 1){
            return;
        }
	 	if(v.length<$e.attr('data-js_minlength')){
			me.showInputErrorMsg($e);
			$e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_minmaxlengthtext')+' is too short');
			err=1;
			$e.attr("hasError", 1);
		}
        //else{ me.showInputInstruction($e); }
	 });

	//max checking...
	 $( tag + '[data-js_maxlength]').each(function(index,input){
		var $e=$(this),v=$e.val();
        if($e.attr("hasError") == 1){
            return;
        }
	 	if(v.length>$e.attr('data-js_maxlength')){
			me.showInputErrorMsg($e);
			$e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_minmaxlengthtext')+' is too long');
			err=1;
			$e.attr("hasError", 1);
		}
    //else{ me.showInputInstruction($e); }

	 });

          //equal checking...
	$( tag + '[data-js_equal_id]').each(function(index,input){
        var $e=$(this),v=$e.val(),
        $target_input=$('#'+$e.attr('data-js_equal_id')),
        target_val=$target_input.val();

        if($e.attr("hasError") == 1){
            return;
        }
        if(target_val!=v){
          me.showInputErrorMsg($e);
	      $e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_equal_idui')+' you entered didn’t match. Please enter again');
	      err=1;
	      $e.attr("hasError", 1);
        }
        //else{ me.showInputInstruction($e); }
          });

	 //no allow special chars checking...
	 $( tag + '[data-js_onlynumandchar=1]').each(function(index,input){
        var $e=$(this),v=$e.val(),
            ary_match=v.match(/[^0-9a-zA-Z_]+/);
            //ary_match=v.match(/[0-9a-z_]+/);
        if($e.attr("hasError") == 1){
            return;
        }
        //if(v.length>0){//if =0, let required handle
     	//if(ary_match[0] && ary_match[0].length!=v.length){
     	if(ary_match){
    		me.showInputErrorMsg($e);
    		$e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_onlynumandchartext')+' contains spaces or invalid characters');
    		err=1;
    		$e.attr("hasError", 1);
    	}
        //else{ me.showInputInstruction($e); }
        //}
	 });


	 //first letter only chars checking...
    $( tag + '[data-js_firstonlychar=1]').each(function(index,input){
        var $e=$(this),v=$e.val(),
            is_match=/^[a-z]/.test(v);
            
        if($e.attr("hasError") == 1){
            return;
        }
        if(!is_match){
            me.showInputErrorMsg($e);
            $e.siblings('.'+me.errmsg_cssclassname()).html($e.attr('data-js_firstonlychartext')+' first char should be a~z');
            err=1;
            $e.attr("hasError", 1);
        }
        //else{ me.showInputInstruction($e); }
    });

          //email checking...
	$( tag + '[data-js_isemail=1]').each(function(index,input){
        var emailpattern=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/,
    		$e=$(this),
    		v=$e.val();
        if($e.attr("hasError") == 1){
            return;
        }
        if(!emailpattern.test(v)){
            me.showInputErrorMsg($e);
            $e.siblings('.'+me.errmsg_cssclassname()).html('Invalid email address');
            err=1;
            $e.attr("hasError", 1);
        }
        //else{ me.showInputInstruction($e); }
    });
    
      if(err){
        //me.clearAllErrorMsg();
        return false;
      }else{
        return true;
      }
    },
    /*[copy code from registration.js]*/
    clearAllErrorMsg:function(){
      var me=this;
      setTimeout(function(){
        $('.'+me.errmsg_cssclassname()).fadeOut('normal',function(){
        $(this).siblings('.inputErrStyle').removeClass('inputErrStyle');
        });
      },2000);
    },
    showInputErrorMsg:function($element){
                     var me=this;
      me.showInputErrorMsgOne($element,me.errmsg_cssclassname());
    },
    /*
    show only one .errormsg by errormsg's customize-cssClassName
    [copy code from registration.js]
    */
    showInputErrorMsgOne:function($element,errormsg_customize_cssclassname){
      var me=this;
      $element.addClass('inputErrStyle').siblings('.'+errormsg_customize_cssclassname).css('opacity','1');
    },
    showInputInstruction:function($element,errormsg_customize_cssclassname){
        var me=this,
            errormsg_customize_cssclassname = errormsg_customize_cssclassname||me.errmsg_cssclassname();//<--bad design, but i have no more road
        var $errormsg = $element.siblings('.'+errormsg_customize_cssclassname).eq(0),
            html_tmp = $errormsg.attr( errormsgClass.slim_instruction_keyname )||'',
            htmltag = $errormsg.attr( errormsgClass.slim_instruction_htmltag_keyname  )||'',
            cssclass = $errormsg.attr(errormsgClass.slim_instruction_cssclass_keyname )||'';
        if(html_tmp){
          $errormsg.html('<'+htmltag+' class="'+cssclass+'">'+html_tmp+'</'+htmltag+'>').css('opacity','1');
        }
    },
    slimNumberInput:function(e){
          /*
          var code = (e.keyCode ? e.keyCode : e.which);
          if((code>=48 && code<=57)||code==8||code==9){
          }else{
            return false;
          }
          */
    },
    /*acceptCodeForNumber:function(code){
      return (code>=48 && code<=57)||code==8||code==9;
    },*/
    getAjaxDateFormat: function(d){
        if(!d){
            d = new Date();
        }
        var d_year = d.getFullYear();
        var d_month = d.getMonth() + 1;
        var d_date = d.getDate();
        return d_year + "-" + d_month + "-" + d_date;
    },
	getAjaxDateFormat02: function(d){
        if(!d){
            d = new Date();
        }
        var d_year = d.getFullYear();
        var d_month = d.getMonth() + 1;
        var d_date = d.getDate();
        return d_year + "/" + d_month + "/" + d_date;
    },
    getDateFormat: function(date){
        if(!date){
            date = new Date();
        }
        var monthArr= ['January','February','March','April','May','June','July','August','September','October','November','December'],
            date_year = date.getFullYear(),
            date_month = monthArr[date.getMonth()],
            date_date = date.getDate();
        return date_month + " " + date_date + ", " + date_year;
    },
    parseTimeObj: function(timeStr){
        var yearStr = timeStr.split("-")[0],
            monthStr = timeStr.split("-")[1] - 1,
            dateStr = timeStr.split("-")[2];
            d = new Date();
        d.setFullYear(yearStr);
        d.setMonth(monthStr);
        d.setDate(dateStr);
        return d;
    },
	parseTimeZoneObj: function(){
		var timeStr = $(".todayDate").text();
		if(timeStr){
			var yearStr = timeStr.split("/")[2],
            	monthStr = timeStr.split("/")[0] - 1,
            	dateStr = timeStr.split("/")[1],
	            d = new Date();
			d.setFullYear(yearStr);
			d.setMonth(monthStr);
			d.setDate(dateStr);
		} else {
			d = new Date();
		}       
        return d;
    },
	addDay:function(d, muchDay){
		var timeData = d.getTime() + 86400000 * muchDay;
		d.setTime(timeData)
		return d;
	},
    moveCloud: function(){
        this.cloudPosition++;
        this.cloudPosition2++;
        $(".cloud").css('backgroundPosition', this.cloudPosition + "px" + " 0px");
        $(".cloud2").css('backgroundPosition', this.cloudPosition2 + "px" + " 0px");
        setTimeout("all.moveCloud();", 100);
    }

}
var searchObj = {
    searchSubmit: function(){
        if($("#uid").val() == "0"){
            cover.add(2);
        } else{
            $("#FoodSearchText02").val($("#searchWord").val());
            $('#FoodFoodsearchForm02').submit();
        }
    },
    searchSubmit01: function(){
        $('#FoodFoodsearchForm').submit();
    }
}
var myProgress = {
    init:function(){
        var d = new Date(),
            tDate = d.getDate(),
            tMonth = d.getMonth() + 1;
        if(tDate < 10){
            tDate = "0" + tDate;
        }
        if(tMonth < 10){
            tMonth = "0" + tMonth;
        }
        $(".todayMonth").text(tMonth);
        $(".todayDay").text(tDate);
        $(".todayYear").text(d.getFullYear());
        
        if($(".myProgressDiv")[0]){
			if($(".todayDate").text()){
				var dateArr = $(".todayDate").text().split("/"),
					date = dateArr[2] + "-" +  dateArr[0] + "-" + dateArr[1];
			} else {
				var d = new Date(),
				date = (d.getMonth()+1) + "-" +  d.getDate() + "-" + d.getFullYear();
			}
            $.ajax({
                url: '/users/totalcalories',
                type: 'POST',
                data: {
                    date: date
                },
                dataType: 'json',
                error: function(jqXHR, textStatus, errorThrown){
                    alert("error: " + textStatus)
                },
                success: function(data){
                    if(data.error){
                        if(data.error != 'parsererror') alert("error: " + data.error);
                        return;
                    }
                    $("#todayTotal").text(data.totalcalories);
                    myProgress.calProgress();
                }
            });
        }
    },
    calProgress: function(){
        var targetW = $("#targetWei").text();
        var todayTotal = $("#todayTotal").text();
        var percent = Math.round(todayTotal /targetW * 100);
        $("#percent").text(percent);
        var progressGrid = Math.round(percent / 10) * 14;
        $(".progressDark").css('backgroundPosition', progressGrid + "px 0");
    }
}

function AjaxSelectBox(v){
 var dl = v.parentNode;
 var dd = dl.getElementsByTagName("dd")[0];
 var dt = dl.getElementsByTagName("dt")[0];
 var lis = dl.getElementsByTagName("li");
 var html = '',
     li_attr_valuekey='data-valueofkey';

 for(var y=0; y<lis.length; y++){
  html += '<li onclick="SetSelectInput(this,1);" onmouseout="SetSelectInput(this,2);" onmousemove="SetSelectInput(this,3);" data-valueofkey="'+lis[y].getAttribute('data-valueofkey')+'">' + lis[y].innerHTML + '</li>';
 }
 dl.getElementsByTagName("ul")[0].innerHTML = html;
 dd.style.display = "block";
 
 
 dl.onmouseout = function() {
	dd.style.display = "none";
	//dl.onmouseover = function() {comboboxHideControl.hide(dd);$('.suggest').after('123')}
 }
 
 dd.onmouseover = function() {comboboxHideControl.cancelHide(); dd.style.display = "block";}
 dd.onmouseout = function() { 
	 comboboxHideControl.hide(dd); 
	 //cleanBubbleEvent();
 }
 
 
 
}


function SetSelectInput(v,flag){
 var dl = v.parentNode;
 while(dl.nodeName != 'DL'){
  dl = dl.parentNode;
 }
 var input = dl.getElementsByTagName("input")[0];
 var dd = dl.getElementsByTagName("dd")[0];
 var dt = dl.getElementsByTagName("dt")[0];

	dd.onmouseover = function() {
		comboboxHideControl.cancelHide();
		dd.style.display = "block";
	}
	v.onmouseover = function() {
		dd.style.display = "block";
	}
	dl.onmouseout = function() {
//			dd.style.display = "none"
	}
	dd.onmouseout = function(e) {
//		dd.style.display = "none";
		comboboxHideControl.hide(dd);
//		cleanBubbleEvent();
	}

 if(flag == 1){
    //alert(input.class)
  //input.setAttribute("value", "123456")
  input.value = v.attributes.getNamedItem("data-valueofkey").value;
  var span = dt.getElementsByTagName("span")[0];
  if( span ){
	  span.innerHTML = v.innerHTML;
  }
  
  dd.style.display = "none";
 } else if(flag == 2){
  v.className = 'out'; return;
 } else{
  v.className = 'move'; return;
 }
}



//temp 未整理
var isIE = navigator.userAgent.search("MSIE") > -1; 
var isIE7 = navigator.userAgent.search("MSIE 7") > -1; 
var isFirefox = navigator.userAgent.search("Firefox") > -1; 
var isOpera = navigator.userAgent.search("Opera") > -1; 
var isSafari = navigator.userAgent.search("Safari") > -1;



/**
 * 取消停止事件上傳方式改用定時
 */
var comboboxHideControl = {
	timeoutFunction : null
	,
	tempobj : null
	,
	hide : function(obj){
		comboboxHideControl.tempobj = obj;
		comboboxHideControl.timeoutFunction = setTimeout("comboboxHideControl.hideTimeout(comboboxHideControl.tempobj)",700);
	}
	,
	cancelHide : function(){
		//alert(1)
		clearTimeout(comboboxHideControl.timeoutFunction);
	}
	,
	hideTimeout : function(obj){
		$(obj).hide();
		/*
		$(obj).parents('dl').mouseover(function(){
			//comboboxHideControl.hide(dd);
			this.hide();
		})
		*/
		// dl.onmouseover = function() {comboboxHideControl.hide(dd);$('.suggest').after('123')}
	}
}



/**
 * 清除事件繼續傳出
 */
function cleanBubbleEvent(){
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
	


/**
 * 單位換算
 * ex: 
 * a = mathUnit.inToCm(100);
 * a = Math.round(mathUnit.cmToIn(100)); 	//四捨五入
 * ft = Math.floor(mathUnit.inToFt(100));	//無條件去除小數
 */
var mathUnit = {
	cmToIn : function( val ){
		//1cm = 0.3937in
		var h = isNaN(val)?0:val;
		h = h * 0.3937;
		return h;
	}
	,
	ftToIin : function( val ){
		//12in = 1ft
		var h = isNaN(val)?0:val;
		h = h * 12;
		return h;
	}
	,
	inToFt : function( val ){
		//12in = 1ft
		var h = isNaN(val)?0:val;
		h = h / 12;
		return h;
	}
	,
	inToCm : function( val ){
		//1in = 2.54cm
		var h = isNaN(val)?0:val;
		h = h * 2.54;
		return h;
	}
	,
	kgToLbs : function( val ){
		//1 kg = 2.20462 lbs
		var w = isNaN(val)?0:val; 
		w = w * 2.20462;
		return w;
	}
	,
	lbsToKg : function( val ){
		//1 lbs = 0.45359 kg
		var w = isNaN(val)?0:val; 
		w = w * 0.45359;
		return w;
	}
	
};




