/**
 * @author Karol Drągowski
 */

// odścieżanie strony
function odswiez() {
	window.location.reload();
}

// ustawianie stałej szerokości

jQuery.fn.extend( {
	strictWidth : function() {
		return this.css('width', this.width() + 'px');
	}
});

// 1 zwraca najdłuższy ciąg znaków wystepujący w napisie(pierwszy argument)
// pomiędzy znakami { i } lub podanymi jako 2 i 3 argument

function $between() {
	var s = arguments[0];
	var ld = '{';
	var rd = '}';
	if (arguments[1] && arguments[2]) {
		ld = arguments[1];
		rd = arguments[2];
	}
	return s.substring(s.indexOf(ld) + 1, s.lastIndexOf(rd))
}

// 3 funkcja do kolorowania wierszy tabeli
function paintRows(elem) {
	$('tr', elem).removeClass('hard');
	$('tr[td]:odd', elem).addClass('hard');
}

// 4 funkcje do obsługi dodawania produktów do koszyka
function updateIlosc(zmiennik, roznica) {
	var $wkoszyku = $('#jqwkoszyku');
	var $wkoszykuwartosc = $('#jqkoszkwartosc');
	var $podmiana = $('#jqpodmiana');
	var newwart = parseFloat($wkoszykuwartosc.text()) + parseFloat(roznica);
	$wkoszykuwartosc.text(newwart.toFixed(2));

	var ile = $wkoszyku.text();
	ile = parseInt(ile) + zmiennik;
	$wkoszyku.text(ile + '');
	$podmiana.text(odmienRzeczownik(ile));
	return ile;
}

function setIlosc(liczba, wartosc) {
	$('#jqwkoszyku').text(liczba + '');
	$('#jqpodmiana').text(odmienRzeczownik(liczba));
	$('#jqkoszkwartosc').text(parseFloat(wartosc).toFixed(2));
}

// funkcje do obsługi zapamiętywania starych wartości pól formularzy i
// kolorowania pól w zalezności od ich stanu

function setChangeEvent(obj) {
	if (arguments[1])
		$(obj).bind('keyup', function() {
			$(this).removeClass("valerr updated");
			if (!compareValues(this))
				$(this).addClass("vc changed");
			else
				$(this).removeClass("vc changed");
		});
	else
		$(obj).bind('keyup', function() {
			$(this).removeClass("valerr updated").addClass('changed');
			if (!compareValues(this))
				$(this).addClass("vc");
			else
				$(this).removeClass("vc");
		});
}

function setUpdated(objs) {
	objs.each(function() {
		this.oldvalue = $(this).val();
		if ($(this).is('.changed'))
			$(this).removeClass("changed valerr").addClass("updated");
	})
}

function setBad(objs) {
	objs.each(function() {
		$(this).removeClass("changed updated").addClass("valerr");
	})
}

function saveFieldsValues(objs) {
	var arg1 = arguments[1];
	objs.each(function() {
		this.oldvalue = $(this).val();
		if (arg1)
			setChangeEvent(this, arg1);
		else
			setChangeEvent(this);
	})
}

function compareValues(obj) {
	return obj.oldvalue == $(obj).val();
}

// 5 funkcje obsługi pojawiających się i znikających komunikatów
function printInNewWindow(echo) {
	var okno = window.open();
	okno.document.write('<html><head><title></title>');
	okno.document
			.write('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">');
	okno.document.write('</head><body onclick="window.close();"><pre>');
	okno.document.write(echo);
	okno.document.write('</pre></body></html>');
	okno.document.close();
	okno.focus();
}

var $infTimeId;

function loadData(json) {
	if (json)
		$.each(json, function(k, o) {
			if ($(k).size() > 0)
				$(k).empty().html(o);
		});
}

