/* Method :: AJAX */
function Inint_AJAX() {
	try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
	try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
	//alert("XMLHttpRequest not supported");
	return null;
};
/* Method :: AJAX */

/* Method :: Check Message */ 
var browser_detect = {
	init: function () {
		this.browser = this.search_string(this.data_browser) || "An unknown browser";
		this.version = this.search_version(navigator.userAgent) || this.search_version(navigator.appVersion) || "an unknown version";
		this.OS = this.search_string(this.data_os) || "an unknown OS";
	},
	search_string: function(data) {
		for(var i = 0; i < data.length; i++)	{
			var data_string = data[i].string;
			var data_prop = data[i].prop;
			this.versionsearch_string = data[i].version_search || data[i].identity;
			if(data_string) {
				if(data_string.indexOf(data[i].sub_string) != -1)
					return data[i].identity;
			}
			else if(data_prop)
				return data[i].identity;
		}
	},
	search_version: function(data_string) {
		var index = data_string.indexOf(this.versionsearch_string);
		if(index == -1) return;
		return parseFloat(data_string.substring(index + this.versionsearch_string.length + 1));
	},
	data_browser: [{
		string: navigator.userAgent,
		sub_string: "Chrome",
		identity: "Chrome"
	},{
		string: navigator.userAgent,
		sub_string: "OmniWeb",
		version_search: "OmniWeb/",
		identity: "OmniWeb"
	},{
		string: navigator.vendor,
		sub_string: "Apple",
		identity: "Safari",
		version_search: "Version"
	},{
		prop: window.opera,
		identity: "Opera"
	},{
		string: navigator.vendor,
		sub_string: "iCab",
		identity: "iCab"
	},{
		string: navigator.vendor,
		sub_string: "KDE",
		identity: "Konqueror"
	},{
		string: navigator.userAgent,
		sub_string: "Firefox",
		identity: "Firefox"
	},{
		string: navigator.vendor,
		sub_string: "Camino",
		identity: "Camino"
	},{		
		// for newer Netscapes (6+)
		string: navigator.userAgent,
		sub_string: "Netscape",
		identity: "Netscape"
	},{
		string: navigator.userAgent,
		sub_string: "MSIE",
		identity: "Explorer",
		version_search: "MSIE"
	},{
		string: navigator.userAgent,
		sub_string: "Gecko",
		identity: "Mozilla",
		version_search: "rv"
	},{ 
		// for older Netscapes (4-)
		string: navigator.userAgent,
		sub_string: "Mozilla",
		identity: "Netscape",
		version_search: "Mozilla"
	}],
	data_os : [{
		string: navigator.platform,
		sub_string: "Win",
		identity: "Windows"
	},{
		string: navigator.platform,
		sub_string: "Mac",
		identity: "Mac"
	},{
		string: navigator.userAgent,
		sub_string: "iPhone",
		identity: "iPhone/iPod"
	},{
		string: navigator.platform,
		sub_string: "Linux",
		identity: "Linux"
	}]
};
browser_detect.init();

function line_break_count(str){
	try {
		return((str.match(/[^\n]*\n[^\n]*/gi).length));
	} catch(e) {
		return 0;
	}
}

function check_require_unicode(tmp_string) {
	for(i = 0, n = tmp_string.length; i < n; i++) {
		if (tmp_string.charCodeAt(i) > 127) {
			return true;
		}
	}
	return false;
}

function check_message(id_string, id_length, id_lang, code_fix) {
	msgBox = document.getElementById(id_string);
	showBox = document.getElementById(id_length);
	langBox = document.getElementById(id_lang);

	var doubleByteChars = ',12,91,92,93,94,123,124,125,126,';

	charNum = msgBox.value.length;
	if(code_fix != 0 && (msgBox.value.indexOf("#code#") >= 0)) {
		charNum = charNum + (code_fix - 6);
	}
	var countDouble = 0;
	var countChar = 0;
	var flagUnicode = false;
	var char_runner = 0;

	for (i = 0; i < charNum; i++) {

		var chCode = msgBox.value.charCodeAt(i);
		
		// Charcode 13 = CR Carriage return
        if ((!(isNaN(chCode))) && (chCode != 13)) {
        	countChar++;
				
        	// Standard ASCII 7-bit is charcode <= 127, count double if charcode more than this
			if (chCode > 127) {
				flagUnicode = true;
			}

			if ((doubleByteChars.indexOf(',' + chCode + ',') > 0) && (!flagUnicode)) {
				countDouble++;
				char_runner++;
			}
			
        }
	}
	
	if (flagUnicode) {
		maxLenght = 70;
		charLess = 3;
		lang = 'ไทย';
		RealMax = 201;
	} else {
		maxLenght = 160;
		charLess = 7;
		countChar += countDouble;
		lang = 'อังกฤษ';
		RealMax = 459;
	}

    if (countChar > maxLenght) {
    	SMSs = Math.floor(((countChar - 1) / (maxLenght - charLess)) + 1);
    	Limit = (maxLenght - charLess) * SMSs;
    } else {
    	SMSs = Math.floor(((countChar - 1) / (maxLenght)) + 1);
    	Limit = maxLenght * SMSs;
    }
	
    if (countChar == 0) {
		Limit = 160;
    }
	
	showBox.value = 'ภาษา: ' + lang + ' ' + Limit + '  ตัวอักษร/ข้อความ สูงสุด ' + RealMax + ' ตัวอักษร';
	langBox.value = countChar + '/' + Limit + ' (' + SMSs + ' ข้อความ)';
		
	if (SMSs > 1) {
		langBox.style.color = 'red';
	} else {
		langBox.style.color = '#007DC3';
	}

	if (countChar > RealMax) {
		if (flagUnicode) {
			msgBox.value = msgBox.value.substr(0,RealMax);
		}else{
			msgBox.value = msgBox.value.substr(0,RealMax-char_runner);
		}
	}
}

