// FORMAT to MONEY ----------------------------------------------------------------------------
Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

// FORMAT OBJ -------------------------------
function formatObj(obj) {
	$.each(obj, function (index, item) {
		if (typeof(item) == 'string') {
			obj[index] = $.trim(obj[index]);
			if (obj[index] != '') {
				try {obj[index] = decodeURIComponent(obj[index]);}
				catch(err) { console.log(item, err);}
				obj[index] = stripslashes(obj[index]);
				
				var reg = new RegExp("&#37;", "g");
				obj[index] = obj[index].replace(reg, '%');
				
			}
		}
		else if (isValidObj(item)) {
			obj[index] = formatObj(item);
		}
	});
	return obj;
}
// Is Valid Obj/Arr AND not JQuery obj
function isValidObj(obj) {
	return ((typeof(obj) == 'object' || typeof(obj) == 'array') && !(obj instanceof $));
}
// add / strip slashes ---------------------------
function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

// FormToObj
function formToObj (container) {
	var data = {};
	container.find('input').each(function() { // INPUTs
		var input_name = $(this).attr("name");
		if ($(this).attr('type') == 'checkbox') var input_value = ($(this).is(':checked')) ? 1 : 0 ; // if checkbox
		else var input_value = $(this).val();
		data[input_name] = input_value;		
	});
	container.find('select').each(function() { // SELECTs
		var input_name = $(this).attr("name");
		var input_value = $(this).find('option:selected').val();
		if (input_value == 'autre' && $(this).siblings('input').size() > 0) input_value = $(this).siblings('input').val();
		data[input_name] = input_value;	
	});
	container.find('textarea').each(function() {  // TEXTAREAs
		var input_name = $(this).attr("name");
		var input_value = $(this).val();
		data[input_name] = input_value;		
	});
	return (data);
}

// Clear From
function clearForm(form) {
	form.find('select option').removeAttr('selected');
	form.find('select option').removeProp('selected');
	
	form.find('input').each(function() {
		if ($(this).is('[type=number]')) $(this).val(0);
		else $(this).val('');
	});
	form.find('textarea').val('');
	form.find('input[type=checkbox]').prop('checked', false);
}

// Format String for update
function formatStringForUpdate(str) {
	var reg = new RegExp("'", "g");
	str = str.replace(reg, String.fromCharCode(180));
	reg = new RegExp("%", "g");
	str = str.replace(reg, '&#37;');
	str = encodeURIComponent(str);
	
	return str;
}

// Validate Form 
function validateForm(fromBind) {
	fromBind = fromBind || false;
	
	var nbVide = 0;
	$('.required').find('input, select').each(function() {
		var t = $(this);
		if ($.trim(t.val()) == '') {
			nbVide++;
			if (nbVide == 1) {
				$('#error_form').show();
				if (!fromBind) t.focus();
			}
			t.css('border','1px solid #f00');
			
			t.parent().next('td').children('span.vide').show();
			t.parent().next('td').children('span.rempli').hide();	
		}
		else {
			t.css('border','1px solid #5ABA00');
			t.parent().next('td').children('span.vide').hide();
			t.parent().next('td').children('span.rempli').show();	
		}
	});
	
	if (nbVide > 0) return false;
	else {
		$('#error_form').hide();
		return true;
	}
}

function validateFormAnimate(icones) {
	noIcones = icones || false;

	if ($('#error_form').size() < 1) {
		$('.btn-envoyer').after('<span id="error_form"> * Veuillez remplir tous les champs obligatoires. </span>');	
		if (!noIcones) $('.required').append('<td width="20"><span class="vide"></span><span class="rempli"></span> </td>');
		$('.required input').keyup(function() { validateForm(true); });	
		$('.required select').change(function() { validateForm(true); });	
	}
}

// Autocomplete CP
$.fn.autocomplete_cp = function() {
	return this.each(function() {
		$(this).autocomplete({
			source : function(request, response){  
				$.ajax ({
					type: "POST",
					url: "/fr/get_localite.php",
					data : "request="+request.term,
					dataType: "json",
					cache: false,
					success: function(data)	{
						response($.map(data, function(item) {
							var content = item.cp+' - '+item.ville;
							return {
								label: content,
								value: content
							}
						}))
					}
				});
			},
			select : function (event, ui) {
			},
			minLength : 1,
			delay : 500
		});	
	});
};