function prepareInfo() {
	var inf = $('#info');
	if (inf.size() == 0)
		inf = $(
				'<div id="info" class="flyTop"><div id="wcontent"></div><div id="wbottom"><div id="infIco"></div></div></div>')
				.prependTo('body');
	else {
		if ($infTimeId)
			clearTimeout($infTimeId);
		inf.css('display', 'none');
	}
	if (!inf.is('[#wtop]')) {
		inf
				.prepend('<div id="wtop"><img src="images/w_minimalize.png" id="wdisplay"><img src="images/w_close.png" id="wclose" title="Zamknij"></div>');
		$('#wdisplay:eq(0)', inf).bind('click', function() {
			if ($(this).attr('src').indexOf('min') > 0) {
				$(this).attr( {
					'src' : "images/w_maxymalize.png",
					'title' : 'Maksymalizuj'
				})
				$('#wcontent:eq(0)', inf).slideUp();
			} else {
				$(this).attr( {
					'src' : "images/w_minimalize.png",
					'title' : 'Minimalizuj'
				})
				$('#wcontent:eq(0)', inf).slideDown();
			}
		}).css('cursor', 'pointer');
		$('#wclose:eq(0)', inf).bind('click', function() {
			$hideInfo();
		}).css('cursor', 'pointer');
		var left = Math.round(($(document).width() - inf.width()) / 2);
		inf.css('left', left + 'px')
	} else {
		// resetowanie
		$('#wdisplay:eq(0)', inf).attr( {
			'src' : "images/w_minimalize.png",
			'title' : 'Minimalizuj'
		});
		$('#wcontent:eq(0)', inf).slideDown();
	}
	return inf;
}

$showInfo = function(json) {
	// printObject(json);
	/*
	 * if(json.devmsg) alert(json.devmsg);
	 */
	var typ = (json.typ ? json.typ : 'msg');
	var actionAfter = (json.runAfter ? json.runAfter + '; ' : '; ');
	var hideafter = (json.hideafter ? json.hideafter : 3000);
	loadData(json.data);
	if (json.echo)
		printInNewWindow(json.echo);
	if (json.runBefore)
		eval(json.runBefore + '; ');
	inf = prepareInfo();
	if (json.msg)
		$('#wcontent:eq(0)', inf).html(json.msg);
	else if (json.dontShow)
		$('#wcontent:eq(0)', inf).html('');

	if (json.runMiddle)
		eval(json.runMiddle + '; ');
	inf.removeClass().addClass(typ + ' flyTop');
	$('div#infIco', inf).ifixpng();
	if ($('#wcontent:eq(0)', inf).html()) {
		if (hideafter > 0)
			inf.fadeIn("slow",
					function() {
						$infTimeId = setTimeout(actionAfter + "$hideInfo()",
								hideafter);
					});
		else
			inf.fadeIn("slow", function() {
				eval(actionAfter);
			});
	} else
		eval(actionAfter);
}

function $hideInfo() {
	if ($infTimeId)
		clearTimeout($infTimeId);
	var speed = 'slow';
	$('#info').fadeOut(speed, function() {
		$('div#infIco', this).iunfixpng();
	});
}

// 6 funkcje obsługi paska ładowania danych
function $showLoad() {
	var lo = $('#load');
	if (lo.size() == 0)
		lo = $('<div id="load" class="flyBottom">Proszę czekać...</div>')
				.prependTo('body');
	else
		lo.css('display', 'none');
	lo.fadeIn();
}

function $hideLoad() {
	var speed = (arguments[0] ? arguments[0] : 'slow');
	$('#load').fadeOut(speed);
}

// 7 funkcja do podliczania wartości z koszyka
function podliczKoszyk() {
	var razem = 0;
	var koszyk = $('#koszyk');
	$('td[@id^=jqcena_brutto]', koszyk).each(
			function(i, o) {
				var id = $between(this.id, '[', ']');
				var wartosc = parseFloat($(this).text())
						* parseInt($('input[@name="jqilosc[' + id + ']"]',
								koszyk).val());
				if (isNaN(wartosc) || wartosc <= 0)
					wartosc = 0.0;
				$('td[@id="jqwartosc_brutto[' + id + ']"]', koszyk).html(
						wartosc.toFixed(2));
				razem = razem + wartosc;
			});
	$('#jqrazemwartosc', koszyk).html(razem.toFixed(2));
}

// 8 funkcja do usuwania niepotrzebnych wierszy w koszyku i liczniku koszyka
function removeDeleted() {
	var koszyk = $('#koszyk');
	var pozostalo = 0;
	$('input[@name^=jqilosc]', koszyk).each(function(i, o) {
		var t_val = $(o).val();
		if (int(t_val) && t_val < 1)
			$(o).parents('tr').eq(0).remove();
		else
			pozostalo++;
	});
	paintRows(koszyk);
	setIlosc(pozostalo, parseFloat($('#jqrazemwartosc', koszyk).text()));
}

// 10 funkcja do ustawiania thickboxa
function setThickboxIn($objs) {
	tb_init('a.thickbox', $objs);
}

