function updateSelect2() {
	if ($("select1").value != "0") {
		if ($("select2")) $("divForSelect2").removeChild($("select2"));
		if ($("select3")) $("divForSelect3").removeChild($("select3"));
	
		lockSelects(true);
		$("divForSelect2").innerHTML = "<p>Wczytywanie danych...</p>";
	
		new Ajax.Request('/gryjava/ajax.php', {
			method:'post',
			parameters: {category: $("select1").value},
			onSuccess: function(transport) {
				var response = transport.responseText;
				$("divForSelect2").innerHTML = response;
				
				lockSelects(false);
		    },
		    onFailure: function(){ /*alert(':/')*/ }
		});
	}
}

function updateSelect3() {
	if ($("select2").value != "0") {
		if ($("select3")) $("divForSelect3").removeChild($("select3"));
	
		lockSelects(true);
		$("divForSelect3").innerHTML = "<p>Wczytywanie danych...</p>";
	
		new Ajax.Request('/gryjava/ajax.php', {
			method:'post',
			parameters: {category: $("select1").value, manufacturer: $("select2").value},
			onSuccess: function(transport) {
				var response = transport.responseText;
				$("divForSelect3").innerHTML = response;
				
				lockSelects(false);
		    },
		    onFailure: function(){ /*alert(':/')*/ }
		});
	}
}

function lockSelects(mode) {
	if ($("select1")) $("select1").disabled = mode;
		
	if ($("select2")) $("select2").disabled = mode;
		
	if ($("select3")) $("select3").disabled = mode;
}

function goToGryJava() {
	//alert($("select1").value + " " + $("select2").value + " " + $("select3").value);
	document.location.href = "/gryjava/" + $("select1").value + "/" + $("select2").value + "/" + $("select3").value + ".htm";
}

function checkGrykomputeroweAddonForm(mode) {
	if (document.getElementById("game").value.length == 0) {
		alert("Proszę wpisać nazwę gry.");
		document.getElementById("game").focus();
		
		return false;
	}

	if (document.getElementById("content_temp").value.length <= 7) {
		alert("Proszę wpisać " + mode + " do gry.");
		document.getElementById("content_temp").focus();
		
		return false;
	}

	if (document.getElementById("size")) {
		re = /^[0-9,\.]+$/;
		
		if (!document.getElementById("size").value.match(re)) {
			alert("Proszę wpisać rozmiar pliku.");
			document.getElementById("size").focus();
			
			return false;
		}
	}
	
	return true;
}

function checkGrykomputeroweAddonFormImage(mode) {
	if (document.getElementById("game").value.length == 0) {
		alert("Proszę wpisać nazwę gry.");
		document.getElementById("game").focus();
		
		return false;
	}

	
	if (document.getElementById("image_1")) {
		re = /\.(jpg|jpeg)$/i;
		
		var i = 1;
		
		while (document.getElementById("image_" + i)) {
			if (document.getElementById("image_" + i).value.length > 0 && !document.getElementById("image_" + i).value.match(re)) {
				alert("Proszę wybrać plik z rozszerzeniem jpg, jpeg dla screena #" + i + ".");
				document.getElementById("image_" + i).focus();
				
				return false;
			}
			
			i++;
		}
	}
	
	return true;
}

function checkUrl(url) {
	window.open(url, null, "status=1, height=400, width=600, resizable=0");
}

function checkSearchForm() {
	if ($("searchQuery").value.length <= 3) {
		alert("Długość poszukiwanej frazy powinna być dłuższa niż 3 znaki.");
		return false;
	}
	
	if (!checkIfIsCheckedOneOrMoreCheckboxes()) {
		alert("Zaznacz przynajmniej jeden obszar wyszukiwnia");
		return false;
	}
	
	return true;
}

function checkIfIsCheckedOneOrMoreCheckboxes() {
	var i = 1;
	
	while (true) {
		var element = $("area[" + i + "]");
		
		if (!element) {
			break;
		}
		
		if (element.checked == true) {
			return true;
		}
		
		i++;
	}
	
	return false;
}

