/******************************* onload functions *******************************/
/* Functions to Run When Page Loads												*/
/********************************************************************************/
$(function() {
	// Messages
	messages();
	// Row Backgrounds
	rows();
	// Tooltips
	//tips();
	// Calendars
	calendar();
	// Tags
	tagIt();
	// Buttons
	buttons();
});

/******************************** document.ready ********************************/
/* Functions to Run When Page Loaded											*/
/********************************************************************************/
$(document).ready(function () {		
	// Parallax
	$('#parallax').jparallax({childrenElements: '.move'});
	// Form Validation
	validate();
	// Text Editor
	texteditor();
	// Draggable
	drag();
	// PNG Fix
	png();
	// Default Values
	defaults();
	// Quicksearch
	quicksearch();
});

/************************************ loader ************************************/
/* Shows loading icon with given text (optional) in given div					*/
/********************************************************************************/
function loader(div,text) {
	if(text == "") text = "Loading..";
	var html = $(this).html();
	$(div).before("<div style='position:relative;min-height:100px;' class='loader_div'><div style='position:absolute;left: 50%;margin-left:-40px;margin-top:30px;' class='loader_image'><center><img src='"+DOMAIN+"images/ajax-loader.gif' style='vertical-align:middle;' /></center></div><div style='opacity:.30;filter:alpha(opacity=30);-moz-opacity:.3;' class='loader_content'>").after("</div></div>");
}

/*********************************** scrollIt ***********************************/
/* Loads content of page, then side scrolls it into view						*/
/********************************************************************************/
function scrollIt(page) {
	if(!page || page == null) type = '';
	$('div.nav a').removeClass('selected');
	$('div.nav a#nav_'+page).addClass('selected');
	/*$('#content .page').fadeOut(500,function() { 
		//loader('#content .page'); 
	});
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=scrollIt&page='+page,
		success: function(html){
			$('#content .page').remove();
			$('#content').append(html);
			$('#content .page').fadeIn(500);
			//$('#content .loader_div').remove();
		}
	});*/
}

/*********************************** confirmIt **********************************/
/* Shows confirm box which redirects to given url if user confirms given text	*/
/********************************************************************************/
function confirmIt(text,url) {
	if (confirm(text)){
		location.replace(url);
	}
}

/************************************ showHide **********************************/
/* Shows or hides given div based upon it's current state						*/
/********************************************************************************/
function showHide(div) {
	if(document.getElementById(div).style.display=="none") $("#"+div).show();
	else $("#"+div).hide();
}

/************************************* showIt ***********************************/
/* Fades in given element in given amount of time								*/
/********************************************************************************/
function showIt(div,time) {
	/*if(time == null) var time = 500;
	$("#"+div).fadeIn(time);*/
	$("#"+div).show();
}

/************************************* hideIt ***********************************/
/* Fades out given element in given amount of time								*/
/********************************************************************************/
function hideIt(div,time) {
	/*if(time == null) var time = 500;
	$("#"+div).fadeOut(time);*/
	$("#"+div).hide();
}

/************************************ submitIt **********************************/
/* Submits form and disables submit button										*/
/********************************************************************************/
function submitIt(f) {
	var s = $(f).find("input[type='submit']");
	$(s).fadeTo("normal", 0.4).attr("disabled", "disabled").after("<img src='"+DOMAIN+"images/ajax-loader.gif' style='margin-left:4px;' class='absmiddle submit_loader' />");
	f.submit();
}

/*********************************** editInline *********************************/
/* Retrieves code for inline editing of given variable							*/
/********************************************************************************/
function editInline(div,table,column,key,id,buttons,redirect) {
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=editInline&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&buttons='+buttons+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Calendar
			calendar();

			// Submit on Enter
			$('#'+div+'_inline').focus().keypress(function (e) {
				if (e.which == 13) saveInline('1',div,table,column,key,id,buttons,redirect);
			});
			
			// Submit on Blur
			if(buttons == 0) {
				$('#'+div+'_inline').blur(function () {
					saveInline('1',div,table,column,key,id,buttons,redirect);
				});
			}
		}
	});
}

/*********************************** saveInline *********************************/
/* Gets inline variable and saves it											*/
/********************************************************************************/
function saveInline(save,div,table,column,key,id,buttons,redirect) {
	var value;
	var v = $('#'+div+'_inline');
	if(v.type == "radio" || v.type == "checkbox") {
		if(v.checked == true) value = v.value;
	}
	else value = encodeURIComponent(v.value);
	
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=saveInline&save='+save+'&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&value='+value+'&buttons='+buttons+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Redirect
			if(redirect != "" && redirect != "undefined" && redirect != undefined && redirect) location.assign(DOMAIN+redirect);
			
			// Refresh jQuery
			thickbox();
			//$('table.sortable').trigger("update");
		}
	});
}