// 12 funkcja do walidacji i wysyłania formularzy POST lub GET parametr type
// odbiera dane w obiekcie JSON
function checkAndSendForm(selector, submiturl, type) {
	var obj = $(selector);
	obj.find('input[@name=back]').remove();
	var opt = {
		url : submiturl,
		type : type,
		data : obj.formToArray(),
		dataType : "json",
		success : $showInfo,
		beforeSubmit : Validate.validateForm
	};
	if (arguments[4]) {
		opt.beforeSubmit = arguments[3];
		opt.success = arguments[4];
	} else if (arguments[3]) {
		opt.success = arguments[3];
	}
	obj.ajaxForm(opt);
}

// 14 funkcja do wypisywania nazw pól i wartości pól obiektu

function printObject(obj) {
	var ret = '';
	var sep = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	var padd = (arguments[1] ? arguments[1] : '')
	if (typeof obj == 'object')// && !obj instanceof Function)
		for ( var i in obj) {
			var v = obj[i];
			// $.each(obj, function (i,v){
			if (typeof v == 'object') {// && !v instanceof Function){
				ret += padd + '<b>' + i + '</b>:<br>';
				ret += printObject(v, padd + sep);
			} else
				ret += padd + '<b>' + i + '</b>: ' + v + '<br>';
		}// );
	else
		ret = obj;
	if (padd == '')
		printInNewWindow(ret);
	else
		return ret;
}

// 15 link przypomnij hasło
function przypomnijHaslo() {
	$('#przypomnij-haslo').bind('click', function(event) {
		$.getJSON("przypomnij-haslo.php?getcontent", function(json) {
			$showInfo(json);
		})
		return false;
	});
}

// 16 odmiana rzeczownika
function odmienRzeczownik(liczba) {
	var rzeczownik = (arguments[1] ? arguments[1] : 'produkt')
	var konc = [ 'ów', '', 'y' ];
	var przedzdo21 = {
		0 : [ 0, 0 ],
		1 : [ 1, 1 ],
		2 : [ 4, 2 ],
		5 : [ 21, 0 ]
	};
	var przedzpo21 = {
		0 : [ 1, 0 ],
		2 : [ 4, 2 ],
		5 : [ 9, 0 ]
	};
	var przel = parseInt(liczba) % 100;
	var przedz = przedzdo21;
	if (przel >= 22) {
		przedz = przedzpo21;
		przel = przel % 10;
	}

	for (k in przedz)
		if (przel >= parseInt(k) && przel <= przedz[k][0])
			return rzeczownik + konc[przedz[k][1]];
}

// zaznacz kategorię
function selectCategory(id) {
	$('a[@href^="k' + id + '-"]', $('#menucat')).addClass('current').parents(
			'ol').show();
}

// zaznacz porzadek sortowania kategorii
function selectOrderCat(order) {
	$("#selectcategoryorder option[@value=" + order + "]").attr('selected',
			'selected');
}

function inspirationLoadCategories() {
	var kategoria = $("#jqInspKategorie").val();
	$.ajax( {
				url : "twoje-inspiracje-dodaj.ax.php",
				type : "POST",
				async : false,
				data : "function=produkty&kategoria="
						+ kategoria,
				success : function(request) {
					if (request == "") {
						request = '<option value="0">-- wybierz powyżej najniższą podkategorię --</option>';
					}
					$("#id_produktu").html(request);

				}
	});
}

// zmienne i uruchamianie funkcji !!!!!!!!!!!!!!!!!!!!!!!!!!!

