//$=function(x){return document.getElementById(x)}

mkPopup=function(mypage,myname,w,h,scroll){
 var winl=(screen.width-w)/2;
 var wint=(screen.height-h)/2;
 var settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=no';
 win=window.open(mypage,myname,settings);
}
resBody=function(o){
	return true;
	var w=o.width;
	var h=o.height;
	if (w>0&&h>0) {
		var resWidth = w + 0;
		var resHeight = h + 40;
		var ua = navigator.userAgent.toLowerCase();
		var isOp=(ua.indexOf("opera")!=-1?true:false);
		var isIe=(ua.indexOf("msie")!=-1&&!isOp?true:false);
		if (isIe) {
			resWidth = w + 35;
			resHeight = h + 65;
		}
	
		if (window.screen.width < resWidth)resWidth=window.screen.width-20;
		if (window.screen.height < resHeight)resHeight=window.screen.height-20;
		
		window.resizeTo(resWidth, resHeight);
		
		var wx=(screen.width-w)/2, wy=(screen.height-h)/2;
 		window.moveTo(wx,wy);
		//self.focus();
	}
}
function preloadImg(src) {
	new Image().src=src;
}

function tabs(tabsconfig)
{
	this.tabsconfig = tabsconfig;
	
	this.ch = function(tab_active)
	{
		for(i=0; i<this.tabsconfig.length; i++)
		{
			if (this.tabsconfig[i] == tab_active)
			{
				$('t'+this.tabsconfig[i]).className = this.tabsconfig[i]+'_a';
				$('c'+this.tabsconfig[i]).className = 'txt'+this.tabsconfig[i]+'_a';
			}
			else
			{
				$('t'+this.tabsconfig[i]).className = this.tabsconfig[i];
				$('c'+this.tabsconfig[i]).className = 'txt'+this.tabsconfig[i];
			}
		}
	}
}

function gourl(u)
{
	document.location.replace(u);
	return false;
}

function chmimg(imgid,o) {
	if (imgs[imgid]) {
		$('phone_mimg').src = imgs[imgid].S;
		$('phone_mimg').parentNode.href=imgs[imgid].D;
		$('phone_mimg').parentNode.title=o.alt;
		new Image().src=imgs[imgid].D;
	}
}

/* newsletter */
function newsletter_change(obj){input_change(obj,'Wpisz swój adres e-mail')}
function input_change(obj,txt){if(obj.value==txt)obj.value=''};
function newsletter_send(o){
	if (typeof o == 'undefined') {
		o = '';
	}
	var err=false;
	var eObj=$('newsletter_email'+o);
	if (eObj.value==null||eObj.value==''||eObj.value=='Wpisz swój adres e-mail'||!isEmail(eObj.value))
	{
		err=true;
		alert('Wpisz poprawny adres e-mail.');
		eObj.focus();
		return false;
	}
	
	advAJAX.get({
		url: "/index.php?m=newsletter&a=addemail&email="+eObj.value,
		onLoading : function(obj){ /* Wy?wietlenie obrazka wskazuj?cego na ?adowanie */ },
		onComplete : function(obj) { /* Ukrycie obrazka... */ },
		onSuccess : function(obj) {
			eval('ret = obj.responseText');
			if (ret == '-1') {
				alert('Podany adres email już został dopisany do naszej bazy.');
				eObj.value='';
				eObj.focus();
			} else if (ret == '1') {
				alert('Dziękujemy. Twój email został dopisany do naszego newslettera.');
				eObj.value='';
			} else {
				alert('Wpisz poprawny adres e-mail.');
			}
		}
	})
	return false;
}

function search_change(obj){input_change(obj,'szukaj...')}

/** email validation stuff. Based on: SmartWebby.com (http://www.smartwebby.com/dhtml/) */
isEmail=function(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}

	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}
	
	if (str.indexOf(" ")!=-1){
		return false
	}

	return true					
}

function checkHeight(d) {
	if (!d) return false;
	var divHeight=0;
	//d=$(arguments[0]);
	if(d.offsetHeight)
		divHeight=d.offsetHeight;
	else if(d.style.pixelHeight)
		divHeight=d.style.pixelHeight;
	return divHeight;
}
function max(a,b) {return (a>b)?a:b}
function bim(){try{window.event.returnValue=false}catch(e){};return false}

