/**
 *
 * Oceniacz.pl
 * skrypty ogólne
 * 
 * @lastmodified 13:44 2010-02-09
 *
 */


/**
 * scorebarClicker 
 * jQuery Plugin
 *
 * @author Mateusz Janik
 */
(function($){
	$.fn.scorebarClicker = function() {
		return this.each( function() {
			
			var $root = $(this);
			var $current = $root.find('i');
			
			var $radios_arr = $root.find(':radio');
			var $links_arr = $root.find('a');
			
			$links_arr.click( function() {
				$(this).parents('.unfilled').removeClass('unfilled');
				var i = $links_arr.index($(this));
				$radios_arr.eq(i).attr('checked',1);
				
				//$current.width(++i*20+'%');
				$current.removeClass().addClass('sbc-'+ ++i+'0');
				
				return false
			} );
			
			var radio_name = $radios_arr.eq(0).attr('name');
			$( ":radio[name='"+radio_name+"']:eq(0)" ).click( function() { 
				$current.removeClass();
			} )
			
		});	// each
	}
})(jQuery);


/**
 * strip HTML tags
 * @url http://devkick.com/blog/parsing-strings-with-jquery/
 */
function stripTags(html) {
	var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
	return html.replace(regexp,"");
}
/**
 * stripTags
 * jQuery plugin
 */
(function($){
	$.fn.stripTags = function() {
		this.each(function() {
			$(this).html(
				stripTags( $(this).html() )
			);
		});
		return $(this);
	}
})(jQuery);



/**
 * in-field label
 */
(function($){
	$.fn.inFieldLabel = function() {
		this.each(function() {
			var $this = $(this);
			if($this.val() === '') {
				$this.val($this.attr('title'));
			}
			$this.focus(function() {
				if($this.val() === $this.attr('title')) {
					$this.val('');
				}
			});
			$this.blur(function() {
				if($this.val() === '') {
					$this.val($this.attr('title'));
				}
			});
		});
		return $(this);
	}
})(jQuery);	 


/**
 * picViewer
 * jQuery plugin
 *
 * @author Mateusz Janik 
 * @revision 7
 *   - [ok] nie pokazywać loadera jak dany obraz jest już wczytany (flaga)
 *   - [ok] if array length == 1 slideshow off
 * @todo revision 8:  
 *   - inne zliczanie interwałów pomiędzy zdjęciami (od momentu załadowania)
 */
(function($) {
	$.fn.picViewer = function(settings) {

		var defaults = {
			clNext: '.pv-next',
			clPrev: '.pv-prev',
			clBank: '.pv-bank',
			clNum: '.pv-num',
			clPicLink: '.pv-pic',
			clPicImg: '.pv-pic img',
			time: 4000
		};
		var opts = $.extend('',defaults, settings);
		
		return this.each( function() {
			var $this = this;
			var $arr = $(opts.clBank+' > li' ,$this);
			
			if ($arr.length == 1) { 
				return;
			}
			
			var $picLink = $(opts.clPicLink, $this);
			var $picImg = $(opts.clPicImg, $this);
			
			var total = $arr.length;
			if (total == 0) return;
			
			var inject = '<p class="pv-panel"> <a href="#" class="pv-next"><span>'+config.lang.nastepne+'</span></a> <a href="#" class="pv-prev"><span>'+config.lang.poprzednie+'</span></a> <span class="pv-num"><em></em></span> </p>';
			$(inject).insertAfter($picLink); 
			var $loader = $('<span class="loader" />').appendTo($picLink);
			
			/* @todo */
			// Check loading state of #1 image
			/* if ($container.find("img:first")[0].complete) {
				$.fn.showcase.start($container, opt);
			}
			else {
				$container.find("img:first").load( function() {
					$.fn.showcase.start($container, opt);
				});
			} */			

			var $num = $(opts.clNum,$this);			
			var current = 0;
			setText(1,total,$num);
			
			bank_arr = [];
			$arr.each( function(i,$li) {
				bank_arr.push( {
					href: $(' a', $li).attr('href'),
					src: $(' img', $li).attr('src')
				});
			}); 
			
 			$picImg.load( function (el) {
				bank_arr[current].loaded = 1;
				$picLink.removeClass('loading');
				//$picImg.fadeIn('slow')
				$picImg.show()
			} );
						
			
			$(opts.clNext,this).bind('click slide', function (e, auto) {
				
				/* if (!auto) {
					// jeśli funkcja nie jest odpalana przez slideshow (interval), to zatrzymujemy interval
					clearInterval(slideshow);
				}  */
				// http://docs.jquery.com/Events/trigger#examples
				if (e.type == 'click') clearInterval(slideshow);
				if (++current > total-1) {current = 0}
				if (!bank_arr[current].loaded) {
					$picLink.addClass('loading');
				}				
				$picImg.fadeOut(150,
					function () {
						/* if (!$picImg.get(0).complete) 
							$picLink.addClass('loading'); */

						setText(current+1,total,$num);
						
						$picImg.attr('src',bank_arr[current].href)
						//$picLink.attr('href',bank_arr[current].href)
						 
					}
				);
				e.preventDefault();
			})
			/* .text('następne') */.attr('title','następne zdjęcie').show();

			$(opts.clPrev,this).bind('click slide', function (e, auto) {
				
				/* if (!auto) {
					// jeśli funkcja nie jest odpalana przez slideshow (interval), to zatrzymujemy interval
					clearInterval(slideshow);
				}  */
				if (e.type == 'click') clearInterval(slideshow);
				
				$picImg.fadeOut(150,
					function () {
						if (--current < 0) {current = total-1}
						setText(current+1,total,$num);
						
						$picImg.attr('src',bank_arr[current].href)
						//$picLink.attr('href',bank_arr[current].href)
					}
				);
				e.preventDefault();
			})
			/* .text('poprzednie') */.attr('title','poprzednie zdjęcie').show();

			/* Włączenie auto-pokazu */
			/**/
			var $next = $(opts.clNext, $this);
			if ( typeof(opts.time) === 'number' ) {
				var slideshow = setInterval(function() { 
					$next.trigger('slide');
				}, opts.time); 
			}
			/**/
			
		}); // each
	
	} // $.fn

	function setText(i, n, $el) {
		$el.html( i+' <em>/ '+n+'</em>');		
	}
	
})(jQuery);


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


