var ie = navigator.appName.indexOf('Microsoft') != -1;

function toTop() {
	window.scroll(0, 0);
}

function openNewScrollableWindow(fileName, windowName, windowHeight, windowWidth) {
	popup = window.open(shopBase + fileName, windowName, 'height = ' + windowHeight + ', width = ' + windowWidth + ', top = ' + (screen.availHeight / 2 - windowHeight / 2) + ', left = ' + (screen.availWidth / 2 - windowWidth / 2) + ', scrollbars = yes');
}

function waitAndForward(seconds) {
	setTimeout('window.location="' + shopBase + 'do/index.jsp"', seconds);
}

function changeElementDisplay(elementName) {
	document.getElementById(elementName).className = switchStyleClasses(document.getElementById(elementName).className, 'hide', 'show');
}

function switchStyleClasses(actualClassName, firstClass, secondClass) {
	var classes = new Array();
	classes = actualClassName.split(' ');
	for (var i = 0; i < classes.length; i++) {
		if (classes[i] == firstClass)
			classes[i] = secondClass;
		else {
			if (classes[i] == secondClass)
				classes[i] = firstClass;
		}
	}
	
	var newClassName = '';
	for (var i = 0; i < classes.length; i++) {
		if (i == classes.length - 1)
			newClassName += classes[i];
		else
			newClassName += classes[i] + ' ';
	}
	
	return newClassName;
}

/*
 	passes parameters inside order form
	param1 - imie i nazwisko
	param2 - ulica z numerem
	param3 - kod pocztowy
	param4 - miasto
	param5 - panstwo
*/
function passParams(param1, param2, param3, param4, param5) {
	document.getElementsByName('prop\(_delivery_name\)\.value')[0].value = param1;
	document.getElementsByName('prop\(_delivery_street\)\.value')[0].value = param2;
	document.getElementsByName('prop\(_delivery_postcode\)\.value')[0].value = param3;
	document.getElementsByName('prop\(_delivery_city\)\.value')[0].value = param4;
	document.getElementsByName('prop\(_delivery_country\)\.value')[0].value = param5;
}

function submitSearchPaging(selectNo) {
	var sSelects = document.getElementsByName('sOffset');
	document.getElementsByName('offset')[0].value = sSelects[selectNo].options[sSelects[selectNo].selectedIndex].value;
	document.getElementById('searchPaging').submit();
}

function showProducerCategories(selectedIndex) {
	var tbody = 'categoriesForProducer';
	var producers = document.getElementById('producers');
	var value = producers.options[producers.selectedIndex].value;

	/* ukrycie i wyzerowanie nieu?ywanych select?w */
	for (i = 0; i < document.getElementsByName(tbody).length; i++) {
		if (document.getElementsByName(tbody)[i].className != 'hide') {
			document.getElementsByName('temp')[i].selectedIndex = 0;
			document.getElementsByName(tbody)[i].className = switchStyleClasses(document.getElementsByName(tbody)[i].className, 'hide', 'show');
		}
	}

	/* przywr?cenie g??wnej kategorii */
	if (selectedIndex == 0) {
		document.getElementById('mainCategoryTree').className = switchStyleClasses(document.getElementById('mainCategoryTree').className, 'hide', 'show');
		return;
	}

	/* ustawienie kategorii jesli zostala wybrana */
	if (document.getElementById(value).className == 'hide')
		document.getElementById(value).className = switchStyleClasses(document.getElementById(value).className, 'hide', 'show');
}

function setChosenCategoryId() {
	var categoryId = '';
	for (i = 0; i < document.getElementsByName('temp').length; i++) {
		if ((select = document.getElementsByName('temp')[i]).selectedIndex > 0)
			categoryId = select.options[select.selectedIndex].value;
	}
	document.getElementById('propertyToSet').value = categoryId;
}

function submitProducerItemSearch(categoryId) {
	document.getElementById('producerItemSearch').submit();
}

