window.onload = function () {
	displayPopupAd();
}

/* initalized when DOM is ready (=page is loaded without waiting for images) */
function DOMOnloadInit() {
	initProductPopups();
	initProductVersions();
	
	if (typeof expandMenuEu == 'function') {
		expandMenuEu();
	} else {
		expandMenu();
	}

	restoreScrollPosition();
	if (typeof search != 'undefined') {
		search.init();
	}
	
	var sl3 = document.getElementById('sl3');
	if (sl3) {
		sl3RefreshInterval = 30000;
		setTimeout(sl3Refresh, sl3RefreshInterval);
	}
}

function sl3Refresh() {
	xhr.loadAction = "sl3ReceiveRequest(xhr.req.responseText)";
	var lang = search.input.form.lang.value;
	xhr.loadXMLDoc(pageLang + "/podglad-sl3&r=" + new Date().getTime());
}

function sl3ReceiveRequest(response) {
	var parent = document.getElementById('sl3').parentNode;
	parent.innerHTML = response;
	setTimeout(sl3Refresh, sl3RefreshInterval);
}

function preserveScrollOnCartRefresh(Form) {
	var removeChecked = false;
	var inputs = Form.getElementsByTagName('input');
	
	for (var i=0; i<inputs.length; i++) {
		var input = inputs[i];
		if (input.type == 'checkbox' && input.name.indexOf('remove[') == 0 && input.checked) {
			removeChecked = true;
			break;
		}
	}
	
	if (!removeChecked) {
		saveScrollPosition();
	}	
}

function saveScrollPosition() {
	var scrollY = document.body.scrollTop
    ? document.body.scrollTop
    : (window.pageYOffset
        ? window.pageYOffset
        : (document.body.parentElement
            ? document.body.parentElement.scrollTop
            : 0
        )
    );
    createCookie('scrollY', scrollY);	
}

function loadAndPreserveScroll(url) {
	saveScrollPosition();
	document.location.href=url;
}

function restoreScrollPosition() {
	var scrollY = readCookie('scrollY');
	if (scrollY !== null) {
		window.scrollTo(0, scrollY);
		eraseCookie('scrollY');
	}
}



//z lewego menu
var ie = (document.getElementById);
function rollMSMenu(item) {
	if (document.getElementById("ms_menu_" + item)) {
	   if (document.getElementById("ms_menu_" + item).style.display == "none") {
			 document.getElementById("ms_menu_" + item).style.display = "inline";
			 //document.getElementById("ms_text_" + item).src = "<?= MS_ROOT ?>" + "webpic/open.gif";
			 document.getElementById("text_" + item).className = "open";
	   } else {
			 document.getElementById("ms_menu_" + item).style.display = "none";
			 //document.getElementById("ms_text_" + item).src = "<?= MS_ROOT ?>" + "webpic/closed.gif";
			 document.getElementById("text_" + item).className = "closed";
	   }

	}
}

var ie = (document.getElementById);
function rollMenu(item) {
	if (document.getElementById("menu_" + item)) {
	   if (document.getElementById("menu_" + item).style.display == "none") {
			 document.getElementById("menu_" + item).style.display = "";
			 document.getElementById("text_" + item).className = "open";
	   } else {
			 document.getElementById("menu_" + item).style.display = "none";
			 document.getElementById("text_" + item).className = "closed";
	   }

	}
}

function expandMenu() {
	if (typeof expanded_cat_level1 != 'undefined') {
		rollMenu('_c'+expanded_cat_level1);

		if (typeof expanded_cat_level2 != 'undefined') {
			rollMenu('_c'+expanded_cat_level1+'_c'+expanded_cat_level2);
		}
	}

	if (typeof cat_path_ids != 'undefined') {
		var rollParam = '';
		
		for (var i=0; i<cat_path_ids.length; i++) {
			var elem = document.getElementById('c'+cat_path_ids[i]);

			if (elem.className.indexOf('expandable') >= 0) {
				rollParam += '_c'+cat_path_ids[i];
				rollMenu(rollParam);
			}
			elem.className += ' active';
		}
	}

	if (typeof filter_cat_path_ids != 'undefined') {
		var rollParam = '';
		
		for (var i=0; i<filter_cat_path_ids.length; i++) {
			var elem = document.getElementById('fc'+filter_cat_path_ids[i]);

			if (elem.className.indexOf('expandable') >= 0) {
				rollParam += '_fc'+filter_cat_path_ids[i];
				rollMenu(rollParam);
			}
			elem.className += ' active';
		}
	}

}