function searchFormCheckAllAreas() {
	var mode = $("area[0]").checked;
	var i = 1;
	
	while (true) {
		var element = $("area[" + i + "]");
		
		if (!element) {
			break;
		}
		
		element.checked = mode;
		
		i++;
	}
}

/////////////////////////////////////////////////

var inputTypeFileCounter = 2;

function addInputFile(div, label) {
	if (inputTypeFileCounter <= 10) {
		var oHr = document.createElement("hr");
		
		var oP0 = document.createElement("p");

		oLabel0 = document.createElement("label");
		oLabel0.innerHTML = "Krótki opis pliku (do 255 znaków):";
		oLabel0.setAttribute("for", "description_" + inputTypeFileCounter);
		
		oInput0 = document.createElement("input");
		oInput0.setAttribute("type", "text");
		oInput0.setAttribute("name", "description[" + inputTypeFileCounter + "]");
		oInput0.setAttribute("id", "description_" + inputTypeFileCounter);
		
		oP0.appendChild(oLabel0);
		oP0.appendChild(oInput0);
	
		var oP1 = document.createElement("p");
		var oLabel = document.createElement("label");
		oLabel.setAttribute("for", "image_" + inputTypeFileCounter);
		oLabel.innerHTML = label + " #" + inputTypeFileCounter + " do gry:";
		
		oP1.appendChild(oLabel);
		
		var oP2 = document.createElement("p");
		oP2.setAttribute("style", "padding-bottom: 2px;");
		var oButton = document.createElement("input");
		oButton.setAttribute("type", "button");
		oButton.setAttribute("value", "+");
		oButton.setAttribute("class", "addInputFile");
		oButton.setAttribute("onclick", "addInputFile('" + div + "', '" + label + "');");
		
		var oInput = document.createElement("input");
		oInput.setAttribute("type", "file");
		oInput.setAttribute("name", "image[" + inputTypeFileCounter + "]");
		oInput.setAttribute("id", "image_" + inputTypeFileCounter);
		
		oP1.appendChild(oButton);
		oP1.appendChild(oInput);
		
		document.getElementById(div).appendChild(oHr);
		document.getElementById(div).appendChild(oP0);
		document.getElementById(div).appendChild(oP1);
		document.getElementById(div).appendChild(oP2);
	
		inputTypeFileCounter++;
	}
}

/////////////////////////////////////////////////

var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "Tekst pogrubiony: [b]tekst[/b]  (alt+b)";
i_help = "Tekst kursywą: [i]tekst[/i]  (alt+i)";
u_help = "Tekst podkreślony: [u]tekst[/u]  (alt+u)";
q_help = "Cytat: [quote]tekst[/quote]  (alt+q)";
c_help = "Pokaż kod: [code]kod[/code]  (alt+c)";
l_help = "Lista: [list]tekst[/list] (alt+l)";
o_help = "Lista uporządkowana: [list=]tekst[/list]  (alt+o)";
p_help = "Wstaw obrazek: [img]http://adres_obrazka[/img]  (alt+p)";
w_help = "Wstaw adres: [url]http://adres[/url] or [url=http://adres]Tekst adresu[/url]  (alt+w)";
a_help = "Zamknij wszystkie otwarte tagi bbCode";
s_help = "Kolor czcionki: [color=red]tekst[/color]  Rada: możesz także podać color=#FF0000";
f_help = "Rozmiar czcionki: [size=x-small]mały tekst[/size]";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.post.helpbox.value = eval(help + "_help");
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;

	if (document.post.message.value.length < 2) {
		formErrors = "Musisz wpisać wiadomość przed wysłaniem";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	//var txtarea = document.post.message;
	
	var txtarea = document.getElementById("content_temp");
	
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	//var txtarea = document.post.message;
	
	var txtarea = document.getElementById("content_temp");

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}