/************************************** tagIt ***********************************/
/* Adds tag funcionality to input fields with class='tag'						*/
/********************************************************************************/
var tags;
function tagIt(div) {
	/*$('input.tag').unautocomplete();
	
	if(tags) {
		if(div == null) div = 'tags';
		$('input.tag').autocomplete(tags, {
			minChars: 0,
			matchContains: true,
			autoFill: false,
			formatItem: function(row) {
				return row.name +' <h4>'+row.note+'</h4>';
			},
			formatMatch: function(row, i, max) {
				return row.name + ' ' + row.username;
			}
		}).result(function(event, data, formatted) {
			$(this).val('');
			$.ajax({
				type: 'GET',
				url: DOMAIN+'?ajaxRequest=tagIt&id='+data.id,
				success: function(html){
					$('#'+div).append(html);
					messages();
					
					// Tag Counter
					if(document.getElementById('tag_counter')) {
						var c = $('#tag_counter').val();
						var test = html.split("class='_error");
						if(!test[1]) $('#tag_counter').val((c * 1) + 1);
						if($('label.error').is(':visible')) $(".require").valid();
					}
				}
			});
		});
	}*/
}

/************************************ untagIt ***********************************/
/* Removes tag from form and sends ajax request to remove from tags session		*/
/********************************************************************************/
function untagIt(div,id) {
	/*removeIt(div);
	
	// Re-activates checkbox (if exists)
	$('#check_'+id+'_text').slideDown(400);
	$('#check_'+id+'_input').removeAttr('checked');
	
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=untagIt&id='+id
	});
	
	// Tag Counter
	var c = $('#tag_counter').val();
	if(c) $('#tag_counter').val((c * 1) - 1);*/
}

/************************************* checkIt **********************************/
/* Handles tagging when checkbox is clicked										*/
/********************************************************************************/
/*function checkIt(id,div) {
	if(div == null) div = 'tags';
	
	// Deactivates Checkbox
	$('#check_'+id+'_text').slideUp(400);
	
	// Send AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=tagIt&id='+id,
		success: function(html){
			$('#'+div).append(html);
			messages();
			
			// Tag Counter
			if(document.getElementById('tag_counter')) {
				var c = $('#tag_counter').val();
				var test = html.split("class='_error");
				if(!test[1]) $('#tag_counter').val((c * 1) + 1);
				if($('label.error').is(':visible')) $(".require").valid();
			}
		}
	});
}

/************************************ removeIt **********************************/
/* Removes given div															*/
/********************************************************************************/
function removeIt(div) {
	$('#'+div).fadeOut(500,function() {
		$(this).remove();
	});
}

/************************************ deleteIt **********************************/
/* Sends ajax request do delete given type's id if given text is confirmed		*/
/********************************************************************************/
function deleteIt(text,div,table,key,id) {
	if (confirm(text)){
		// Hide
		$('#'+div).fadeOut(500,function() {
		
			// AJAX
			$.ajax({
				type: 'GET',
				url: DOMAIN+'?ajaxRequest=deleteIt&table='+table+'&div='+div+'&id='+id+'&key='+key,
				success: function(html){
					if(html.length > 0) $('#'+div).html(html);
					else $('#'+div).remove();
					
					// Redirect
					if(document.getElementById('redirect')) location.assign(DOMAIN+document.getElementById('redirect').value);
					
					// Rows
					rows();
				}
			});
		});
	}
}

/******************************** deactivateIt **********************************/
/* Deactivates item (deleted from frontend, still in db)						*/
/********************************************************************************/
function deactivateIt(text,div,table,column,key,id) {
	if (confirm(text)){
		// Hide
		$('#'+div).fadeOut(500,function() {
			$(this).remove();
			// Disable in DB
			$.ajax({
				type: 'GET',
				url: DOMAIN+'?ajaxRequest=deactivateIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id
			});
			rows();
		});
	}
}