function gsm_zoompic(pic, width, height, lang, nextPic) {
	var win = window.open("/showpic.php?file=" + pic + '&lang=' + lang, 'zoompic', 'resizable,width=' + (width+5) + ',height=' + (height+5));
   win.focus();
}

function open_popup(id, lang) {
   win = window.open('popup.php?id=' + id + '&lang=' + lang, 'popup', 'scrollbars,resizable,width=320,height=320,');
   win.focus();
}

function open_new_win(link, title, params) {
   win = window.open(link, title, params);
   win.focus();
}

function openWin(url, width, height, scrollbars) {
	scrollbars = scrollbars ? 1 : 0;
   var win = window.open(url, 'win'+width+height, 'scrollbars=' + scrollbars + ',resizable=1,width=' +width+ ',height=' + height);
   win.focus();
}


function invoice_alert() {
	alert("This product may not support all couriers and/or payment methods. The details will be displayed on 'check out' screen.");
}

function askForProduct(lang, id, name) {
	var win = window.open('/' + lang + '/askforproduct?id=' + id + '&name=' + name, 'ask', 'resizable=1,scrollbars=1,width=500,height=430,')
	win.focus()
}

function objById(elemID) {
	var obj;
	if (document.getElementById) {
		obj = document.getElementById(elemID);
	}
	return obj;
}
function hide(obj) {
	obj.style.display = 'none';
}
function show(obj) {
	obj.style.display = 'inline';
}
function toggleHideShow(obj) {
	if(obj != undefined) {
		if(obj.style.display != 'none') {
			hide(obj);
		} else {
			show(obj);
		}
	}
}

ystart=0;
function moveY(obj, timeout) {
	if(obj) {
		if(timeout == undefined) {
			timeout = 50;
		}
	
	
		if (navigator.appName == "Netscape") {
			y=window.pageYOffset;
			doHeight=window.innerHeight;
		} else {
			y=document.body.scrollTop;
			doHeight=document.body.clientHeight;
		}
		
		startY = obj.offsetTop;
	
		ydiff=y-ystart;
		if ((ydiff<(-1))||(ydiff>(1))) {
			movey=Math.round(ydiff/10);
		
		} else {
			movey=0;
		}
		ystart+=movey;
		obj.style.top = startY + movey + "px";

		setTimeout("moveY(objById('"+obj.id+"'),"+timeout+")", timeout);
	}
}


function SwitchTags(tagName) {
	for (var i=0; i<document.getElementsByTagName(tagName).length; i++) {
		if (document.getElementsByTagName(tagName)[i].style.display != 'none')
			document.getElementsByTagName(tagName)[i].style.display = 'none'
		else
			document.getElementsByTagName(tagName)[i].style.display = 'inline'
	}
}

function focusLogin() {
	var href = document.location.href;
	var hashPos = href.indexOf('#');
	if (hashPos >= 0) {
		href = href.substr(0, hashPos);
	}
	document.location.href = href + '#login_form';
	document.getElementById('login_form').auth_login.focus();
}

function submitSubscriptionForm(form) {
	form.check_back.value = form.check.value + form.check.value;
	return true;
}


/* Reklama popup */
function displayPopupAd() {
	setTimeout('displayPopupAd2()', 1000);
}

function displayPopupAd2() {
	popupAd = document.getElementById('popup-ad');
	if (!popupAd) return;
	
	setOpacity(popupAd, 1);
	positionPopupAd();
	window.onresize = positionPopupAd;
	
	popupAdOpacity = 1;
	fadeInPopupAdINT = setInterval('fadeInPopupAd()', 50);
}