var $noStdAJAX;
var $wKoszyku = false;
// on ready
$(function() {
	// obsługa wyszukiwarki kolorów
	$('div#kolor-wybor a').click(function() {
		$('div#kolor-wybor img.selected').removeClass('selected');
		$(this).children().addClass('selected');
		if ($(this).children().attr('title') != 'brak')
			$('div#szukaj input#ikolor').val($(this).children().attr('title'));
		else
			$('div#szukaj input#ikolor').val('');
	});
	// pokaz - ukryj w wyszukiwarce
	$('a#pokaz-ukryj').click(
			function() {
				if (readCookie('wyszukiwarka') == 'ukryta') {
					$('div#szukaj').show('slow');
					$(this).children('img#pokaz-ukryj-strzalka').attr('src',
							'images/hide.gif');
					eraseCookie('wyszukiwarka');
				} else {
					$('div#szukaj').hide('slow');
					$(this).children('img#pokaz-ukryj-strzalka').attr('src',
							'images/show.gif');
					createCookie('wyszukiwarka', 'ukryta', 30);
				}
				;
			});

	// stan wyszukiwarki czytany z cookie
	if (readCookie('wyszukiwarka') == 'ukryta') {
		$('div#szukaj').hide('slow').addClass('hidden');
		$('a#pokaz-ukryj').children('img#pokaz-ukryj-strzalka').attr('src',
				'images/show.gif');
	}

	// ustawianie wyszukiwarki kategorii
	/*
	 * $('div#szukaj select#skategoria option').each(function(){
	 * if($(this).val()==$('div#szukaj input#hkategoria').val()) //
	 * $(this).attr('selected','selected'); });
	 */

	// zaokrąglenia w nagłówkach tabelek i formularzach
	$('table.formtab, table.colored')
			.find('tr[th]')
			.each(
					function(i, o) {
						$th = $(o).find('th');
						if ($th.size() == 1) {
							$($th)
									.css('padding', '0px')
									.html(
											'<img src="images/th_right.jpg" style="float:right;"><img src="images/th_left.jpg" style="float:left;"><div style="margin-top:4px; text-align:left;">' + $(
													$th).html() + '</div>');
						} else {
							$th
									.filter(':first')
									.css('background',
											'#EEE2BB url(images/th_left.jpg) top left no-repeat')
									.end()
									.filter(':last')
									.css('background',
											'#EEE2BB url(images/th_right.jpg) top right no-repeat');
						}
					})
	if (window.location.pathname.indexOf('koszyk.php') != -1)
		$wKoszyku = true;

	// obsługa formularzy logowania i newslettera
	checkAndSendForm('#frmlogowanie', "logowanie.ax.php"
			+ ($wKoszyku ? '?full' : window.location.search), "GET");

	checkAndSendForm("#frmnewsletter", "newsletter.ax.php", "GET");
	checkAndSendForm("#frmnewsletter2", "newsletter.ax.php", "GET");

	// dodawanie stylu do radio
	$('input:radio, input:checkbox').addClass('radio');

	// //////////////////dodaniwanie inspiracji

	checkAndSendForm('#frminspiracja', "twoje-inspiracje-dodaj.ax.php", "POST");
	checkAndSendForm('#frminspiracjaedycja', "twoje-inspiracje-edytuj.ax.php", "POST");

	$("#dodajElement").bind('click',function() {
						var elementy = "";
						if ($("#id_produktu").val() == "0") {
							var info = new Array();
							info['stat'] = false;
							info['typ'] = 'msg';
							info['msg'] = '<p>Nie został wybrany żaden produkt.<br/>Określ kategorię i wybierz produkt z listy.<br/>&nbsp;<br/></p>';
							$showInfo(info);
						} else if (!isInteger($("#ilosc").val())) {
							var info = new Array();
							info['stat'] = false;
							info['typ'] = 'msg';
							info['msg'] = '<p>Nieprawidłowa ilość produktu.<br/>Ilość produktu musi być wartością całkowitą.<br/>&nbsp;<br/></p>';
							$showInfo(info);
						} else {
							var ilosc = $("#ilosc").val();
							var produkt = $("#id_produktu").val();
							$.ajax( {
										url : "twoje-inspiracje-dodaj.ax.php",
										type : "POST",
										async : false,
										data : "function=dodaj&produkt="
												+ produkt + "&ilosc=" + ilosc,
										success : function(request) {
											$("#jqElementyInspiracji").append(
													request);
											$(".iqInspUsun").click(
													function() {
														$(this).parents(
																'.jqInspRow')
																.remove();
														return false;
													});
											var info = new Array();
											info['stat'] = false;
											info['typ'] = 'msg';
											info['msg'] = '<p>Nowy element inspiracji został dodany do listy.<br/>&nbsp;<br/></p>';
											$showInfo(info);
										}
									});
						}
					});
	
	inspirationLoadCategories();
	$("#jqInspKategorie").change(inspirationLoadCategories);
	$(".iqInspUsun").click(function() {
		$(this).parents(
				'.jqInspRow')
				.remove();
		return false;
	});

	// inicjalizacja menu
	// kategorii-----------------------------------------------------------------------//

	jqsekcjamenu = $('#menucat');
	$("div#menucat ol").each(function(i, o) {
		if (i == 1)
			$(o).addClass('menucat');
	});
	$("div#menucat ol:first").addClass('menucat');
	$("div#menucat ol.menucat ol").addClass('podmenu');
	$("div#menucat ol.menucat ol.podmenu ol").addClass('podmenu2');
	$("div#menucat ol.menucat ol.podmenu ol").removeClass('podmenu');

	// reakcja na kliknięcie opcji poziom1
	$('li[ol.podmenu]', jqsekcjamenu).each(function(i, o) {
		var a = $(o).children('a:first');
		$(a).bind('click', function() {
			var next = $(o).children('.podmenu:first');
			if ($(a).is(".active") && next.css('display')) {
				$(a).removeClass('active');
			} else {
				$('a.active').removeClass('active');
				$(a).addClass('active');
			}
			$('.podmenu:visible', jqsekcjamenu).not(next).slideUp(1);
			next.slideToggle("fast"); // zwalnia ostro w IE6
				return false;
			});
	});
	// reakcja na kliknięcie opcji poziom2
	$('li[ol.podmenu2]', jqsekcjamenu).each(function(i, o) {
		var a = $(o).children('a:first');
		$(a).bind('click', function() {
			var next = $(o).children('.podmenu2:first');
			$('.podmenu2:visible', jqsekcjamenu).not(next).slideUp(1);
			next.slideToggle("fast"); // zwalnia ostro w IE6
				return false;
			});
	});

	// wypełnianie pustych komórek tabeli
	$('td:empty').html('&nbsp');

	// odznaczanie zaznaczanego elementu
	$('a, input:button, input:image, input:radio, img').click(function() {
		this.blur()
	});

	// zapamiętywanie wartości pól które mają być aktualizowane
	saveFieldsValues($('input, textarea, select, radio', $('form.jqupdate')),
			'strict');

	// testowa obsługa błędów ajaxa
	$('body')
			.ajaxError(function(request, settings) {
				$hideLoad();
				// printObject(request);
					// printObject(settings);
					//printInNewWindow('<b>responseText</b>: ' + settings.responseText + '<br>');
				alert(settings.responseText);
				}).ajaxStart(function() {
				if (!$noStdAJAX)
					$showLoad();
			}).ajaxStop(function() {
				if (!$noStdAJAX)
					$hideLoad();
			});

	// domyślne wartości pola wyszukiwania
	var domyslnyTekst = 'podaj nazwę lub kod ...';
	$('input[@name=keywords]').each(function(i, o) {
		if ($(this).val() == '')
			$(this).val(domyslnyTekst);
	}).focus(function() {
		if ($(this).val() == domyslnyTekst)
			$(this).val('');
	}).blur(function() {
		// if($(this).val()=='')
			// $(this).val(domyslnyTekst);
		});

	// domyślne wartości pola wyszukiwania produktow niaktywnych
	var domyslnyTekst3 = 'podaj nazwę produktu ...';
	$('input[@name=keywords2]').each(function(i, o) {
		if ($(this).val() == '')
			$(this).val(domyslnyTekst3);
	}).focus(function() {
		if ($(this).val() == domyslnyTekst3)
			$(this).val('');
	}).blur(function() {
		if ($(this).val() == '')
			$(this).val(domyslnyTekst3);
	});

	// domyślne wartości pola wyszukiwania encyklopedii
	var domyslnyTekst2 = 'podaj hasło ...';
	$('input[@name=haslo]').each(function(i, o) {
		if ($(this).val() == '')
			$(this).val(domyslnyTekst2);
	}).focus(function() {
		if ($(this).val() == domyslnyTekst2)
			$(this).val('');
	}).blur(function() {
		if ($(this).val() == '')
			$(this).val(domyslnyTekst2);
	});
});