function toggleProducers() {
	var p = document.getElementById('prod_div');
	var l = document.getElementById('prod_link');
	
	if (p.style.display == 'none') {
		p.style.display = 'block';
		l.className = 'rollOff';
	} else {
		p.style.display = 'none';
		l.className = 'rollOn';
	}
}

function submitFilterForm(index) {
	var value = document.getElementsByName('staticProducerId')[0].options[index].value;
	document.getElementById('filterProducerId').value = value;
	document.getElementById('filterForm').submit();
}

function submitProducerFilterForm(categoryId) {
	document.getElementById('filterCategoryId').value = categoryId;
	document.getElementById('filterForm').submit();
}

function refreshCart(price, id) {
	var src = document.getElementsByName('quantities[' + id + ']')[0];
	var target = document.getElementById('cartItemValue[' + id + ']');
	
	var sum = Math.round(src.value * price * 100.00) / 100.00;
	target.innerHTML = sum.toFixed(2);

	var sum = 0;
	var amounts = document.getElementsByName('cartItemValue');
	
	for (var i = 0; i < amounts.length; i++)
		sum += Math.round(amounts[i].innerHTML * 100) / 100;
	
	document.getElementById('cartSum').innerHTML = sum.toFixed(2);
}

function onlyDigits(e)
{
	var key;
	var keychar;
	
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);
	
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
		return true;
	else if ((("0123456789").indexOf(keychar) > -1))
		return true;
	else
		return false;
}

function cartInc(field) {
	var value = parseInt(document.getElementById(field).value);
	if (typeof value == "number")
		value++;
	document.getElementById(field).value = value;
}

function cartDec(field) {
	var value = parseInt(document.getElementById(field).value);
	if (typeof value == "number" && value > 0)
		value--;
	document.getElementById(field).value = value;
}

function toggleImage(c, pl, bl) {
	var color = nopl(c);
	var popup = document.getElementById('popupImage');
	var big = document.getElementById('bigImage');
	
	bl = bl.substring(0, bl.lastIndexOf('.')) + '_' + color + bl.substring(bl.lastIndexOf('.'), bl.length);
	big.src = bl;
	
	pl = pl.substring(0, pl.lastIndexOf('.')) + '_' + color + pl.substring(pl.lastIndexOf('.'), pl.length);
	popup.href = 'javascript:Popup("' + pl + '");';
}

function nopl(s) {
	var polish = "?????????";
	var nonPolish = "acelnoszz";
	
	for (var i = 0; i < polish.length; i++)
		s = replace(s, polish.charAt(i), nonPolish.charAt(i));
	
	return s;
}
					
function replace(s, arg0, arg1) {
	for (var i = 0; i < s.length; i++)
		if (s.charAt(i) == arg0)
			s = s.substring(0, i) + arg1 + s.substring(i + 1, s.length);

	return s;
}

function hideEmpty(arg0, name) {
	var objName = 's' + name;
	if (arg0 == null || arg0.length == 0)
		document.getElementById(objName).style.display = 'none';
}

/*********** UNIVERSAL ROLLING MECHANISM ***********/
/* 
	This is basic representation of roll mechanism single item. It
	does not contain launching image (it's launched with basic HTML
	link).
*/
function rmItem(layerId) {
	this.layerId = layerId;
	this.imageId = null;
	this.imageOn = null;
	this.imageOff = null;
	
	var currentDisplay = document.getElementById(layerId).style.display;
	if (currentDisply != 'none') {
		this.state = true;
		this.orgDisplay = currentDisplay;
	} else {
		this.state = false;
		this.orgDisplay = 'inline';
	}
}

/*
	This is representation of roll mechanism single item.
	Parameters:
		layerId - id of layer that is to be rolled;
		imageId - id of image that is rolling mechanism launcher;
		imageOn - path of an image that is shown when layer is HIDDEN;
		imageOff - path of an image that is shown when layer is VISIBLE;
*/
function rmItem(layerId, imageId, imageOn, imageOff) {
	this.layerId = layerId;
	this.imageId = imageId;
	this.imageOn = imageOn;
	this.imageOff = imageOff;

	var currentDisplay = document.getElementById(layerId).style.display;
	if (currentDisplay != 'none') {
		this.state = true;
		this.orgDisplay = currentDisplay;
	} else {
		this.state = false;
		this.orgDisplay = 'inline';
		// TODO: how to solve it? what display should be set? block? inline? or maybe default for given object type?
	}
}