function check_message9(id_string, id_length, id_lang, code_fix) {
	var tmp_msg = document.getElementById(id_string).value;
	var max;
	var msg_length = tmp_msg.length;
	
	//alert(msg_length);
	
	if(code_fix != 0 && (tmp_msg.indexOf("#code#") >= 0)) {
		msg_length = msg_length + (code_fix - 6);
	}
	
	if (msg_length == 0) {
		document.getElementById(id_lang).value = "ภาษา: อังกฤษ 160 ตัวอักษร/ข้อความ, สูงสุด 450 ตัวอักษร";
		document.getElementById(id_length).value = "0/160 (0 ข้อความ)";

		return true;
	}
	var max_char_now;
	var number_message = 1; 

	if (browser_detect.browser == 'Explorer') {
		msg_length = msg_length - line_break_count(tmp_msg);
	}
	
	if (check_require_unicode(tmp_msg)) {
		document.getElementById(id_lang).value = "ภาษา: ไทย 70 ตัวอักษร/ข้อความ สูงสุด 210 ตัวอักษร";
		max = 70;
		number_message = Math.ceil(msg_length / max);
		max_char_now = number_message * max;
		document.getElementById(id_length).value = msg_length + "/" + max_char_now + " (" + number_message + " ข้อความ)";
		if (msg_length > 210) {
			//alert("ข้อความยาวก่อนกว่าที่กำหนด!");
			document.getElementById(id_string).value = tmp_msg.substr(0,210);
		}
		
	} else {
		document.getElementById(id_lang).value = "ภาษา: อังกฤษ 160 ตัวอักษร/ข้อความ สูงสุด 450 ตัวอักษร";
		max = 160;
		number_message = Math.ceil(msg_length / max);
		max_char_now = number_message * max;
		document.getElementById(id_length).value = msg_length + "/" + max_char_now + " (" + number_message + " ข้อความ)";
		if (msg_length > 450) {
			//alert("ข้อความยาวก่อนกว่าที่กำหนด!");
			document.getElementById(id_string).value = tmp_msg.substr(0,450);
		}
	}
}

function update_textbox_counter(id_string, id_length, id_lang, time_delay, code_fix) {
	//alert(id_string + " " + id_lang + " " + time_delay + " " + code_fix);
	timer_delay = setInterval("check_message(" + '"' + id_string + '"' + "," + '"' + id_length + '"' + "," + '"' + id_lang + '"' + "," + '"' + code_fix + '"' + ")", time_delay);
	return true;
}

function clear_textbox_counter() {
	clearInterval(timer_delay);
}	

/*function clear_textbox_counter() {
   document.forms[0].InfoCharCounter.value = "";
}*/
/* Method :: Check Message */ 

/* Method :: Active Checkbox */
function checkbox_check(id, name) {
	if(document.getElementById(id).checked == true) {
		check_all(id, name);
	} else {
		uncheck_all(id, name);
	}
}

function check_all(id, name) {
	$("input[type='checkbox']").attr('checked', true);
}

function uncheck_all(id, name) {
	$("input[type='checkbox']").attr('checked', false);
}
/* Method :: Active Checkbox */

/* Method :: Element */
function set_value(id, value) {
	document.getElementById(id).value = value;
}
/* Method :: Element */