function addToFavorite()
{
	try {
		window.external.AddFavorite(document.location, document.title);
	} catch(e) {
		alert('Jeżeli chcesz dodać tę stronę do ulubionych, naciśnij OK a następnie CTRL+D');
	}
}

function popover_colors(prod)
{
	try{
		var bW = document.body.getWidth(), bH = document.body.getHeight();
	}
	catch(e)
	{
		var bW = document.body.scrollWidth, bH = document.body.scrollHeight;
	}
	if (!$('shadow'))
	{
		var div = document.createElement('div');
		div.className = 'popover-shadow';
		div.style.width = bW+'px';
		div.style.height = bH+'px';
		div.id = 'shadow';
		document.body.insertBefore(div, document.body.childNodes[0]);
	}
	else
	{
		$('shadow').style.display = 'block';
	}
	$('shadow').onclick = popover_close;
	
	var div = document.createElement('div');
	div.className = 'popover-window';
	div.style.left = ((bW-750)/2)+'px';
	div.style.top = (40+(document.documentElement||document.body).scrollTop)+'px';
	div.id = 'popover_window';
	document.body.insertBefore(div, $('shadow').nextSibling);
	$('popover_window').innerHTML = '<p class="loading">Trwa ładowanie...<br /><img src="'+SERVOFFSET+'/i/loading.gif" width="220" height="19"/></p><div class="btn-close"><img src="../i/lightbox/closelabel.gif" class="link" onclick="javascript:popover_close()"/></div>';
	
	advAJAX.get({
		url: SERVOFFSET+"/ajax.php?m=okladziny&a=getProdLinks&p="+prod,
		onLoading : function(obj){ /* Wy?wietlenie obrazka wskazuj?cego na ?adowanie */ },
		onComplete : function(obj) { /* Ukrycie obrazka... */ },
		onSuccess : function(obj) {
			var ret = eval('(' + obj.responseText + ')');
			if (ret.length)
			{
				$('popover_window').innerHTML = '';
				ret.each(function(e){
					var _d = document.createElement('div');
					var r = '<h2><strong>cena: <span>'+(1*e.c)+' zł</span></strong>'+e.k+'</h2>';
					r += '<p>';
					if (e.o.length)
					{
						r += 'Opis... <span class="link" onclick="javascript:alert(\''+e.o+'\')">&raquo;</span>';
					}
					else
					{
						r += '&nbsp;';
					}
					r += '</p>';
					_d.innerHTML = r;
					var _ul = document.createElement('ul');
					e.l.each(function(ee){
						var _li = document.createElement('li');
						_li.className = 'link';
						_li.onclick = function(){
							$('prod_kolor').innerHTML = '<img src="'+SERVOFFSET+'/i/cms/'+ee.z+'" width="30" height="30"/>';
							$('prod_cena_box').innerHTML = 1*e.c + ' PLN';
							$('prod_cena_value').value = 1*e.c;
							$('prod_okl').value = ee.i;
							popover_close();
						};
						_li.innerHTML = '<img src="'+SERVOFFSET+'/i/cms/'+ee.z+'" width="70" height="70"/><br/>'+ee.o;
						_ul.appendChild(_li);
					})
					_d.appendChild(_ul);
					
					var _c = document.createElement('div');
					_c.className = 'okl-kat';
					_c.appendChild(_d);
					
					$('popover_window').appendChild(_c);
				})
				var _d = document.createElement('div');
				_d.innerHTML = '<br/>&nbsp;';
				$('popover_window').appendChild(_d);
				_d = document.createElement('div');
				_d.setAttribute('class', 'btn-close');
				_d.innerHTML = '<img src="../i/lightbox/closelabel.gif" class="link" onclick="javascript:popover_close()"/>';
				$('popover_window').appendChild(_d);
				
				var bH = (document.documentElement||document.body).scrollHeight;
				$('shadow').style.height = bH+'px';
			}
		}
	})
}