/*
	This is initialization of roll mechanism.
*/
function rmInit() {
	rmArray = new Array();
}

/*
	This function adds rmItem to rmArray.
*/
function rmAdd(layerId) {
	var item = new rmItem(layerId);
	rmArray[rmArray.length] = item;
}

/*
	This function adds rmItem with it's launching image set to rmArray.
*/
function rmAdd(layerId, imageId, imageOn, imageOff) {
	var item = new rmItem(layerId, imageId, imageOn, imageOff);
	rmArray[rmArray.length] = item;
}

/*
	This function returns rmItem with given layerId from rmArray.
*/
function rmGet(layerId) {
	for (i = 0; i < rmArray.length; i++) {
		if (rmArray[i].layerId == layerId)
			return rmArray[i];
	}
}

/*
	This function changes state of given layer to opposite one.
*/
function rmChangeState(layerId) {
	for (i = 0; i < rmArray.length; i++) {
		if (rmArray[i].layerId == layerId) {
			if (rmArray[i].state == true)
				rmArray[i].state = false;
			else
				rmArray[i].state = true;
		}
	}
}

/*
	This function executes rolling mechanism on given layer. It also
	switches image that represents roll mechanism launcher.
*/
function rmExecute(layerId) {
	var item = rmGet(layerId);
	if (item != null) {
		if (item.state == true) {
			document.getElementById(item.layerId).style.display = 'none';
			if (item.imageId != null)
				document.getElementById(item.imageId).src = item.imageOn;
			rmChangeState(item.layerId);
		} else {
			document.getElementById(item.layerId).style.display = item.orgDisplay;
			if (item.imageId != null)
				document.getElementById(item.imageId).src = item.imageOff;
			rmChangeState(item.layerId);
		}
	}
}

/* upgraded */

function Popup(img) {
	popup(img);
}

function submitCategoryPaging(selectNo) {
	var sSelects = document.getElementsByName("sOffset");
	var offset = document.getElementById("categoryOffset");
	offset.value = sSelects[selectNo].options[sSelects[selectNo].selectedIndex].value;
	submitCategoryForm();
}

function changeSort(sortName) {
	var sort = document.getElementById("categorySort");
	sort.value = sortName;
	submitCategoryForm();
}

function filterByProducer(producerId) {
	document.location = "do/cat?producer=" + producerId;
}

function submitCategoryForm() {
	var form = document.getElementById("categoryForm");
	form.submit();
}

function toggle(big, popup) {
	var toggle = document.getElementById("toggle");
	
	var link = document.createElement("a");
	link.setAttribute("href", "javascript:popup('" + popup + "')");
	
	var image = document.createElement("img");
	image.setAttribute("src", big);

	link.appendChild(image);
	
	toggle.replaceChild(link, toggle.firstChild);
}

function popup(nazwa) {
	if (nazwa == null)
		return;
	void newWin(nazwa, 0, 0);
}