function fadeInPopupAd() {
	popupAdOpacity += 5;
	
	if (popupAdOpacity > 100) {
		popupAdOpacity = 100;
		clearInterval(fadeInPopupAdINT);
		
		setTimeout("document.getElementById('popup-close').style.display = 'block';", 500);
	}
	
	setOpacity(popupAd, popupAdOpacity);
}

function closePopupAd() {
	popupAd.style.display = "none";
}

function positionPopupAd() {
	var width = 210;
	var height = 240;
	
	var winWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	
	var winHeight = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);
	
	//alert(winHeight)
	
	var x = Math.round(winWidth / 2 - width / 2);
	var y = Math.round(winHeight / 2 - height / 2);
	if (x < 0) x = 0;
	if (y < 0) y = 0;
	
	//alert(x + ', ' + y);
	
	popupAd.style.left = x + 'px';
	popupAd.style.top = y + 'px';
}

function setOpacity(elem, percent) {
	elem.style.opacity = percent / 100;
	elem.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + percent + ")";
	//elem.style.filter = "alpha(opacity=" + percent + ")";
}


function findElementPos(obj) {
	var curleft = curtop = 0;

	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
	
		} while (obj = obj.offsetParent);
	}

	return [curleft,curtop];
}

/* pokaz opis produktu jako popup */
function getScrollingPosition()
{
 var position = [0, 0];
 if (typeof window.pageYOffset != 'undefined')
 {
   position = [
       window.pageXOffset,
       window.pageYOffset
   ];
 }
 else if (typeof document.documentElement.scrollTop
     != 'undefined' && document.documentElement.scrollTop > 0)
 {
   position = [
       document.documentElement.scrollLeft,
       document.documentElement.scrollTop
   ];
 }
 else if (typeof document.body.scrollTop != 'undefined')
 {
   position = [
       document.body.scrollLeft,
       document.body.scrollTop
   ];
 }
 return position;
}