function popover_close()
{
	if ($('popover_window'))
	{
		$('popover_window').remove();
	}
	if($('shadow'))
	{
		$('shadow').style.display = 'none';
	}
}

var cart = {
	prodPrices: {},
	prodCnt: {},
	sumPrice: 0.0,
	deliveryPrice: 0.0,
	totalPrice: 0.0,
	addProduct: function(prodId) {
		if ($('prod_okl')) {
			var cena = 1*$('prod_cena_value').value;
			var okl = 1*$('prod_okl').value;
			if (cena > 0 && okl > 0) {
				document.location.replace(SERVOFFSET+'/koszyk.html?a=prod_add&p='+prodId+'&o='+okl+'&c='+cena);
			} else {
				alert('Proszę wybrać kolor.');
			}
		} else {
			document.location.replace('/koszyk/?a=prod_add&p='+prodId);
		}
	},
	recntAll: function() {
		//totalPrice i uaktualnienie formularza:
		cart.totalPrice=cart.sumPrice+cart.deliveryPrice;
		$('sum_price').innerHTML=cart.sumPrice;
		$('delivery_price').innerHTML=cart.deliveryPrice;
		$('total_price').innerHTML=cart.totalPrice;
		
		if ($H(cart.prodCnt).values().length) {
			new Ajax.Request('koszyk.html?a=update', {
				method: 'post',
				parameters: $('fkoszyk').serialize(),
				onLoading: function() {
					$('fkoszyk').disable();
				},
				onLoaded: function() {
					$('fkoszyk').enable();
				},
				onError: function() {
					$('fkoszyk').enable();
				},
				onSuccess: function(t) {
					$('fkoszyk').enable();
					if (-1==parseFloat(t.responseText) || parseFloat(t.responseText) != cart.totalPrice) {
						//document.location.reload();
						console.log(t.responseText)
					}
				}
			});
		}
	},
	checkOrderFrm : function(fobj) {
		var err = true;
		$$('#platnosci-wybor input[type="radio"]').each(function(e){
			if (e.checked)	{
				err = false;
			}
		})
		if (err) {alert('Wybierz sposób płatności.');}
		return !err;
	},
	load: function() {
		if ($$('#platnosci-wybor input').length) {
			var _ch=false,_els=$$('#platnosci-wybor input');
			_els.each(function(e,i){if(e.checked)_ch=true});
			if (!_ch){
				_els.first().checked=true;
			}
			_els.each(function(e,i){if(e.checked)e.nextSiblings()[0].setStyle({'fontWeight' : 'bold'})});
			_els.each(function(e,i){if(e.checked){$('delivery_price').innerHTML=cart.deliveryPrice=cart.payMap[e.id.substring(8)+'_price'];$('total_price').innerHTML=cart.sumPrice+cart.deliveryPrice;throw $break}});
		}
		
		//ustalenie sumPrice:
		$$('input.prod-quantity').each(function(el){
			Event.observe(el, 'change', function(){
				cart.sumPrice=0;
				cart.prodCnt={};
				$$('input.prod-quantity').each(function(e){
					e.value=parseInt(e.value);
					if (isNaN(e.value)||e.value<=0) {
						e.value=1;
					}
					cart.sumPrice+=cart.prodPrices[e.getAttribute('rel')]*e.value;
					cart.prodCnt[e.getAttribute('rel')]=e.value;
					$(el.parentNode).nextSiblings().first().innerHTML=(cart.prodPrices[e.getAttribute('rel')]*e.value)+' zł';
					
				 });
				cart.recntAll();
			})
		});
		
		//ustalenie deliveryPrice:
		$$('#platnosci-wybor input[type=radio]').each(function(el){
			Event.observe(el, 'click', function(e){
				$$('#platnosci-wybor label').invoke('setStyle', {fontWeight:'normal'});
				if(this.checked){
					$(this).nextSiblings()[0].setStyle({fontWeight : 'bold'});
					cart.deliveryPrice = cart.payMap[this.id.substring(8)+'_price'];
				}
				cart.recntAll();
			})
		});
		
		cart.recntAll();
	}
};