/* Method :: Number Validate */
function numbers_only(e, opt) {
	var evt = (e) ? e : window.event;
	var key = (evt.keyCode) ? evt.keyCode : evt.which;

	if(key != null) {
		key = parseInt(key, 10);

		if((key < 48 || key > 57) && (key < 96 || key > 105) || (key == 190)) {
			if(!is_user_friendly_char(key, opt)) {
				return false;
			}
		} else {
			if(evt.shiftKey) {
				return false;
			}
		}
	}
	return true;
}

function is_user_friendly_char(val, opt) {
	if(opt == "money") {
		if(val == 190) {
			return true;
		}
	}

	// Backspace, Tab, Enter, Insert, and Delete
 	if(val == 8 || val == 9 || val == 13 || val == 45 || val == 46)
	  return true;

	// Ctrl, Alt, CapsLock, Home, End, and Arrows
	if((val > 16 && val < 21) || (val > 34 && val < 41))
	  return true;

	return false;
}
/* Method :: Number Validate */

/* Method :: URL Encode */
function urlencode(str) {   
    var hash_map = {};
    var unicodeStr = '', str_hex_esc = '';
    var ret = (str + '').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urldecode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (str_unicode in hash_map) {
    	str_hex_esc = hash_map[str_unicode];
        ret = replacer(str_unicode, str_hex_esc, ret); // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
}
/* Method :: URL Encode */

/* Method :: Field Validate */
function validateEmpty(fld) {
    var error = "";
  
    if (fld.value.length == 0) {
        //fld.style.background = '#FFFFFF'; 
        //fld.style.background = "url('../images/backend/bg_txtbox05.jpg') no-repeat scroll left top transparent";
        //fld.style.borber = "solid #FF0000 1px;";
        error = "กรุณากรอกข้อมูลให้ครบถ้วน\n"
    } else {
        //fld.style.background = 'White';
    }
    return error;   
}


function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        //fld.style.background = '#FFFF99'; 
        error = "กรุณากรอกชื่อผู้ใช้งานด้วยค่ะ";
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        //fld.style.background = '#FFFF99'; 
        error = "ชื่อผู้ใช้งานขั้นต่ำ 6 ตัวอักษรค่ะ";
    } else if (illegalChars.test(fld.value)) {
        //fld.style.background = '##FFFF99'; 
        error = "The username contains illegal characters.\n";
    } else {
        //fld.style.background = 'White';
    } 
    return error;
}
function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (fld.value == "") {
        //fld.style.background = '#FFFF99';
        error = "กรุณากรอกรหัสผ่าน\n";
    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
        error = "ขออภัย รหัสผ่านต้องมีตัวอักษรอย่างน้อย 7 ตัวอักษรขึ้นไปค่ะ\n";
        //fld.style.background = '#FFFF99';
    } else if (illegalChars.test(fld.value)) {
        error = "รหัสผ่านต้องเป็นภาษาอังกฤษหรือตัวเลขเท่านั้นค่ะ\n";
        //fld.style.background = '#FFFF99';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "รหัสผ่านต้องเป็นภาษาอังกฤษหรือตัวเลขเท่านั้นค่ะ\n";
        //fld.style.background = '#FFFF99';
    } else {
        //fld.style.background = 'White';
    }
   return error;
} 
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
} 

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    
    if (fld.value == "") {
        //fld.style.background = '#FFFF99';
        error = "กรุณากรอกอีเมล์ด้วยค่ะ\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        //fld.style.background = '#FFFF99';
        error = "กรุณาตรวจสอบอีเมล์ให้ถูกต้องด้วยค่ะ\n";
    } else if (fld.value.match(illegalChars)) {
        //fld.style.background = '#FFFF99';
        error = "กรุณาตรวจสอบอีเมล์ให้ถูกต้องด้วยค่ะ\n";
    } else {
        //fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "กรุณากรอกหมายเลขโทรศัพท์\n";
        //fld.style.background = '#FFFF99';
    } else if (isNaN(parseInt(stripped))) {
        error = "กรุณากรอกหมายเลขโทรศัพท์ให้ถูกต้อง\n";
        //fld.style.background = '#FFFF99';
    } else if (!(stripped.length == 10)) {
        error = "กรุณากรอกหมายเลขโทรศัพท์ให้ถูกต้อง\n";
        //fld.style.background = '#FFFF99';
    } 
    return error;
}

function validateID(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "กรุณากรอกเลขบัตรประชาชน\n";
        //fld.style.background = '#FFFF99';
    } else if (isNaN(parseInt(stripped))) {
        error = "กรุณากรอกเลขบัตรประชาชนให้ถูกต้อง\n";
        //fld.style.background = '#FFFF99';
    } else if (!(stripped.length == 13)) {
        error = "กรุณากรอกเลขบัตรประชาชนให้ถูกต้อง\n";
        //fld.style.background = '#FFFF99';
    } 
    return error;
}