/**
 * clicky
 * jQuery plugin
 * 
 * Make CONTAINER (or AREA) clickable
 *
 * @revision 3
 * @param href jq selector
 * @param area jq selector/s
 * @example $(CONTAINER).clicky() - CONTAINER clickable (first HREF inside)
 * @example $(CONTAINER).clicky(HREF) - CONTAINER clickable (HREF)
 * @example $(CONTAINER).clicky(HREF, AREA) - AREA (inside CONTAINER) clickable (HREF)
 */
(function($){
$.fn.clicky = function(href, area) {
	return this.each( function() {
		//console.log('link: '+href+', area: '+area);
		var $t = $(this);
		
		var $link;
		if (href) {
			$link = $t.find(href).eq(0);
		} else {
			$link = $t.find('a');
			if ($link.length != 1) {
				$link = null;
			}
		}
		
		var $area = $t;
		if (area) {
			var $f = $t.find(area);
			$area = ($f.length) ? $f : $t;
		}
		
		if ($link) {
			$area.each( function() {
				//console.log($(this));
				$(this)
				.click( function(e) {
					if (e.target.nodeName != 'a') {
						window.location = $link.attr('href');
					} 
					e.preventDefault();
				})
				.css('cursor','pointer')
				.attr('title',$link.attr('title'));
			})
		}
	} );	
}
})(jQuery);
/**/


/**
 * GalleryTeaser class
 * @required jCarousel http://sorgalla.com/projects/jcarousel 
 */
function GalleryTeaser(el,opt) {
	var self = this;
	self.$el = $(el);
	self.visible = false;
	
	self.opt = $.extend({
		buttonPrevHTML: '<div class="c ps-prev"></div>',
		buttonNextHTML: '<div class="c ps-next"></div>', 
		initCallback: $.proxy(self.initCallback, self),
		setupCallback: $.proxy(self.setupCallback, self),
		itemLoadCallback: $.proxy(self.itemLoadCallback, self)
	}, opt);
}

GalleryTeaser.prototype.init = function () {
	var self = this;
	self.$el.css('visibility','hidden');
	self.$el.jcarousel(self.opt);		
}

GalleryTeaser.prototype.setupCallback = function (carousel) {
	var self = this; 
	//self.$el.show(); 
}

GalleryTeaser.prototype.initCallback = function (carousel, state) {
	var self = this;
/* 
  if (state == 'init') {
    if (self.opt.urlInit) {
      $.ajax({
        url: self.opt.urlInit,
        success: function (json) {
          carousel.options.start = json.start;
        },
        dataType: 'json',
        async: false,
      });
    }
  }
 */  
  
}