/************************************ saveIt ************************************/
/* Gets values from a form, posts to AJAX, and handles response					*/
/********************************************************************************/
function saveIt(form,div,method) {
	var vals;
	$('#'+form+' :input').each(function() {
		if(this.type == "radio" || this.type == "checkbox") {
			if(this.checked == true) vals = vals + '&' + this.name + '=' + this.value;
		}
		else vals = vals + '&' + this.name + '=' + encodeURIComponent(this.value);
	});
	
	// Method
	if(method == null) method = 'GET';
	if(method == 'GET') {
		var url = DOMAIN+'?ajaxRequest=saveIt&form='+form+'&div='+div+vals;
		var data = '';
	}
	if(method == 'POST') {
		var url = DOMAIN+'?ajaxRequest=saveIt';
		var data = 'form='+form+'&div='+div+vals;
	}
	
	$.ajax({
		type: method,
		url: url,
		data: data,
		success: function(html){
			// Comment
			if(form == "comment"){
				$("#"+div).after(html);
			}
			// Tags
			else if(form == "contacts_add" || form == "contact_add"){
				var s = html.split('|||');
				$("#"+div).html(s[0]);
				if(s[1]) $("#tags").append(s[1]);
				if(document.getElementById('tag_counter')) {
					var c = $('#tag_counter').val();
					$('#tag_counter').val((c * 1) + 1);
					if($('#'+form+' label.error').is(':visible')) $(".require").valid();
				}
				if(form == "contacts_add") {
					document.getElementById('contacts_get')['email'].value = '';
					document.getElementById('contacts_get')['password'].value = '';
				}
				if(form == "contact_add") document.getElementById('contact_add')['email'].value = '';
			}
			else $("#"+div).html(html);
			
			// Submit Button
			var s = $("#"+form+" input[type='submit']").fadeTo("normal", 1.0).removeAttr("disabled");
			$('img.submit_loader').each(function() { $(this).remove(); });
			// Refresh jQuery
			rows();
			thickbox();
			messages();
			validate();
			drag();
			buttons();
			texteditor();
		}
	});
}

/*********************************** updateIt ***********************************/
/* Handles various update scripts												*/
/********************************************************************************/
function updateIt(table,column,key,id) {
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=updateIt&table='+table+'&column='+column+'&key='+key+'&id='+id,
		success: function(html){
			var array = html.split('|||');
			for(var i in array) {
				if(!(i % 2)) {
					var j = (i * 1) + 1;
					if(array[j]) {
						$('#'+array[i]).html(array[j]);
					}
				}
			}
		}
	});
}

/************************************ loadIt ************************************/
/* Handles various load scripts													*/
/********************************************************************************/
function loadIt(div,type,id,loc) {
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=loadIt&div='+div+'&type='+type+'&id='+id,
		success: function(html){
			if(loc == "prepend") $('#'+div).prepend(html);
			else if(loc == "append") $('#'+div).append(html);
			else $('#'+div).html(html);
			
			// Refresh jQuery
			rows();
			messages();
			thickbox();
			calendar();
			validate();
			texteditor();
			quicksearch();
			//$('.sortable').trigger("update");
		}
	});
}

/************************************ loadIt ************************************/
/* Handles various load scripts													*/
/********************************************************************************/
function loadIt(div,type,id,loc) {
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=loadIt&div='+div+'&type='+type+'&id='+id+'&loc='+loc,
		success: function(html){
			if(loc == "prepend") $('#'+div).prepend(html);
			else if(loc == "append") $('#'+div).append(html);
			else $('#'+div).html(html);
			
			// Refresh jQuery
			rows();
			messages();
			thickbox();
			calendar();
			validate();
			drag();
			buttons();
		}
	});
}

/*********************************** updateIt ***********************************/
/* Handles various update scripts												*/
/********************************************************************************/
function updateIt(table,column,key,id) {
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=updateIt&table='+table+'&column='+column+'&key='+key+'&id='+id,
		success: function(html){
			var array = html.split('|||');
			for(var i in array) {
				if(!(i % 2)) {
					var j = (i * 1) + 1;
					if(array[j]) {
						$('#'+array[i]).html(array[j]);
					}
				}
			}
		}
	});
}