// on load
$(window).load(function() {
	// temp
		// $('#layout > tbody > tr > td').bind('click',function
		// (){alert($(this).width())});
	});

function validateemail(pole) {
	if (pole.indexOf("@") == -1 || pole.indexOf(".") == -1)
		return false;
	return true;
}

function validate_formularz_kontakt() {
	f = document.forms['formnewuser'];
	if (f.polecajacy_imie.value == "") {
		window.alert("Podaj proszę swoje imię");
		return false;
	}
	if (!validateemail(f.adresat_email.value)) {
		window.alert("Podaj prawidłowy email adresata");
		return false;
	}
	if (!validateemail(f.polecajacy_email.value)) {
		window.alert("Podaj swój prawidłowy email");
		return false;
	}
	return true;
}

function validate_platnosc() {

	f = document.forms['payform'];

	if (f.desc.value == "") {
		window.alert("Enter title!");
		return false;
	}

	if (f.amount.value == "") {
		window.alert("Enter amount!");
		return false;
	}

	f.amount.value = (parseFloat(f.amount.value) * 100);
	// alert(f.amount.value);

	return true;
}

// bestsellers
$(document).ready(
		function() {
			$('ul.bestsellers').children('li').mouseover(
					function() {
						var _a = $(this).find('a').is('a') ? $(this).find('a')
								: false;
						var img = $(this).find('img').is('img') ? $(this).find(
								'img') : false;
						var li = $('ul.bestsellers li.active');
						var img2 = li.find('img.img').is('img.img') ? li
								.find('img.img') : false;
						var _a2 = li.find('a').is('a') ? li.find('a') : false;
						li.removeClass('active');
						img2.css('display', 'none');
						_a2.css('color', '#CC6600');
						$(this).addClass('active');
						img.css('display', 'block');
						_a.css('color', 'black');
					});
			
			$('ul.najwyzej_oceniane').children('li').mouseover(function() {
				var _a = $(this).find('a').is('a') ? $(this).find('a') : false;
				var img = $(this).find('img').is('img') ? $(this).find('img') : false;
				var li = $('ul.najwyzej_oceniane li.active');
				var img2 = li.find('img').is('img') ? li.find('img') : false;
					var _a2 = li.find('a').is('a') ? li.find('a') : false;
						li.removeClass('active');
						img2.css('display','none');
						_a2.css('color','#CC6600');
				$(this).addClass('active');
				img.css('display','block');
				_a.css('color','black');
			});
		});