function getWindowSize() {
	var y=0;
	if (self.innerHeight) // all except Explorer
	{
		y = self.innerHeight;
		x = self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return Array(x,y);
}


function initProductPopups() {
	var listElemNames = document.getElementById('product-list-names');
	var listElemImages = document.getElementById('product-list-images');
	
	if (!listElemNames && !listElemImages) return;
	
	productPopupTO = null;
	
	// place popup container just after <body>
	productPopupContainer = document.createElement('div');
	productPopupContainer.id = 'product-popup-container';
	
	var body = document.getElementsByTagName('body')[0];
	
	body.insertBefore(productPopupContainer, body.firstChild);
	
	if (listElemNames) {
		viewType = 'names';

		productPopupContainer.className = 'short-list compact-view-list';
		var trs = listElemNames.getElementsByTagName('tr');
		
		for (var i=0; i<trs.length; i++) {
			var a = trs[i].getElementsByTagName('a')[0];
	
			if (a.id.indexOf('productlink') == 0) {
				a.onmouseover = showDescriptionPopupDelayed;
				a.onmouseout = hideDescriptionPopup;
			}
		}

	} else  if (listElemImages) {
		viewType = 'images';
		
		productPopupContainer.className = 'images-product-list compact-view-list';
		var tds = listElemImages.getElementsByTagName('td');
		
		for (var i=0; i<tds.length; i++) {
			var span = tds[i].getElementsByTagName('span')[0];
	
			if (span && span.id.indexOf('productlink') == 0) {
				span.onmouseover = showDescriptionPopupDelayed;
				span.onmouseout = hideDescriptionPopup;
			}
		}
	}
}

function showDescriptionPopupDelayed(e) {
	productPopupTO = setTimeout('toggleDescriptionPopup("' + this.id + '", true)', 500);
}

function toggleDescriptionPopup(id, show) {
	var popupId = 'popup_info' + id.substr(12);
	var popup = document.getElementById(popupId);
	
	if (show) {
		var scrollPos = getScrollingPosition();
		var winSize = getWindowSize();
		
		var popup2 = popup.cloneNode(true);
		
		if (productPopupContainer.firstChild) {
			productPopupContainer.removeChild(productPopupContainer.firstChild);
		}
		
		productPopupContainer.appendChild(popup2);
		
		var popupHeight = popup2.offsetHeight;

		if (viewType == 'names') {
			var td = document.getElementById(id).parentNode;
			var tdPos = findElementPos(td);
			
			var x = tdPos[0];
			var y = tdPos[1] + td.offsetHeight;
			
			var fixedY = y - scrollPos[1];
			
			if (winSize[1] - fixedY < popupHeight && fixedY - popupHeight > 0) {
				y = y - popupHeight - td.offsetHeight;
			}

			popup2.style.top = y+'px';
			popup2.style.left = x+'px';
			
		} else if (viewType == 'images') {
			
			var picElem = document.getElementById(id);
			var td = picElem.parentNode.parentNode;
			var tr = td.parentNode;
			var trPos = findElementPos(tr);
			var spanPos = findElementPos(picElem);

			var x = trPos[0];
			var y = spanPos[1] + picElem.offsetHeight + 4;
			
			var fixedY = y - scrollPos[1];

			if (winSize[1] - fixedY < popupHeight && fixedY - popupHeight > 0) {
				y = y - popupHeight - picElem.offsetHeight - 8;
			}
			
			popup2.style.top = y+'px';
			popup2.style.left = x+'px';
		}

	} else {
		// hide
		popup.style.left = '-2000px';
	}	
}

function hideDescriptionPopup() {
	if (productPopupTO) {
		clearTimeout(productPopupTO);
	}
	
	toggleDescriptionPopup(this.id, false);	
}



function updateProductPrice() {
	updateProductPriceInForm('buy_form1');
	updateProductPriceInForm('buy_form2');
}

initialProductPrice = new Object;
productPriceCurrency = null;

function initProductVersions() {
	initProductVersionsInForm('buy_form1');
	initProductVersionsInForm('buy_form2');
}

function initProductVersionsInForm(formId) {
	var Form = document.getElementById(formId);
	var priceElem = document.getElementById('price_' + formId);
	
	if (!Form || !priceElem) return;
	
	if (typeof initialProductPrice[formId] == 'undefined') {
		var priceText = priceElem.firstChild.data.split(/\s+/);
		
		initialProductPrice[formId] = parseFloat(priceText[0].replace(/,/, '.'));
		productPriceCurrency = priceText[1];
	}
	
	if (initialProductPrice[formId] == 0) {
		// zaznacz pierwsze radio
		var autoCheck = !isRadioCheckedInVersionForm(Form);
		
		var inputs = Form.getElementsByTagName('input');
				
		for (var i=0; i<inputs.length; i++) {
			var input = inputs[i], lastName;
			
			if (input.type == 'radio' && input.name.indexOf('version[') == 0) {
				
				if (!input.disabled && autoCheck && input.name != lastName) {
					input.checked = true;
				}
				
				var label = input.nextSibling.data;
				
				// usun + w (+7.60 USD)
				var newLabel = label.replace(/ \(\+/, ' (');
				input.nextSibling.data = newLabel;
				
				if (!input.disabled) {
					lastName = input.name;
				}
			}
		}

	}
	updateProductPriceInForm(formId);
}



function updateProductPriceInForm(formId) {
	var Form = document.getElementById(formId);
	var priceElem = document.getElementById('price_' + formId);
	
	if (!Form || !priceElem || typeof initialProductPrice[formId] == 'undefined') return;
	
	// get radios, calculate total price
	var totalPrice = initialProductPrice[formId];
	var inputs = Form.getElementsByTagName('input');
	
	for (var i=0; i<inputs.length; i++) {
		var input = inputs[i];
		
		if (input.type == 'radio' && input.name.indexOf('version[') == 0 && input.checked) {
			var label = input.nextSibling.data;
			
			// eg. retrieve from "blue (+7.60 USD)"
			var result = /[^\(]+\(([+-]?[0-9.,]+)[A-Z ]+\)\s*$/.exec(label);
			var priceDiff = (result && result[1]) ? result[1] : "0";
			priceDiff = parseFloat(priceDiff.replace(/,/, '.'));
						
			totalPrice += priceDiff;
		}
	}
	
	var priceText = totalPrice.toFixed(2) + ' ' + productPriceCurrency;
	
	priceElem.firstChild.data = priceText;
}

function isRadioCheckedInVersionForm(Form) {

	var inputs = Form.getElementsByTagName('input');
	
	for (var i=0; i<inputs.length; i++) {
		var input = inputs[i];
		
		if (input.type == 'radio' && input.name.indexOf('version[') == 0 && input.checked) {
			return true;
		}
	}
	return false;
}


function submitBuyForm(formId) {
	Form = document.getElementById(formId);
	
	if (validateBuyForm(Form)) {
		Form.submit();
	}
}

function validateBuyForm(Form) {
	// get radios
	var radioNames = new Array;
	var inputs = Form.getElementsByTagName('input');
	
	for (var i=0; i<inputs.length; i++) {
		var input = inputs[i];
		
		// produkty czasowo niedostepne maja value='', wiec je pomijamy
		if (input.type == 'radio' && input.name.indexOf('version[') == 0 && input.value != '') {
			
			if (!radioNames.in_array(input.name)) {
				radioNames.push(input.name);
			}
		}
	}
	
	var fieldsAreaElem = document.getElementById('fields_area_' + Form.id);
	
	if (fieldsAreaElem) {
		if (!fieldsAreaElem.className) {
			fieldsAreaElem.className = "";
		}
	
		if (fieldsAreaElem.className.indexOf('versions-form-error') < 0) {
			fieldsAreaElem.className += ' versions-form-error';
		}
	}
	
	for (var i=0; i<radioNames.length; i++) {
		if (getRadioValue(Form, radioNames[i]) === null) {
			
			lang = getPageLang();
			
			if (lang == 'pl') {
				alert("Aby dodać produkt do koszyka, wybierz najpierw jego właściwości!");
			} else {
				alert("Please choose product properties before adding it to the cart!");
			}
			
			return false;
		}
	}	
	
	if (fieldsAreaElem) {
		fieldsAreaElem.className = fieldsAreaElem.className.replace(/versions-form-error/, '');
	}
	return true;
}

function getRadioValue(Form, radioName) {
	var rad_val = null;

	for (var i=0; i<Form.elements.length; i++) {
		if (Form.elements[i].name == radioName && Form.elements[i].checked) {
			var rad_val = Form.elements[i].value;
			break;
		}
	}
	return rad_val;
}

function getPageLang() {
	var url = document.location.href;
	
	if (url.indexOf('/pl/') >= 0) {
		return 'pl';
	}
	return 'en';
}

/* Zagiel */
function PoliczRate(priceElemId, minimalnaCena, wariantSklepu, numerSklepu) {
	
	var priceElem = document.getElementById(priceElemId);
	
	var priceStr = (priceElem.nodeName == 'INPUT') ? priceElem.value : priceElem.firstChild.data;
	
	var koszyk = parseFloat(priceStr.replace(/,/, '.'));
	
	if (koszyk >= minimalnaCena) {
		var win = window.open('https://www.eraty.pl/symulator/oblicz.php?numerSklepu=' + numerSklepu + '&wariantSklepu='+wariantSklepu+'&typProduktu=0&wartoscTowarow='+koszyk, 'Policz_rate', 'width=630,height=500,directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no');
		win.focus();

	} else {
		alert("Zakup na raty dostępny jest od " + minimalnaCena + " zł wartości produktu lub całego zamówienia.");
	}
}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

String.prototype.htmlspecialchars = function() {
	var s = this.replace(/&/g, '&amp;');
	s = s.replace(/</g, '&lt;');
	s = s.replace(/>/g, '&gt;');
	s = s.replace(/"/g, '&quot;');
	s = s.replace(/'/g, '&#039;');
	return s;	
}