/* Method :: Field Validate */

/* Method :: Auto Comaplete */
function auto_comaplete(id, array_value) {
	$(id).autocomplete(array_value, {
		//multiple: true, //ยอมให้ป้อนได้หลายค่า
		mustMatch: false, //ป้อนได้เฉพาะค่าที่เตรียมไว้ให้
		autoFill: true, //เติมคำอัตโนมัติ
		matchContains: true //หาค่าที่ไม่ใช่ตัวเริ่มต้น
	});
}
/* Method :: Auto Comaplete */

/* Method :: ToolTip */
function tool_tip(id) {
	$(id).tooltip();
	/*$(id_msg).tooltip({
		track: true,
		delay: 0,
		showURL: false,
		showBody: " - ",
		fixPNG: true,
		left: -120
	});*/
}
/* Method :: ToolTip */

/* Method :: Light Box Overlay */
function lightbox_open(color, dir) {
	SexyLightbox.initialize({
		color: color,
		dir: dir
	});
}

function lightbox_close(){
	SexyLightbox.close();
}
/* Method :: Light Box Overlay */

/* Method :: Date & Time */
function check_datetime(datetime_range_1, datetime_range_2) {//now_year, now_month, now_day, now_hour, now_min, year, month, day, hour, min) {
	var datetime_range_1_year = datetime_range_1.getFullYear();
	var datetime_range_1_month = datetime_range_1.getMonth() + 1;
	var datetime_range_1_date = datetime_range_1.getDate();
	var datetime_range_1_hour = datetime_range_1.getHours();
	var datetime_range_1_min = datetime_range_1.getMinutes();
	
	if(datetime_range_1_month < 10) { datetime_range_1_month = "0" + datetime_range_1_month; }
	if(datetime_range_1_date < 10) { datetime_range_1_date = "0" + datetime_range_1_date; }
	if(datetime_range_1_hour < 10) { datetime_range_1_hour = "0" + datetime_range_1_hour; }
	if(datetime_range_1_min < 10) { datetime_range_1_min = "0" + datetime_range_1_min; }
	
	var datetime_range_2_year = datetime_range_2.getFullYear();
	var datetime_range_2_month = datetime_range_2.getMonth() + 1;
	var datetime_range_2_date = datetime_range_2.getDate();
	var datetime_range_2_hour = datetime_range_2.getHours();
	var datetime_range_2_min = datetime_range_2.getMinutes();
	
	if(datetime_range_2_month < 10) { datetime_range_2_month = "0" + datetime_range_2_month; }
	if(datetime_range_2_date < 10) { datetime_range_2_date = "0" + datetime_range_2_date; }
	if(datetime_range_2_hour < 10) { datetime_range_2_hour = "0" + datetime_range_2_hour; }
	if(datetime_range_2_min < 10) { datetime_range_2_min = "0" + datetime_range_2_min; }
	
	var str_datetime_range_1 = datetime_range_1_year.toString() + datetime_range_1_month.toString() + datetime_range_1_date.toString() + datetime_range_1_hour.toString() + datetime_range_1_min.toString();
	var str_datetime_range_2 = datetime_range_2_year.toString() + datetime_range_2_month.toString() + datetime_range_2_date.toString() + datetime_range_2_hour.toString() + datetime_range_2_min.toString();

	var int_datetime_range_1 = parseInt(str_datetime_range_1);
	var int_datetime_range_2 = parseInt(str_datetime_range_2);
	
	if(int_datetime_range_1 == int_datetime_range_2) {
		return 0;
	} else if(int_datetime_range_1 > int_datetime_range_2) {
		return 1;
	} else {
		return -1;
	}
}
/* Method :: Date & Time */

/* Method :: IFrame */
function resize_iframe(iframe_name, add_height) {
	alt = document.body;
	frm = parent.document.getElementById(iframe_name);

	frm.height = alt.offsetHeight + add_height;	
}

function reset_size_iframe(iframe_name) {
	parent.document.getElementById(iframe_name).height = "0px";
}
/* Method :: IFrame */

/* Method :: encode */
function encode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
	while (i < input.length) {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);
 
		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;
 
		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}
 
		output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
   }
   
   return output.toString();
}

function decode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
 
	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
	while (i < input.length) {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));
 
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;
 
		output += String.fromCharCode(chr1);
 
		if (enc3 != 64) {
			output.append(String.fromCharCode(chr2));
		}
		if (enc4 != 64) {
			output.append(String.fromCharCode(chr3));
		}
	}
 
	return output.toString();
}
/* Method :: encode */

/* Method :: format */
function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
/* Method :: format */