GalleryTeaser.prototype.itemLoadCallback = function (carousel, state) { 
	var self = this;
	
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) { 
        return;
    }
	
	/* @TODO */
	//https://github.com/jsor/jcarousel/issues/169
	

    $.get(
        self.opt.url,
        {
            first: carousel.first,
            last: carousel.last
        },
        function(json) {  
            self.itemAddCallback(carousel, carousel.first, carousel.last, json);
        },
		'json'
    );

};

GalleryTeaser.prototype.itemAddCallback = function (carousel, first, last, json) {
	var self = this;

    // Set the size of the carousel
    carousel.size(json.total);
    $.each(json.photos, function(i, item) {
		// carousel.add(first + i, self.getItemHTML(item.thumb, item.href));
		carousel.add(first + i, self.getItemHTML(item));
	   
	 	if ((!self.visible) && (i == json.photos.length-1)) {
			//self.$el.show();
			self.$el.css('visibility','visible');
			self.visible = true
		} 
    });
};
/* 
GalleryTeaser.prototype.getItemHTML = function (thumb, href) {
    return '<a href="'+ href +'"><img src="' + thumb + '" alt="" /></a>';
};
 */
 
GalleryTeaser.prototype.getItemHTML = function (item) {
    var html; 
	if (item.album) {
		html = '<li class="splitter"><a href="'+item.href+'">Album <strong>'+item.label+'</strong></a></li>'
	} else {
		html = '<li';
		html += (item.active) ? ' class="current"' : '';
		html += '><a href="'+item.href+'"><img src="' + item.thumb + '" alt="" />';
		html += (item.active) ? '<span>'+item.label+'</span>' : '';
		html += '</a></li>';
		//class="splitter"><a href="'+item.href+'">Album <strong>'+item.label+'</strong></a></li>'
	}
	return html
};
/**/