/*********************************** uploadPhoto ********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
var uploadPhoto_n = 0;
function uploadPhoto(div,results,input,path) {
	var file = $('#'+input).val();
	var album = $('#album').val();
	if(file) {
		// Total Number of Current Uploads
		uploadPhoto_n = uploadPhoto_n + 1;
		
		// Loader
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=previewPhoto&x='+uploadPhoto_n+'&div='+div+'&file='+file,
			success: function(html){
				$("#"+div).append(html);
				var d = div+'_'+uploadPhoto_n;
				$("#"+d).slideDown(350);
				
				// Upload Photo
				$.ajaxFileUpload({
					url:DOMAIN+'?ajaxRequest=uploadPhoto&path='+path+'&d='+d+'&album='+album,
					secureuri:false,
					fileElementId:input,
					dataType: 'script',
					success: function (data, status) {
						var array = data.split('|||');
						// Remove "Uploading" add Photo Info Box
						$("#heading").show();
						$("#"+results).show().prepend(array[0]);
						$("#submit").show();
						$("#"+d+'_up').slideDown(350);
						$("#"+d).slideUp(350, function() {
							$(this).remove();
							calendar();
						});
						
						rows();
						thickbox();
						tagIt(array[1]);
						notes(array[1]);
						
						// Hide Failure Messages
						$("#red").animate({opacity: 1.0}, 1500).slideUp(500, function() {
							$(this).remove();
						});
						
					},
					error: function (data, status, e) {
						alert(e);
					}
				});
				
				// Clear File Input
				$('#'+input).animate({opacity: 1.0}, 50,function(){
					document.getElementById(input).value = "";
				});
				
			}
		});
	}
	return false;
}

/************************************ uploadIt **********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
function uploadIt(div,input,path) {
	loader('#'+div,'Uploading..');
	
	$.ajaxFileUpload(
		{
			url:DOMAIN+'?ajaxRequest=upload&path='+path,
			secureuri:false,
			fileElementId:input,
			dataType: 'html',
			success: function (data, status) {
				// Add Message / Hidden Input
				$("#"+div).append(data);
				// Clear File Input
				document.getElementById(input).value = "";
				// Hide Failure Messages
				$("#red").animate({opacity: 1.0}, 1500).slideUp(500, function() {
					$(this).remove();
				});
			},
			error: function (data, status, e) {
				alert(e);
			}
		}
	)
	return false;
}

/********************************* disableIt ************************************/
/* Disables given element														*/
/********************************************************************************/
function disableIt(div,table,column,key,id,button) {
	// Fade Out Div
	if(document.getElementById(div)) {
		document.getElementById(div).disabled = true;
		$('#'+div).css('cursor','default').fadeTo("normal", 0.4);
	}
	
	// Disable in DB
	if(table) {
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=disableIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&button='+button,
			success: function(html){
				$('#'+button).html(html);
			}
		});
	}
}

/********************************** enableIt ************************************/
/* Enables given element														*/
/********************************************************************************/
function enableIt(div,table,column,key,id,button) {
	// Fade In Div
	if(document.getElementById(div)) {
		document.getElementById(div).disabled = false;
		$('#'+div).css('cursor','pointer').css('cursor','hand').fadeTo("normal",1);
	}
	
	// Enable in DB
	if(table) {
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=enableIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&button='+button,
			success: function(html){
				$('#'+button).html(html);
			}
		});
	}
}

/************************************ defaults **********************************/
/* Clears or Restores default value for input field where class='default'		*/
/********************************************************************************/
function defaults() {
	$('input.default').focus(function() {	
		if(this.defaultValue == this.value) $(this).val('').removeClass('default');
	}).blur(function() {
		if(!this.value) $(this).val(this.defaultValue).addClass('default');
	});
}

/*********************************** checkAll ***********************************/
/* Checks or unchecks all checkboxes (with optional class name) 				*/
/********************************************************************************/
function checkAll(c,classID) {
	if(classID) {
		if(c.checked) $('input[@type=checkbox].'+classID).attr('checked', 'checked');
		else $('input[@type=checkbox].'+classclassID).removeAttr('checked');
	}
	else {
		if(c.checked) $('input[@type=checkbox]').attr('checked', 'checked');
		else $('input[@type=checkbox]').removeAttr('checked');
	}
}

/************************************* tips *************************************/
/* Runs scripts for tooltips on elements with class="tip"						*/
/********************************************************************************/
function tips() {
	$('a.tip, img.tip, div.tip').tooltip({
		track: true,
		delay: 0,
		showURL: false
	});
}

/************************************** rows ************************************/
/* Adds alternate shading to odd and even rows where class="row"				*/
/********************************************************************************/
function rows() {
	$('tr.row:odd, div.row:odd').addClass("odd").removeClass("even");
	$('tr.row:even, div.row:even').addClass("even").removeClass("odd");
}

/************************************ calendar **********************************/
/* Shows calendar date picker on all input fields with class="calendar"			*/
/********************************************************************************/
function calendar() {
	/*$('img.ui-datepicker-trigger').remove();
	$('input.hasDatepicker').removeAttr('id').removeClass('hasDatepicker');
	
	$('input.calendar').each(function() {
		//$(this).attr('readonly','readonly');
		$(this).datepicker({ 
			showOn: 'both', 
			buttonImage: DOMAIN+'images/calendar.png',	
			changeMonth: true,
			changeYear: true,
			buttonImageOnly: true
		});
	});*/
}