function CategoriesOrder(order, link, gets) {
	document.location.href = link + "?order=" + order + "" + gets;
	return true;
}

function print_r(array, return_val) {
	// Prints out or returns information about the specified variable
	// 
	// version: 909.322
	// discuss at: http://phpjs.org/functions/print_r // + original by: Michael
	// White (http://getsprink.com)
	// + improved by: Ben Bryan
	// + input by: Brett Zamir (http://brett-zamir.me)
	// + improved by: Brett Zamir (http://brett-zamir.me)
	// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // -
	// depends on: echo
	// * example 1: print_r(1, true);
	// * returns 1: 1

	var output = "", pad_char = " ", pad_val = 4, d = this.window.document;
	var getFuncName = function(fn) {
		var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
		if (!name) {
			return '(Anonymous)';
		}
		return name[1];
	};

	var repeat_char = function(len, pad_char) {
		var str = "";
		for ( var i = 0; i < len; i++) {
			str += pad_char;
		}
		return str;
	};
	var formatArray = function(obj, cur_depth, pad_val, pad_char) {
		if (cur_depth > 0) {
			cur_depth++;
		}
		var base_pad = repeat_char(pad_val * cur_depth, pad_char);
		var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char);
		var str = "";
		if (typeof obj === 'object' && obj !== null && obj.constructor
				&& getFuncName(obj.constructor) !== 'PHPJS_Resource') {
			str += "Array\n" + base_pad + "(\n";
			for ( var key in obj) {
				if (obj[key] instanceof Array) {
					str += thick_pad
							+ "["
							+ key
							+ "] => "
							+ formatArray(obj[key], cur_depth + 1, pad_val,
									pad_char);
				} else {
					str += thick_pad + "[" + key + "] => " + obj[key] + "\n";
				}
			}
			str += base_pad + ")\n";
		} else if (obj === null || obj === undefined) {
			str = '';
		} else { // for our "resource" class
			str = obj.toString();
		}
		return str;
	};

	output = formatArray(array, 0, pad_val, pad_char);
	if (return_val !== true) {
		if (d.body) {
			this.echo(output);
		} else {
			try {
				d = XULDocument; // We're in XUL, so appending as plain text
									// won't work; trigger an error out of XUL
				this
						.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
			} catch (e) {
				this.echo(output); // Outputting as plain text may work in some
									// plain XML
			}
		}
		return true;
	} else {
		return output;
	}
}

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++) {
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9")))
			return false;
	}
	// All characters are numbers.
	return true;
}