/* ************************************************

   Document ready 

*/
$(function(){

	/* Aktywacja wystawiania ocen */
	$('.scorebar_active').scorebarClicker();
	
	
	/* Wyjazdy - rozwijanie poszczególnych uczestników */ 
	$('table.triplisting .switch').click( function () {
		$(this).parent().find('.details').toggleClass('shown');
		return false
	});
	/* Wyjazdy - rozwijanie archiwalnych */
	$('#triplisting-past-trigger').click( function () {
		$( $(this).attr('href') ).toggle();
		//return false
	} )

	
	/* Wyszukiwarka boczna - rozwijanie */
	$('#multisearch h3').click( function () {
		if ($(this).parent().hasClass('active')) {
			$(this).siblings().slideUp('fast',function() {
				$(this).parent().removeClass('active');
			});
		} else {
			$('#multisearch .active form').slideUp('fast',function() {
				$(this).parent().removeClass('active');
			});
			$(this).siblings('form').slideToggle('fast',function() {
				$(this).parent().toggleClass('active');
			});
		} 
	});
	
	
	/**
	 * Wyszukiwarka boczna - szerokość select'ów w IE 
	 * @todo min-width = init width
	 */
	 
	if ($.browser.msie) {
		$('#main:not(.home) #multisearch, .objectcombo').each(function(){
			var $selects = $('select', this);
			var width = $selects.width();
			// var height = $selects.height();
			$selects
			.wrap('<span class="select-wrap"></span>')
			.mousedown(function(){
				$(this).css({"width":"auto", "position":'absolute'});
			})
			.blur(function(){
				$(this).css({"width":width+'px', "position":'static'});
			})
			.change(function(){
				$(this).css({"width":width+'px', "position":'static'});
			})
			//.parent().height(height+2);
		})
	}
	
	
	/**
	 * Przełączanie trybu wyszukiwarki
	 */
	var $searchbox = $('#searchbox');
	$searchbox.find('.toggler a, h2').click(function () {
		var $exts = $searchbox.find('.ext')
	
		$exts.fadeToggle( 222, function () { 
			if ($exts.filter(':animated').length <= 1) {
				$searchbox.toggleClass('extended');
				//$exts.css('visibility','visible')
			}
		});
		
		return false
	} );
	
	
	/**
	 * Rotowanie numerów telefonu
	 */
	(function ($self) {
		if (!$self.length) return; 
		
		var 
		markup = '<span class="n">',
		$panes = $self.find('img')
		;
		
		$panes.each(function () {
			markup += '<a href="#"></a>'
		});
		markup += '</span>';
		
		var $nav = $(markup);
		
		$self.append($nav);
		
		$nav.tabs( $panes,{
			effect: 'fade',
			fadeOutSpeed: 200,
			fadeInSpeed: 0,
			rotate: true
		} )
		.slideshow( {
			autoplay: true,
			interval: 3000
		} );		
		
	})($('div.infoline'));
	
	//var $infoline = $('#infoline');
/* 	$infoline.append()
	$("#infoline .switch").tabs("#infoline .pane", {
		effect: 'fade',
		fadeOutSpeed: 600,
		fadeInSpeed: 400,
		// start from the beginning after the last tab
		rotate: true
	})
	.slideshow({
		autoplay: true,
		interval: 3000
	});	 */
		
	
	/* Aktywacja przeglądarki zdjęć */
	if ($('#survey').length) {
		$('.picviewer').picViewer({time:false})
	} else {
		$('.picviewer').picViewer() 
	}
	
	
	/* Aktywacja zakładek na s. głównej */
	/* $('#home-catalogue .box-hd').tabz({clActive:'current'}); */
	
	
	/* Przycinanie listy krajów do 12 elementów */
	(function(max) { 
		var $pl = $('ul.poplocations.shortened > li'); 
		if ($pl.length > max) {
			var $pl_over = $pl.eq(max-1).nextAll().hide();			
			var hidden = true;
			var label = 'wyświetl wszystkie';
			var $toggler = $('<a href="#"/>')
				.text(label)
				.bind( 'click', function () {
						var $this = $(this);
						$pl_over.toggle();
						if (!hidden) { 
							$this.text(label).toggleClass('minimize'); hidden = true;
						} else {
							$this.text('pozostaw tylko '+max).toggleClass('minimize'); hidden = false;
						}
						return false
					})				
			$pl.parent().after( $('<p/>').addClass('poplocations_toggler').append($toggler) );
		};		
	})(12);	
	
	
	/* Rozwijanie ocen cząstkowych przy obiekcie i nie tylko */
	$('.subscores li')
		.filter( function () {
			//if (!$(this).parents('div.reviewext').length) return true;
			// zostawic (tj. zwrocic true) powinno gdy nie ma rodzica .reviewext
			return !$(this).parents('div.reviewext').length
		} )
		.hoverIntent( {
			sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
			interval: 150, // number = milliseconds for onMouseOver polling interval
			timeout: 250, // number = milliseconds delay before onMouseOut
			over: function() { $(' dd.subs', this).show(); }, 
			out: function() { $(' dd.subs', this).hide(); }
		} )
		// zamykanie listy przy kliknięciu:
		.click( function () {
			$(' dd.subs', $(this)).toggle();
		} )
		// ...i dodanie 'x' zamykającego listę:
		.find('dd.subs').append('<a class="dismiss" href="#">'+config.lang.zwin+'</a>').find(':last').click( function () { $(this).parents('dd').hide(); return false } );

	
	/**
	 * Klikalne obszary
	 */
	//$('li.review').clicky('a.more','h3.score');
	$('ul.objects li.obj').clicky('h3 a','.thumb, span.score');
	$('.catalogue-mostly').prev('h2').clicky();
	$('.weather-days li.city .h').clicky();
	$('div.album .summary').clicky();
	
	
	/**
	 * Date picker
	 */	
	$.tools.dateinput.localize("pl", {
		months: 'Styczeń,Luty,Marzec,Kwiecień,Maj,Czerwiec,Lipiec,Sierpień,Wrzesień,Październik,Listopad,Grudzień',
		shortMonths: 'Sty,Lut,Mar,Kwi,Maj,Cze,Lip,Sie,Wrz,Paź,Lis,Gru',
		days: 'Niedziela,Poniedziałek,Wtorek,Środa,Czwartek,Piątek,Sobota',
		shortDays: 'Ni,Po,Wt,Śr,Cz,Pt,So'
	});
	// Inicjalizacja 
	$(".datepicker :text").dateinput({
		lang: 'pl',
		format: 'yyyy-mm-dd', 
		min: 2,
		selectors: true
	});
	// Pokazywanie kalendarza po kliknięciu ikony
	$('.datepicker').each(function () {
		var cal = $(':text', this).eq(0).data('dateinput');
		$(this).find('img').toggle(
			function () {
				cal.show();
				return false
			},
			function () {
				cal.hide();
				return false
			}
		)
	});
	// Aktualizowanie drugiego pola (powrót) po wybraniu daty wyjazdu
	/*
	$('#searchbox .datepicker:first :text').data("dateinput").change(function() {
		$("#searchbox .datepicker:last :text").data("dateinput").setMin(this.getValue(), true);
	});	
	*/
	
	
	/**
	 * Zakładki na stronie kategorii
	 * @requires JQuery Tools
	 */
	var $cat_teaser = $("#cat-teaser");
	$cat_teaser.find(".pagination").tabs($cat_teaser.find(" .panes > div"), {
		effect: 'slide', 
		// start from the beginning after the last tab
		rotate: true
		//tabs: 'li'
	});
	
	$cat_teaser.find(".minitabs").tabs($cat_teaser.find(" .panes > div"), {
		effect: 'slide', 
		rotate: true,
		tabs: 'li'
	})
	.slideshow({
		interval: 5000,
		autoplay: true
	});
	
	var $cat_cols = $("#cat-cols");
	$cat_cols.find(".pagination").tabs("#cat-cols .panes > div", {
		effect: 'fade',  
		rotate: true,  
		onBeforeClick: function(event, i) {
	
			// get the pane to be opened
			var pane = this.getPanes().eq(i);
	
			// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
			if (pane.is(":empty")) {
				// load it with a page specified in the tab's href attribute 
				pane.html('<div class="loader"><i></i><span>pobieranie ofert...</span></div>');
				pane.load(this.getTabs().eq(i).attr("href"));
			}
		}
	});		

	
	/* Zapraszanie znajomych */
	$('#invite')
	.find('.way').click( function () {
		$(this)
		.siblings('.way')
		.removeClass('way_active')
		.end()
		.addClass('way_active')
		//.find('h3 :radio').each( function() { attr('checked',!$(this).is(':checked')) })
	} );
	
	/* in-field label */
	$(':input[title]').inFieldLabel();
	/* .each(function() {
		var $this = $(this);
		if($this.val() === '') {
			$this.val($this.attr('title'));
		}
		$this.focus(function() {
			if($this.val() === $this.attr('title')) {
				$this.val('');
			}
		});
		$this.blur(function() {
			if($this.val() === '') {
				$this.val($this.attr('title'));
			}
		});
	});
	 */
	
	/**
	 * Obsługa tabelki z uczestnikami wyjazdu
	 */
	(function() {
		var
			min = $('#participants-min_num').html(),
			max = $('#participants-max_num').html(),
			$people = $('#offer-bookingform #participants'),
			$tpl_row = $people.find('> li.template')
		;
		
		$tpl_row.removeClass('template').detach();
		
		var num = $people.children(":not('.template')").length;
		if (num < min || num == 0) {
			$tpl_row.clone().appendTo($people)
		}
		
		$people
		.delegate('.btn-add', 'click', function () {
			if ($people.children().length < max) {
				$tpl_row.clone().hide().appendTo($people).fadeIn();
			} else {
				alert('Dodano maksymalną ilość osób.')
			}
			return false
		})
		.delegate('.btn-del', 'click', function () { 
			if ($people.children().length > min) { 
				$(this).closest('li').fadeOut().remove()
			}
			return false
		});
		
	})(); 
	/**/
	
	
	/**
	 * Obsługa ankietki
	 */
	(function () {
		var $poll = $('form.poll');
		$poll.find('.row').each(function () {
			
			var $trigger = $("input.trigger", this); 
			if (!$trigger.length) return;
			var $target = $();
			$("input.target", this).each(function () {
				//console.log($('#'+ $(this).get(0).value ));
				$target = $target.add( $('#'+ $(this).get(0).value).get(0) );
				//console.log($target);
			})
			
			
			$trigger
			.parent('label').siblings().andSelf()
			.click(function (event) {
				var $input = $('input', this);
				/*
				w sumie to tak dla upośledzonych przeglądarek które nie włączają inputa wewnątrz labela
				if (event.target.type !== "radio") {
					$input.attr('checked', !$input.get(0).checked);
					if (event.target.nodeName !== "A") event.preventDefault()
				}
				*/
				if ($trigger.get(0).checked) {
					$target.slideDown();
				} else {
					$target.slideUp();
				}	
			
			})
			
		})
	})();
	
	
	
}) // Document ready
/* ************************************************ */

if (typeof(config) === 'undefined') var config = {};

config.colorbox = {
	opacity: .4,
	transition: 'none'
}
config.jqModal = { 
	overlay: config.colorbox.opacity*100
}
//config.picviewer.slideshow = false;

/* do rozszerzania config'a można też użyć narzedzia: $.extend(config, nowe, nowe, ...); */

config.lang = {
	zwin: 'zwiń',
	poprzednie: 'poprzednie',
	nastepne: 'następne'
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   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
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     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'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    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);
}



