Useful Javascript Functions

function round_number(n){
	return Math.round(n*100) / 100;
}

function isset(v){
  if(v == null) return false;
  if(v == '') return false;

  return true;
}

function set_value(field_name, value, $container){
	if(typeof $container == 'undefined'){
		var $field = $('[name="' + field_name + '"]');
	}else{
		var $field = $container.find('[name="' + field_name + '"]');
	}

	if(field_name == 'stop_restrict'){
		//console.log($field[0]);
	}

	var common_types = ['text', 'password', 'hidden', 'email', 'tel', 'number', 'textarea', 'select-one', 'date'];

	if($field.length > 0){
		var type = $field[0].type;

		if($.inArray(type, common_types) != -1){
			$field.val(value);
		}else if(type == 'radio'){
			$field.each(function(index){
				var $this = $(this);
				if($this.val() == String(value)){
					$this.prop('checked', true);
				}else{
					$this.prop('checked', false);
				}
			});
		}else if(type == 'checkbox'){
			if($.isArray(value) == false){
				var arr = [];
				arr.push(value);
				value = arr;
			}

			//Conver values in the array to string to make sure the comparison is correct.
			for(i = 0; i < value.length; i++){
				value[i] = String(value[i]);
			}

			$field.each(function(index){
				var $this = $(this);

				//Debug
				if(field_name == 'stop_restrict' && false){
					//console.log($this.val());
					//console.log(value);
					//console.log($.inArray($this.val(), value));
				}

				if($.inArray(String($this.val()), value) > -1){
					$this.prop('checked', true);
				}else{
					$this.prop('checked', false);
				}
			});
		}
	}
}

function get_value(field_name, $container, default_value, debug){
	if(typeof $container == 'undefined'){
		var $field = $('[name="' + field_name + '"]');
	}else{
		var $field = $container.find('[name="' + field_name + '"]');
	}

	if($field.length == 0){
		return null;
	}

	var type = $field[0].type;

	if(type == 'text' 
		|| type == 'password' 
		|| type == 'hidden' 
		|| type == 'email' 
		|| type == 'tel' 
		|| type == 'number' 
		|| type == 'textarea' 
	){
		return $field.val();
	}else if(type == 'radio'){
		return checked_value(field_name, $container, default_value, debug);
	}else if(type == 'checkbox'){
		return checked_values(field_name, $container, default_value, debug);
	}else if(type == 'select' || type == 'select-one'){
		return $field.val();
	}
}

function checked_value(field_name, $container){
	if(typeof $container == 'undefined'){
		var $field = $('[name="' + field_name + '"]:checked');
	}else{
		var $field = $container.find('[name="' + field_name + '"]:checked');
	}

	if(typeof default_value == 'undefined'){
		default_value = null;
	}

	if(typeof debug == 'undefined'){
		debug = false;
	}
	
	if($field.length == 0){
		return null;
	}

	return $field.val();
}

function checked_values(field_name, $container, default_value, debug){
	var checked = [];

	if(typeof default_value == 'undefined'){
		default_value = null;
	}

	if(typeof debug == 'undefined'){
		debug = false;
	}

	if(typeof $container == 'undefined'){
		var $fields = $('[name="' + field_name + '"]');
	}else{
		var $fields = $container.find('[name="' + field_name + '"]');
	}

	if(debug == true){
		console.log($fields);
	}

	//單一選項,通常是開啟或關閉
	if($fields.length == 1 && $fields.hasClass('single-value')){
		if($fields.prop('checked') == true){
			return $fields.val();
		}else{
			return default_value;
		}
	}

	$fields.each(function(index){
		var $this = $(this);
		if($this.prop('checked') == true){
			checked.push($(this).val());
		}
	});

	return checked;
}

function select_default($e){
	if($e.val() != '' && $e.val() != null){
		return false;
	}

	var default_value = $e.attr('data-value');
	if(typeof default_value == 'undefined' || default_value == ''){
		return false;
	}

	$e.val(default_value);
	$e.trigger('change');
}

function disable_field(field_name, $container, disable){
	if(typeof $container == 'undefined'){
		var $field = $('[name="' + field_name + '"]');
	}else{
		var $field = $container.find('[name="' + field_name + '"]');
	}

	$field.prop('disabled', disable);
}

function loading(){
	$('body').loading({
        message: '處理中, 請稍侯...'
    });
}

function loaded(){
	$('body').loading('stop');
}

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

function makeNumber() {
  var text = "";
  var possible = "0123456789";

  for (var i = 0; i < 1; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

//Error handler for normal ajax response
function show_response_error(errors){
    var str = '';
    //console.log(errors);
 
    for(var key in errors){
        var err = errors[key];
        str += err[0] + '\n';
    }
    
    alert(str);
}


//Error handler for errors that laravel request created.
function show_request_error($form, errors){
    var str = '';
    //console.log(errors);
 
    for(var key in errors){
        var err = errors[key];
        //str += err[0] + '\n';
        var $el = $form.find('[name="' + key + '"]');
        if($el.length != 0){
        	//console.log($el.next('.error').length);
        	if($el.next('.error').length == 0){
        		var $error = $('<div class="error invalid-feedback" style="display:block;">' + err[0] + '</div>');
        		$el.parent().append($error);
        	}else{
        		var $error = $el.next('.error');
        		$error.show();
        	}
        }
    }
}

//https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
function is_object(p){
	if(typeof p === 'object' &&
    	!Array.isArray(p) &&
    	p !== null){
		return true;
	}

	return false;
}

function is_array(p){
	if(Array.isArray(p)){
		return true;
	}

	return false;
}