function newWin(nazwa, szer, wys) {
	var sizes = false;
	if (wys > 0) { 
		sizes = true;
		szer = szer + 28;
		wys = wys + 28;
		odlewa = (screen.width - szer) / 2;
		odgory = (screen.height - wys) / 2;
	} else {
		szer = 800;
		wys = 600;
		odlewa = (screen.width) / 4;
		odgory = (screen.height) / 4;
	}
	
	config = 'left = ' + odlewa + ', top = ' + odgory + ', width = ' + szer + ', height = ' + wys + ', innerheight = ' + wys + ', innerwidth = ' + szer + ', toolbar = no, location = no, directories = no, status = no, menubar = no, resizable = yes, scrollbars = auto';
	cel = window.open('', 'okno', config);
	cel.document.write('<html><head>');
	cel.document.write('<base href="');
	cel.document.write(shopBase);
	cel.document.write('" />');
	cel.document.write('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">');
	cel.document.write('<title></title>');
	if (!sizes) {
		cel.document.write('<script language="javascript" type="text/javascript">');
		cel.document.write('	var temp = self.location.href.split("?");');
		cel.document.write('	var picUrl = (temp.length > 1) ? temp[1] : "";');
		cel.document.write('	var NS = (navigator.appName == "Netscape") ? true : false;');
		cel.document.write('	function fitPic() {');
		cel.document.write('		iImg1 = document.getElementById("img1");');
		cel.document.write('		iWidth = (NS) ? window.innerWidth : document.body.clientWidth;');
		cel.document.write('		iHeight = (NS)? window.innerHeight : document.body.clientHeight;');
		cel.document.write('		if (iImg1.width > 800) iWidth = 640 - iWidth; else {iWidth = iImg1.width + 32 - iWidth;}');
		cel.document.write('		if (iImg1.height > 600) iHeight = 600 - iHeight; else {iHeight = iImg1.height + 32 - iHeight;}');
		cel.document.write('		window.resizeBy(iWidth, iHeight-1);');
		cel.document.write('		self.focus();');
		cel.document.write('	};');
		cel.document.write('	function setTitle() {');
		cel.document.write('		self.document.title = top.opener.document.title;');
		cel.document.write('	};');
		cel.document.write(' function myurlencode(string) {');
		cel.document.write('		return escape(string).replace(/[+]/g, "%2B");');
		cel.document.write(' }');
		cel.document.write('</scr' + 'ipt>');
	}
	cel.document.write('</head>');
	cel.document.write('<body scroll="auto" leftmargin = "10" topmargin = "10" marginheight = "10" marginwidth = "10">');
	cel.document.write('<a href="#" onclick="javascript:self.close();"><img src="' + shopBase);
	cel.document.write(escape(nazwa).replace(/[#]/g, "%23"));
	cel.document.write('" id="img1" class = "obw" alt="Kliknij, aby zamkn?? okno..." style="border: 1px solid #000;" onload="javascript: fitPic();" align="center"></a>');
	if (!sizes) {
		cel.document.write('<script language="javascript" type="text/javascript">');
		cel.document.write('	setTitle();');
		cel.document.write('</scr' + 'ipt>');
	}
	cel.document.write('</body></html>');
	cel.focus();
}

function toggleAddress() {
	var checkbox = document.getElementById("diff");
	
	if (checkbox == null)
		return;
	
	var deliveryElements = new Array();
	deliveryElements.push("prop(_delivery_name)");
	deliveryElements.push("prop(_delivery_street)");
	deliveryElements.push("prop(_delivery_postcode)");
	deliveryElements.push("prop(_delivery_city)");
	deliveryElements.push("prop(_delivery_country)");
	
	if (checkbox.checked == false) {
		for (var i = 0; i < deliveryElements.length; i++) {
			document.getElementById(deliveryElements[i]).disabled = true;
			document.getElementById(deliveryElements[i]).value = "";
		}
	} else {
		for (var i = 0; i < deliveryElements.length; i++) {
			document.getElementById(deliveryElements[i]).disabled = false;
		}
	}
}

function submitForm(form) {
	var form = document.getElementById(form);

	try {
		form.submit();
	} catch (err) {
		alert("Wybrany obiekt nie jest formularzem.");
	}
}

function changeProducer() {
	var producersList = document.getElementById('producersList').options;
	var selIndex = producersList.selectedIndex;
	var symbol = producersList[selIndex].value;
	if (symbol != '')
	document.location='/do/producer?symbol=' + symbol;
}

function showCart() {
	var hiddenCart = document.getElementById('hiddenCart');

	if (hiddenCart.style.display == 'none')
		hiddenCart.style.display = 'block';
	else
		hiddenCart.style.display = 'none';
}