function bbstyle(bbnumber) {
	//var txtarea = document.post.message;
	
	var txtarea = document.getElementById("content_temp");

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.post.addbbcode' + butnumber + '.value');
			eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.post.addbbcode' + butnumber + '.value');
				eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.post.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.post.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

/////////////////////////////////////////////////

var currentDd = null;

var SlideMenu = Class.create();
SlideMenu.prototype = {
	initialize: function(id) {
		this.id = id;
		this.elements = new Array();

		if ($(this.id)) {
			var childs = $(this.id).childElements();
			var childsLength = childs.length;
			
			var dt;
			var dd;
			
			for (var i = 0; i < childsLength; i++) {
				var child = childs[i];
				
				switch (child.tagName.toLowerCase()) {
					case "dt":
						dt = (child.className != "empty") ? new SlideMenu_Dt(child) : null;
						
						break;
					case "dd":
						dd = new SlideMenu_Dd(child);
						
						if (child.id != firstLoadedTab) {
							child.hide();
						}
						
						if (dt instanceof SlideMenu_Dt && dd instanceof SlideMenu_Dd) {
							pair = new SlideMenu_Pair(dt, dd);
							
							this.elements.push(pair);
							
							if (dd.element.id == firstLoadedTab) {
								pair.dd.open();
								currentDd = dd;
							}
							
							dt = null;
							dd = null;
						}
						
						break;
				}
			}
		}
	}
}

var SlideMenu_Pair = Class.create();
SlideMenu_Pair.prototype = {
	initialize: function(dt, dd) {
		this.dt = dt;
		this.dd = dd;

		dt.element.onclick = function() {
			if (dd != currentDd) {
				if (!dd.isOpened) {
					dd.open();
				}
				else {
					dd.close();
				}

				currentDd = dd;
			}
		}
	}
}

var SlideMenu_Dt = Class.create();
SlideMenu_Dt.prototype = {
	initialize: function(element) {
		this.element = element;
	}
}

var SlideMenu_Dd = Class.create();
SlideMenu_Dd.prototype = {
	initialize: function(element) {
		this.element = element;
		this.isOpened = false;
	},

	open: function() {
		if (currentDd != null) {
			currentDd.close();
		}
		
		if (!this.isOpened) {
			//new Effect.SlideDown(this.element, {duration:0.1});
			this.element.show();
			this.isOpened = true;
		}
	},

	close: function() {
		if (this.isOpened) {
			//new Effect.SlideUp(this.element, {duration:0.1});
			this.element.hide();
			this.isOpened = false;
		}
	}
}

function initMenu() {
	var menu = new SlideMenu("scoresRoot");
}

Event.observe(window, "load", initMenu, false);

if (top.location.href != self.location.href) {
	alert("Nie kradnij!");
	
	top.location.href = "http://gryzonie.pl";
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// shoutbox
function shoutboxInsertEntry() {
	var errorMessages = new Array;
	errorMessages[1] = 'Aby dodać wpis do shoutboxa musisz być zalogowany.';
	errorMessages[2] = 'Nie możesz dodawać wpisów w tak krótkim odstępie czasu.';
	
	var entry = trim($("shoutboxEntry").value);
	
	if (entry.length < 1) {
		alert("Wpisz treść wpisu.");
		return false;
	}
	
	new Ajax.Request('/shoutbox/controller.php', {
		method:'post',
		parameters: {
			mode: "newEntry",
			shoutboxEntry: entry
		},
		onCreate: function() {
			$("shoutboxSubmit").disabled = true;
			$("shoutboxEntry").disabled = true;
		},
		onSuccess: function(transport){
			var response = transport.responseText || 0;
			response = parseInt(response);
			
			if (response > 0) {
				alert(errorMessages[response]);
				
				$("shoutboxSubmit").disabled = false;
				$("shoutboxEntry").disabled = false;

				return false;
			}
			
			$("shoutboxEntry").value = "";
		},
		onComplete: function() {
			$("shoutboxSubmit").disabled = false;
			$("shoutboxEntry").disabled = false;
			$("shoutboxEntry").focus();
		},
	    onFailure: function() {
			/*alert(':/')*/
		}
	});
	
	return false;
}

var runShoutbox = true;

function shoutboxAjaxUpdater() {
	if (runShoutbox == true) {
		new Ajax.Request('/shoutbox/controller.php', {
			method: 'post',
			onSuccess: function(transport){
				var response = transport.responseText;
				$("shoutbox").innerHTML = response;
			},
			onFailure: function(){
				/*alert(':/')*/
			}
		});
		
		setTimeout("shoutboxAjaxUpdater()", 10000);
	}
}

function runShoutboxAjaxUpdater() {
	runShoutbox = true;
	
	shoutboxAjaxUpdater();
}

function stopShoutboxAjaxUpdater() {
	runShoutbox = false;
}

Event.observe(window, "load", shoutboxAjaxUpdater, false);

//function ajaxUpdater() {
//	new Ajax.PeriodicalUpdater('shoutbox', '/shoutbox/controller.php', {
//		method: 'post',
//		frequency: 10,
//		decay: 0,
//		onComplete: function() {
//			//$("shoutbox").scrollTop = $("shoutbox").scrollHeight;
//		}
//	});
//}
//
//Event.observe(window, "load", ajaxUpdater, false);

function jumpToUrl(url) {
	if (url.length > 0) {
		document.location.href = url;
	}
}

function changeProductAmount(productId, mode) {
	var v = parseInt($("amount[" + productId + "]").value);
	
	if (mode == 1 || (mode == -1 && v > 0)) {
		$("amount[" + productId + "]").value = v + mode;
		
		if ($("makeAnOrderItemsAmountsChangedInfo")) {
			$("makeAnOrderItemsAmountsChangedInfo").style.display = "block";
			$("makeAnOrderSubmitButton").disabled = true;
		}
	}
}

function removeProduct(productId, productName) {
	if (confirm('Czy na pewno chcesz usunąć ' + productName + ' ze swojego koszyka?')) {
		document.location.href = '/sklep/basket.php?mode=removeProduct&id=' + productId;
	}
}

function validateMakeAndOrderForm() {
	if (trim($("buyer[name]").value) == "") {
		alert("Proszę wpisać imię.");
		return false;
	}
	if (trim($("buyer[surname]").value) == "") {
		alert("Proszę wpisać nazwisko.");
		return false;
	}
	if (trim($("buyer[street]").value) == "") {
		alert("Proszę wpisać nazwę ulicy.");
		return false;
	}
	if (trim($("buyer[building]").value) == "") {
		alert("Proszę wpisać numer budynku.");
		return false;
	}
	
	re = /^[0-9]{2}-[0-9]{3}$/;
	
	if (!trim($("buyer[postCode]").value).match(re)) {
		alert("Proszę wpisać poprawny kod pocztowy.");
		return false;
	}
	
	if (trim($("buyer[city]").value) == "") {
		alert("Proszę wpisać nazwę miejscowości.");
		return false;
	}
	
	return true;
}

/*******************************************************************************/
function onChangeRankType(value) {
	if (value != '') {
		switch (value) {
			case '1':
				$("rankGameIdFieldset").style.display = "none";
				$("gameId").disabled = true;
				$("rankDatesFieldset").style.display = "none";
				$("from_day").disabled = true;
				$("from_month").disabled = true;
				$("from_year").disabled = true;
				$("to_day").disabled = true;
				$("to_month").disabled = true;
				$("to_year").disabled = true;
				break;
			case '2':
			case '3':
			case '4':
			case '5':
				$("rankGameIdFieldset").style.display = "block";
				$("gameId").disabled = false;
				$("rankDatesFieldset").style.display = "none";
				$("from_day").disabled = true;
				$("from_month").disabled = true;
				$("from_year").disabled = true;
				$("to_day").disabled = true;
				$("to_month").disabled = true;
				$("to_year").disabled = true;
				break;
			default:
				$("rankGameIdFieldset").style.display = "block";
				$("gameId").disabled = false;
				$("rankDatesFieldset").style.display = "block";
				$("from_day").disabled = false;
				$("from_month").disabled = false;
				$("from_year").disabled = false;
				$("to_day").disabled = false;
				$("to_month").disabled = false;
				$("to_year").disabled = false;
		}
	}
}


function bugReportWindow(url) {
	window.open("/zglos-blad.htm?url=" + url, "bugReportWindow", "status=1,height=300,width=450,resizable=0");
	
	return false;
}
