//show loading panel
function ShowLoading()
{
  $("#loading").css("height", $(document).height());
  $("#loading").fadeIn();
}
//hide loading panel
function HideLoading()
{
  $("#loading").fadeOut();
}
//return num checked in container table
function CountChecked(tblID)
{
  var num = 0;
  $("#" + tblID + " td input[type='checkbox']").each(function() {
    if(this.checked)
      num++;
  });
  return num;
}
function IsValidUrl(url)
{
  var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  return regexp.test(url);
}
function ShowMessage(title, message, btnOK)
{
  var buttons = {};
  buttons[btnOK] = function(){ $(this).dialog('destroy'); };
  var dialog = $("<div></div>");
  dialog.html(message);
  var $dialog = dialog.dialog({
    title: "<span class='dialog-title'>"+title+"</span>",
		autoOpen: false,
		modal: true,
		buttons: buttons
	});
	//center the button
	$dialog.parent().find("div.ui-dialog-buttonset").css("width","100%");
	$dialog.parent().find("div.ui-dialog-buttonset").css("text-align","center");
	
	$dialog.dialog('open');
	return $dialog;
}
function ShowConfirm(title, message, btnOK, btnCancel, onOK)
{
  var buttons = {};
  buttons[btnOK] = function(){ $(this).dialog('close'); onOK();};
  buttons[btnCancel] = function(){ $(this).dialog('destroy'); };
  var dialog = $("<div></div>");
  dialog.html(message);
  var $dialog = dialog.dialog({
    title: "<span class='dialog-title'>"+title+"</span>",
		autoOpen: false,
		modal: true,
		buttons: buttons
	});
	//center the button
	$dialog.parent().find("div.ui-dialog-buttonset").css("width","100%");
	$dialog.parent().find("div.ui-dialog-buttonset").css("text-align","center");
	
	$dialog.dialog('open');
	return $dialog;
}
//input list of validator objects (using jquery.validate.js plug-in)
function CheckValidations(lstValidators)
{
  var numErrs = 0;
  for(var i=0;i<lstValidators.length;i++)
  {
    var val = lstValidators[i];
    if((val.rules().required && !val.valid()) || 
       (val.val() != "" && !val.valid()))
    {
      numErrs++;
      if(!val.rules().date)//not focus on date field
        val.focus();
    }
  }
  return numErrs;
}
//On Ajax error: just show friendly message to user
//Server side will catch error and write to log file
function OnError()
{
  HideLoading();
  ShowMessage("Error", "Opp!... Please try again later or contact our support!", "OK");
}
/*
 isValidDate
 check if a string is a valid date. The format of date can be specified 
 1- is mm/dd/yyyy
 2- is dd/mm/yyyy
 3 -is mm/dd/yy
 4 -is dd/mm/yy 	
*/
function isValidDate(strDate,intFormatDate)
{
 var m;
 var d;
 var y;
 var i1;
 var i2;
 
 if((intFormatDate!=1)&&(intFormatDate!=2)&&(intFormatDate!=3)&&(intFormatDate!=4)) return false;

 strDate=$.trim(strDate);
 if(strDate=="") return false; 
 i1 = strDate.indexOf("/");
 if(i1<0) return false;
 
 if((intFormatDate==1)||(intFormatDate==3))
 	m = strDate.substring(0,i1);
 else
	d = strDate.substring(0,i1);

  
 i2= strDate.indexOf("/",i1+1)
 if(i2<0) return false;

 if((intFormatDate==1) || (intFormatDate==3))
	d = strDate.substring(i1+1,i2);
 else
	m = strDate.substring(i1+1,i2);
 
 y = strDate.substring(i2+1)

 if((m=="")||(d=="")||(y=="")) return false;
 if((m.length > 2)||(d.length > 2)) return false;
 if((m==0)||(d==0)) return false;
 if(!isPosInt(m))
 	 return false;
 else
 	{	
	 m = parseInt(m);
	 if(m>12) return false;
 	}

 if(!isPosInt(y))
 	 return false;
 else
	{
	 y = parseInt(y)
	 if(y>9999) return false;
	 if((y>=100)&&(y<1900)) return false;
	}

 if(!isPosInt(d))
 	 return false;
 else
	{
	 d = parseInt(d)
	 if((m==1)||(m==3)||(m==5)||(m==7)||(m==8)||(m==10)||(m==12))
		 if(d>31) return false;
 	 if((m==4)||(m==6)||(m==9)||(m==11))
		if(d>30) return false;

	 if(m==2)
		{
		 if(d>29) return false;
		 if((y%4)!=0) // not a leap year
		 	if(d>28) return false;
		}
	}
  return true;
}
/*
 isPosInt
 check if a string is a valid positive integer
*/
function isPosInt(s)
{
 var n;
 n = s.length
 if(n==0) return false;
 for(i=0;i<n;i++)
	if(!isDigit(s.charAt(i))) return false;
 return true;
}
function isDigit(c)
{
if((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9'))
	return true;
else
	return false;
}
/****************************************************/
//User Config Info
UserInfo = new function()
{
  //use for date validation
  this.DateFormatID = 1;//1: mm-dd-yyyy, 2: dd-mm-yyyy
  //use for display datetime in jquery datepicker
  this.DateFormat = "mm/dd/yy";//or dd/mm/yy
  
  //Format decimal number
  this.DecimalFormatOptions = {thousands:',',decimal:'.'};
 
  this.Init = function(dateFormatID, decFormatOptions)
  {
    this.DateFormatID = dateFormatID;
    if(dateFormatID == 1)
      this.DateFormat = "mm/dd/yy";
    else
      this.DateFormat = "dd/mm/yy";
    this.DecimalFormatOptions = decFormatOptions;
  };
  this.FormatDate = function(objDate)
  {
    var month = objDate.getMonth()+ 1;
    month = month.toString().length == 1 ? '0' + month : month;
    var day = objDate.getDate();
    day = day.toString().length == 1 ? '0' + day : day;
    switch(this.DateFormat)
    {
      case "mm/dd/yy":
        return month  + "/" + day + "/" + objDate.getFullYear();
      break;
      case "dd/mm/yy":
        return day + "/" + month + "/" + objDate.getFullYear();
      break;
    }
  };
  this.ParseDate = function(strDate)//date hour:minute
  {
    if(strDate=="") return null;
    var els = strDate.split(' ');
    var date = $.datepicker.parseDate(this.DateFormat,els[0]);
    if(els[1] != null)//hour minute
    {
      date.setHours(els[1].split(':')[0]);
      date.setMinutes(els[1].split(':')[1]);
    }
    //http://bytes.com/topic/asp-net/answers/621170-asp-net-ajax-date-serialization-timezones
    //http://weblogs.asp.net/cprieto/archive/2010/01/03/handling-timezone-information-in-asp-net.aspx
    var browserOffsetInMins = (new Date()).getTimezoneOffset();
    var browserOffsetInHours = browserOffsetInMins/60; //in hours
    
    date.setHours(date.getHours() - browserOffsetInHours);
    date.setMinutes(date.getMinutes() - (browserOffsetInMins%60));
    return date;
  };
  //33,333.88 -> 33333.88(real number)
  this.GetNumberValue = function(str)
  {
    if(str=='') return 0;
    var parts = str.split(this.DecimalFormatOptions.decimal);
    var reg = new RegExp(this.DecimalFormatOptions.thousands == '.'?"\\.":this.DecimalFormatOptions.thousands,"g");
    var returnedVal = parts[0].replace(reg,""); //thousands
    if( parts[1] != null)
        returnedVal = returnedVal + '.' + parts[1];
    return parseFloat(returnedVal);
  }
  //nStr is real number: decimal='.'
  //33333.88 -> 33,333.88
  this.FormatNumber = function(nStr)
  {
    nStr += '';
    nStr = nStr.replace(/,/g,".");//replace "," by "."
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? this.DecimalFormatOptions.decimal + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)){
      x1 = x1.replace(rgx, '$1' + this.DecimalFormatOptions.thousands + '$2');
    }
    return x1 + x2;
  }
};
// -----------------------------------------------------------------------
// excelbrothers.com
// smarter CRM - hook on enter for an element
// requires jQuery
//------------------------------------------------------------------------
(function($) {
  $.fn.OnEnter = function (options) {
    options = $.extend({}, $.fn.OnEnter.defaults, options);
    return this.each(function() {
      $(this).bind('keypress', function(e){
        var code= (e.keyCode ? e.keyCode : e.which);
        if(code == 13){//enter
          if(options.DoEnter){
            return options.DoEnter();
          }
        }
      });
		});
  }
  $.fn.OnEnter.defaults = {
		
	};
})(jQuery);
// -----------------------------------------------------------------------
// excelbrothers.com
// smarter CRM - allow enter digits only
// requires jQuery
//------------------------------------------------------------------------
(function($) {
  $.fn.DigitOnly = function (opts) {
    //options = $.extend({}, $.fn.DigitOnly.defaults, opts);
    var options = $.extend({integer:false}, opts);

    return this.each(function() {
      $(this).bind('keypress', function(e){
        var code= (e.keyCode ? e.keyCode : e.which);//alert(code);
        var condition = code!=8 && code!=0 && code!=37 && code!=39;
        if(!options.integer)
          condition = condition && code!=44 && code!=46 && code!=45;//'.', ',', '-'
        if(condition && (code<48 || code>57))
          return false;
      });
		});
  }
})(jQuery);
// -----------------------------------------------------------------------
// excelbrothers.com
// smarter CRM - month picker
// requires jQuery
//------------------------------------------------------------------------
(function($) {
  $.fn.MonthPicker = function () {
    this.datepicker( {
      changeMonth: true,
      changeYear: true,
      showButtonPanel: false,
      dateFormat: "mm/yy",
      onClose: function(dateText, inst) { 
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
      },
      beforeShow : function(input, inst) {
        
        if ((datestr = $(this).val()).length > 0) {
          year = datestr.substring(datestr.length-4, datestr.length);
          month = parseInt(datestr.substring(0,datestr.length-5)) - 1;
          $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
          $(this).datepicker('setDate', new Date(year, month, 1));
        }
        $(".ui-datepicker-calendar").addClass("hide");
      }
    });
    this.focus(function() {
      $(".ui-datepicker-calendar").hide();    
    });
  }
})(jQuery);
// -----------------------------------------------------------------------
// excelbrothers.com
// smarter CRM - enable maxlength attribute for textarea
//------------------------------------------------------------------------
function EnableMaxLengthForTextArea(obj)
{
    var len = parseInt(obj.getAttribute("maxlength"), 10); 
    if(obj.value.length > len) { 
      obj.value = obj.value.substr(0, len);       
    } 
}