/************************************ validate **********************************/
/* Adds form validation to all forms with class="require"						*/
/********************************************************************************/
function validate() {
	// Form Validation
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
	
	// Registration Validation
	$("#register").validate({
		rules: {
			user_name: { remote: DOMAIN+"?ajaxRequest=checkUsername", regex: '[a-zA-Z0-9_\-]' }, 
			user_confirm_password: { equalTo: "#user_password"}, 
			user_confirm_email: { equalTo: "#user_email"}
		},
		messages: {
			user_name: { remote: jQuery.format("This username is already taken"), regex: 'Your username may only contain letters and numbers' },
			user_confirm_password: { equalTo: "Your passwords don't match" },
			user_confirm_email: { equalTo: "Your e-mail addresses don't match" }
		},
		submitHandler: function(form) {	submitIt(form); }
	});
}

/************************************** drag ************************************/
/* Add draggability functionality to various elements							*/
/********************************************************************************/
function drag() {
	// Draggable
	/*** Implementaion Example ***/
	/*<ul class='drag'>
		<li class='draggable'><input type='hidden' class='dragged' value='$qry[photo_id]' /></li>
		<input type='hidden' name='type' value='photos' />
	</ul>
	*/
	/*$('div.drag, ul.drag, table.drag').sortable({
		items: 'div.draggable, li.draggable, tr.draggable',
		placeholder: 'helper',
		handle: ".handle",
		opacity: 0.5,
		stop : function () {
			var order = '';
			var type;
			$(this).find('input').each(function() {
				if(this.className == "dragged") order = order + '|' + this.value;
				if(this.name == "type") type = this.value;
			});
			if(order) $.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=orderIt&type='+type+'&order='+order});
			rows();
		}
	});
	
	$('div.dragThese, ul.dragThese, table.dragThese').sortable({
		items: 'div.dragThis, li.dragThis, tr.dragThis',
		placeholder: 'helper',
		opacity: 0.5,
		stop : function () { rows(); }
	});*/
}

/************************************ thickbox **********************************/
/* Removes old thickbox, adds new ones where class="thickbox" (call after ajax)	*/
/********************************************************************************/
function thickbox() {
	$('a.thickbox, area.thickbox, input.thickbox').each(function(i) { $(this).unbind('click'); });
	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

/********************************** quicksearch *********************************/
/* Adds quicksearch functionality to input id='quicksearch_q for ul with id='quicksearch'*/
/********************************************************************************/
function quicksearch() {
	$('#quicksearch_q').liveUpdate('#quicksearch');
}

/*********************************** texteditor *********************************/
/* Adds texteditor (TinyMCE) to textarea's with class='texteditor'				*/
/********************************************************************************/
function texteditor() {
	//$('textarea.texteditor').tinymce();
	$('textarea.texteditor').each(function() {
		$(this).wysiwyg(/*{
		controls : {
			justifyLeft: { visible : true },
			justifyCenter: { visible : true },
			justifyRight: { visible : true },
			separator04: { visible : true }
		}}*/).removeClass('texteditor');
	 });
}

/************************************* buttons **********************************/
/* Shows / hides elements with class=buttons on mouseover / mouseout			*/
/********************************************************************************/
function buttons() {
	//$('div.buttons').parent('div').mouseover(function() { $('div.buttons',this).show(); }).mouseout(function() { $('div.buttons',this).hide(); });
	$('div.button, li.button').mouseover(function() { $('div.buttons',this).show(); }).mouseout(function() { $('div.buttons',this).hide(); });
}

/*************************************** png ************************************/
/* Fixes .png images for IE <= 6												*/
/********************************************************************************/
function png() {
	$('body').pngFix();
}

/************************************ messages **********************************/
/* Removes '_message' and '_error' divs											*/
/********************************************************************************/
function messages() {
	$('div.slideDown').slideDown(1000,0);
	$('div.slideUp').slideUp(1000,0);
	$('div.fadeOut').fadeOut(1000,0);
	$('div.fadeIn').fadeIn(1000,0);
	
	$('div._error').animate({opacity: 1.0}, 5000).slideUp(500,function() { $(this).remove(); });
	$('div._message').animate({opacity: 1.0}, 5000).slideUp(700,function() { $(this).remove(); });
}

/********************************************************************************/
/******************************** PHP Functions *********************************/
/********************************************************************************/

/********************************* str_replace **********************************/
function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
    };
     
    return sa ? s : s[0];
}

/*********************************** is_array ***********************************/
function is_array( mixed_var ) {
    return ( mixed_var instanceof Array );
}

/********************************* number_format ********************************/
function number_format(number,decimals,dec_point,thousands_sep) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var 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) : "");
}