 var ceneoTools={ getWindowSize: function()
{
	var windowWidth = windowHeight =0;

  	if( typeof( window.innerWidth ) == 'number' )
	{
	    windowWidth = window.innerWidth;
	    windowHeight = window.innerHeight;
	}
	else if(document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
	    windowWidth = document.documentElement.clientWidth;
	    windowHeight = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
   	    windowWidth = document.body.clientWidth;
	    windowHeight = document.body.clientHeight;
  	}


	return [windowWidth, windowHeight];
},
 getScroll: function()
{
	var sX = sY = 0;

	if (document.documentElement && document.documentElement.clientHeight)
	{
		sY = document.documentElement.scrollTop;
		sX = document.documentElement.scrollLeft;
	}
	else
	{
		sY = document.body.scrollTop;
		sX = document.body.scrollLeft;
	}

	return [sX,sY];
},
findPos:function(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
},
popupWindow:function(fileUrl, winW, winH, winN, scrollB) {    
    var nn4 = (document.layers) ? true : false;
    var ie4 = (document.all) ? true : false;
    var dom = (document.createTextNode)? true : false;
	var winWidth = (winW)? winW : 740;
	var winHeight = (winH)? winH : 520;
	var winName = (winN)? winN : 'popupWin'
	var scrollBars = (scrollB)? scrollB : 'auto'
	if (nn4 || ie4 || dom) {
		if (screen.width < winWidth + 50) { winWidth = screen.width - 50; scrollbars = 'yes' }
		if (screen.height < winHeight + 100) { winHeight = screen.height - 100; scrollbars = 'yes' }
		posX = Math.round((screen.width - winWidth) / 2);
		posY = Math.round((screen.height - winHeight) / 2);
		posCode = (nn4)? "screenX="+posX+",screenY="+posY : "left="+posX+",top="+posY;
	} else {
		posCode = "";
	}
	var popupWin = window.open(fileUrl, winName,"menubar=no,toolbar=no,scrollbars=" + scrollBars + ",status=yes,resizable=yes,width=" + winWidth + ",height=" + winHeight + "," + posCode);
	if (popupWin) popupWin.focus();
}
};

/* Copyright © 2005-2008 Ceneo SA */

/* === VARIABLES === */

var ceneoBoxes = {
    ids: ['filters', 'history', 'links'],
    init: function() {
        forEach(ceneoBoxes.ids, function() {
            var x = document.getElementById('close-' + this);
            if (x) {
                x.style.display = 'block';
                if (cookie.get(this) == 'hide') {
                    ceneoBoxes.hide(this);
                }
                forEach(x.getElementsByTagName('a'), function() {
                    this.onclick = function() {
                        ceneoBoxes.toogle(this.href.split('#box-')[1]);
                        this.blur();
                        return false;
                    };
                });
            }
        });
      },
    toogle: function(id) {
        if (document.getElementById('box-' + id).style.display == 'none') {
            ceneoBoxes.show(id);
            cookie.del(id);
        }
        else {
            ceneoBoxes.hide(id);
            cookie.set(id, 'hide', 90);
        }
    },
    show: function(id) {
        var x = document.getElementById('close-' + id).getElementsByTagName('img')[0], y = document.getElementById('box-' + id);
        x.src = x.src.replace('show.gif', 'hide.gif');
        x.alt = 'ukryj';
        x.parentNode.parentNode.getElementsByTagName('a')[0].innerHTML = 'ukryj';
        y.style.display = 'block';
    },
    hide: function(id) {
        var x = document.getElementById('close-' + id).getElementsByTagName('img')[0], y = document.getElementById('box-' + id);
        x.src = x.src.replace('hide.gif', 'show.gif');
        x.alt = 'pokaż';
        x.parentNode.parentNode.getElementsByTagName('a')[0].innerHTML = 'pokaż';
        y.style.display = 'none';
    }
};

var ceneoFilters = {
    init: function() {
        var x = document.getElementById('form-body-filters');
        if (x) {
            forEach(x.getElementsByTagName('input'), function() {
                if (this.type == 'text') {
                    if (hasInSpaceSeparated('number', this.className)) {
                        this.onfocus = function() {
                            //ceneoFilters.toogle('none');
                            if ((hasInSpaceSeparated('half-1', this.className) && (this.value == '- od -')) || (hasInSpaceSeparated('half-2', this.className) && (this.value == '- do -'))) {
                                this.value = '';
                            }
                            this.style.color = '#000';
                        };
                        this.onblur = function() {
                            if (this.value === '') {
                                this.value = hasInSpaceSeparated('half-1', this.className) ? '- od -' : '- do -';
                                this.style.color = '';
                            }
                            else {
                                this.style.color = /^[\d]*((,|\.)[\d]+)?$/.test(this.value) ? '#000' : 'red';
                            }
                        };
                    }
                    else if (hasInSpaceSeparated('string', this.className)) {
                        this.onfocus = function() {
                            ceneoFilters.toogle('none');
                            if (this.value == '- wpisz -') {
                                this.value = '';
                            }
                            this.style.color = '#000';
                            this.style.textAlign = 'left';
                        };
                        this.onblur = function() {
                            if (this.value === '') {
                                this.value = '- wpisz -';
                                this.style.color = '';
                                this.style.textAlign = '';
                            }
                            else {
                                this.style.color = /^[a-zA-Z0-9_ ]*$/.test(this.value) ? '#000' : 'red';
                            }
                        };
                    }
                }
            });
            forEach(x.getElementsByTagName('div'), function() {
                if (hasInSpaceSeparated('filter', this.className)) {
                    forEach(this.getElementsByTagName('a'), function() {
                        if (this.parentNode && this.parentNode.tagName.toLowerCase() == 'label') {
                            this.onclick = function() {
                                this.blur();
                                this.parentNode.parentNode.getElementsByTagName('input')[0].checked = true;
                                var elements = this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('button');
                                if (elements.length > 0)
                                    elements[0].onclick();
                                //zmiana false na true, klikniecie w linka na divie powoduje przeladowanie strony
                                return true;
                            };
                        }
                    });
                }
            });
            forEach(x.getElementsByTagName('a'), function() {
                if (this.parentNode && this.parentNode.tagName.toLowerCase() == 'p') {
                    this.style.display = 'block';
                }
            });
            forEach(x.getElementsByTagName('select'), function() {
                if (hasInSpaceSeparated('multiple', this.className)) {
                    this.multiple = true;
                }

                if (!hasInSpaceSeparated('donthide', this.className)) {
                    this.style.display = 'none';

                    this.parentNode.getElementsByTagName('label')[0].onclick = function() {
                        ceneoFilters.toogle(this.parentNode.getElementsByTagName('select')[0].id);
                        return false;
                    };
                }


            });
        }
        if (document.getElementById('filters-choosen')) {
            ceneoBoxes.hide('filters');
            forEach(document.getElementById('close-filters').getElementsByTagName('a'), function() {
                this.onclick = function() {
                    ceneoBoxes.toogle(this.href.split('#box-')[1]);
                    document.getElementById('filters-choosen').style.display = 'none';
                    this.blur();
                    return false;
                };
            });
        }
    },
    onKeyCheck: function(e) {
        e = e || window.event;
        if (e.keyCode == 27) {
            ceneoFilters.toogle('none');
        }
    },
    toogle: function(x) {
        document.onkeydown = null;
        forEach(document.getElementById('form-body-filters').getElementsByTagName('div'), function() {
            if (hasInSpaceSeparated('filter', this.className)) {
                var id = this.id.replace(/js\-tip\-/, ''), y = document.getElementById(this.id), z = 0;
                if (id == x && y.style.display != 'block') {
                    z = 1;
                    document.onkeydown = ceneoFilters.onKeyCheck;
                }
                if (!isIE6) {
                    document.getElementById(id).parentNode.getElementsByTagName('label')[0].style.fontWeight = z ? 'bold' : 'normal';
                }
                document.getElementById('js-val-' + id).className = z ? 'filter-active' : (document.getElementById('js-val-' + id).innerHTML == '- wybierz -' ? 'filter' : 'filter-choosen');
                y.style.display = z ? 'block' : 'none';


                $(y).find("div.values div").height("auto");
                $(y).find("div.values div").css("overflow", "hidden");
                
                if ($(y).height() > $(document).height()) {
                    $(y).find("div.values div").height($(document).height() - 500);
                    $(y).find("div.values div").css("overflow-y", "scroll");
                }
            }
        });
        return false;
    },
    apply: function(x) {
        var txt = [], val = '', y = document.getElementById('js-val-' + x); y.innerHtml = "";
        forEach(document.getElementById(x).getElementsByTagName('option'), function() {
            this.selected = false;
        });
        forEach(document.getElementById('js-tip-' + x).getElementsByTagName('input'), function() {
            if (this.id && this.checked && this.type != "text") {
                var z = document.getElementById(this.id.replace(/js\-/, ''));
                txt.push(z.text.trim());
                z.selected = true;
            }
        });
        forEach(document.getElementById('js-tip-' + x).getElementsByTagName('option'), function() {
            if (this.id && this.selected) {
                var z = document.getElementById(this.id.replace(/js\-/, ''));
                txt.push(z.text.trim());
                z.selected = true;
            }
        });
        forEach(document.getElementById('js-tip-' + x).getElementsByTagName('input'), function() {
            if (this.id && this.type == "text") {
                if (this.name == "price-min" && this.value == "- od -") { return; }
                if (this.name == "price-max" && this.value == "- do -") { return; }
                var z = document.getElementById(this.id.replace(/js\-/, ''));
                z.text = this.value;
                z.value = this.value;
                z.selected = true;
                var prefix = "";
                if (this.name == "price-min" && this.value != "- od -") {
                    prefix += "od ";
                }
                if (this.name == "price-max" && this.value != "- do -") {
                    prefix += "do ";
                }
                txt.push(prefix + z.text.trim());
            }
        });
        if (txt.length === 0) {
            y.title = '';
            y.innerHTML = '- wybierz -';
            y.style.color = '';
        }
        else {
            forEach(txt, function() {
                if (val.length < 8) {
                    if (val.length !== 0) {
                        val += ', ';
                    }
                    val += this;
                }
            });
            if (val.length > 12) {
                val = val.substring(0, 10).trim() + '...';
            }
            else if (val.length != txt.join(', ').length) {
                if (val.length > 10) {
                    val = val.substring(0, 10).trim();
                }
                val += '...';
            }
            y.title = txt.join(', ');
            y.innerHTML = val;
            y.style.color = '#000';
        }
        return ceneoFilters.toogle(x);
    },
    erase: function(x) {
        var y = document.getElementById('js-val-' + x);
        forEach(document.getElementById(x).getElementsByTagName('option'), function() {
            this.selected = false;
        });
        y.title = '';
        y.innerHTML = '- wybierz -';
        y.style.color = '';
        return ceneoFilters.toogle(x);
    }
};

var ceneoFiltersAlt = {
	link: {
	hide: '<a href="javascript:void(0);" onclick="return ceneoFiltersAlt.hide(this.parentNode);"><img src="common/image/icon/hide.gif" alt="mniej" /></a> <a href="javascript:void(0);" onclick="return ceneoFiltersAlt.hide(this.parentNode);">mniej</a>',
		show: '<a href="javascript:void(0);" onclick="return ceneoFiltersAlt.show(this.parentNode);"><img src="common/image/icon/show.gif" alt="więcej" /></a> <a href="javascript:void(0);" onclick="return ceneoFiltersAlt.show(this.parentNode);">więcej</a>'
	},
	init: function()
	{
		var x = document.getElementById('form-body-filters-alt');
		if(x)
		{
			forEach(x.getElementsByTagName('input'), function()
			{
				if(this.type == 'text')
				{
					if(hasInSpaceSeparated('number', this.className))
					{
						this.onfocus = function()
						{
							//ceneoFilters.toogle('none');
							if((hasInSpaceSeparated('half-1', this.className) && (this.value == '- od -')) || (hasInSpaceSeparated('half-2', this.className) && (this.value == '- do -')))
							{
								this.value = '';
							}
							this.style.color = '#000';
						};
						this.onblur = function()
						{
							if(this.value === '')
							{
								this.value = hasInSpaceSeparated('half-1', this.className) ? '- od -' : '- do -';
								this.style.color = '';
							}
							else
							{
								this.style.color = /^[\d]*((,|\.)[\d]+)?$/.test(this.value) ? '#000' : 'red';
							}
						};
					}
					else if(hasInSpaceSeparated('string', this.className))
					{
						this.onfocus = function()
						{
							//ceneoFilters.toogle('none');
							if(this.value == '- wpisz -')
							{
								this.value = '';
							}
							this.style.color = '#000';
							this.style.textAlign = 'left';
						};
						this.onblur = function()
						{
							if(this.value === '')
							{
								this.value = '- wpisz -';
								this.style.color = '';
								this.style.textAlign = '';
							}
							else
							{
								this.style.color = /^[a-zA-Z0-9_ ]*$/.test(this.value) ? '#000' : 'red';
							}
						};
					}
				}				
			});
			forEach(x.getElementsByTagName('div'), function()
			{
			    var count = 0;
			    forEach(this.getElementsByTagName('label'), function() 
			    {
			        if (hasInSpaceSeparated('hide', this.className)) {
			            count++;
			        }
			    });
			    var moreLink = '<p class="manage">';
			    if (count) 
			    {
			        moreLink += ceneoFiltersAlt.link.show + '</p>';
			    }
			    else 
			    {
			        moreLink += '</p>';
			    }
			    var moreLinkPlaceholder = $('strong', this);
			    if (moreLinkPlaceholder.length && moreLinkPlaceholder.hasClass('moreLinkPlaceholder')) {
			        moreLinkPlaceholder.before(moreLink).remove();
			    }
			    else 
			    {
			        $(this).append(moreLink);
			    }
			});
			
			$('#form-body-filters-alt').find('input[type=checkbox]').click(function()
			{
			    var checked = $(this).attr('checked');
			    $('#form-body-filters-alt').find('input[id=' + this.id + ']').each(function()
			    {
			        $(this).attr('checked', checked);
			    });
			});			    
		}
	},
	show: function(x)
	{
		x.innerHTML = ceneoFiltersAlt.link.hide;
		forEach(x.parentNode.getElementsByTagName('label'), function()
		{
			if(hasInSpaceSeparated('hide', this.className))
			{
				this.style.display = 'block';
			}
			if(hasInSpaceSeparated('forcehide', this.className))
			{
				this.style.display = 'none';
			}
		});
		return false;
	},
	hide: function(x)
	{
		x.innerHTML = ceneoFiltersAlt.link.show;
		forEach(x.parentNode.getElementsByTagName('label'), function()
		{
			if(hasInSpaceSeparated('hide', this.className))
			{
				this.style.display = '';
			}
			if(hasInSpaceSeparated('forcehide', this.className))
			{
				this.style.display = '';
			}
		});
		return false;
	}
};

var ceneoGmap = {
    area: null,
    gmap: null,
    icon: null,
    current: 0,
    types: [
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 18.680191, 'Y': 54.404145, 'ZoomLevel': 11 },
		{ 'X': 19.057159, 'Y': 50.321792, 'ZoomLevel': 11 },
		{ 'X': 19.978638, 'Y': 50.121899, 'ZoomLevel': 11 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 },
		{ 'X': 19.145136, 'Y': 51.919438, 'ZoomLevel': 6 }
	],
    markers: [],
    init: function() {
        var x = new Image(), y = new Image();
        if (ceneoGmap.area) {
            if (typeof GBrowserIsCompatible != 'function') {
                ceneoGmap.area.innerHTML = [
					'<div class="gmap-msg">',
						'<div class="warning-msg">',
							'<h3>Mapy sklepów nie mogą zostać wyświetlone</h3>',
							'<p>Mapy sklepów korzystają z zewnętrznych serwerów, co sprawia, że od czasu do czasu niestety mogą być niedostępne.</p>',
							'<p>Spróbuj ponownie za kilka minut. Przepraszamy za niedogodności.</p>',
						'</div>',
					'</div>'
				].join('');
            }
            else if (!GBrowserIsCompatible()) {
                ceneoGmap.area.innerHTML = [
					'<div class="gmap-msg">',
						'<div class="warning-msg">',
							'<h3>Mapy sklepów nie mogą zostać wyświetlone</h3>',
							'<p>Mapy sklepów korzystają z najnowszych technologii internetowych, których Twoja przeglądarka nie obsługuje.</p>',
							'<p>Aby wyświetlić mapy sklepów, zaktualizuj przeglądarkę do najnowszej wersji, a następnie spróbuj ponownie.</p>',
						'</div>',
					'</div>'
				].join('');
            }
            else {
                x.src = 'common/image/icon/gmap-icon.gif';
                y.src = 'common/image/icon/gmap-shadow.png';
                window.onunload = GUnload;
                forEach([G_NORMAL_MAP, G_HYBRID_MAP], function() {
                    this.getMinimumResolution = function() {
                        return 3;
                    };
                    this.getMaximumResolution = function() {
                        return 17;
                    };
                });
                G_NORMAL_MAP.getName = function() {
                    return 'Mapa ulic';
                };
                G_HYBRID_MAP.getName = function() {
                    return 'Satelitarna';
                };
                ceneoGmap.gmap = new GMap2(ceneoGmap.area);
                ceneoGmap.gmap.removeMapType(G_SATELLITE_MAP);
                ceneoGmap.gmap.setCenter(new GLatLng(ceneoGmap.types[ceneoGmap.current].Y, ceneoGmap.types[ceneoGmap.current].X), ceneoGmap.types[ceneoGmap.current].ZoomLevel);
                ceneoGmap.gmap.addControl(new GLargeMapControl());
                ceneoGmap.gmap.addControl(new GMapTypeControl());
                ceneoGmap.icon = new GIcon();
                ceneoGmap.icon.image = x.src;
                ceneoGmap.icon.shadow = y.src;
                ceneoGmap.icon.iconSize = new GSize(27, 24);
                ceneoGmap.icon.shadowSize = new GSize(40, 24);
                ceneoGmap.icon.iconAnchor = new GPoint(14, 24);
                forEach(ceneoGmap.markers, function() {
                    ceneoGmap.addMarkers(this);
                });
                if ((x = document.getElementById('form-body-geo'))) {
                    x.onsubmit = function() {
                        ceneoGmap.current = parseInt(document.getElementById('form-body-geo-map').value, 10);
                        ceneoGmap.gmap.setCenter(new GLatLng(ceneoGmap.types[ceneoGmap.current].Y, ceneoGmap.types[ceneoGmap.current].X), ceneoGmap.types[ceneoGmap.current].ZoomLevel);
                        this.getElementsByTagName('select')[0].blur();
                        this.getElementsByTagName('button')[0].blur();
                        return false;
                    };
                }
            }
        }
    },
    setArea: function(el) {
        el = document.getElementById(el);
        el.innerHTML = '';
        ceneoGmap.area = el;
    },
    prepareHtml: function(obj, tabsLength) {
        var width = tabsLength == undefined ? "270px" : 270 + (tabsLength-1) * 50 + "px";
        return [
			'<div style="width: ' + width + ';font-size:13px !important;">',
				'<p><a href="' + obj.link + '" rel="external nofollow">'
				+ (obj.hasLogo
					? '<img src="' + obj.logoSrc + '" alt="' + obj.logoAlt + '" height="40" />'
					: '<span class="shopLogo">' + obj.shopDomain + '</span>'
					)
				+ '</a></p>',
				'<p style="width: 132px; float: left;">' + obj.address + '<br />(<a href="javascript:void(0);" onclick="return ceneoGmap.zoomIn(this);">przybliż mapę</a>)</p>',
				'<p style="width: 132px; float: right;">' + (obj.phone ? '<img src="common/image/icon/phone.gif" alt="telefon" /> ' + obj.phone + '<br />' : '') + (obj.hours ? '<strong>Godziny otwarcia:</strong><br />' + obj.hours : '') + '</p>',
				'<p style="padding: 7px 0 2px; clear: both; overflow: hidden;">' + (obj.productName ? 'Produkt: ' + obj.productName + '</p><p>Cena: <strong>' + obj.productPrice + '</strong> zł' + (obj.productPriceTotal ? ', z dostawą: od <big>' + obj.productPriceTotal + '</big> zł' : '') + '<br />' : '') + '<br /><a target="_blank" href="' + obj.link + '" class="buy" onmousedown=\'' + obj.onmousedownEventCode + '\'><span>Idź do sklepu &raquo;</span></a></p>',
			'</div>'
		].join('');
    },
    addMarker: function(point) {
        var marker = new GMarker(new GLatLng(point.Y, point.X), { title: point.Title, icon: ceneoGmap.icon });
        GEvent.addListener(marker, 'click', function() {
            ceneoGmap.gmap.openInfoWindowHtml(new GLatLng(point.Y, point.X), ceneoGmap.prepareHtml(point.Html));
        });
        ceneoGmap.gmap.addOverlay(marker);
    },
    addMarkers: function(points) {
        if (points.length > 1) {
            var marker = new GMarker(new GLatLng(points[0].Y, points[0].X), { title: points[0].Title, icon: ceneoGmap.icon });
            var tabs = [];
            for (var i in points) {
                tabs.push(new GInfoWindowTab(points[i].Html.shopDomain, ceneoGmap.prepareHtml(points[i].Html, points.length)));
            };
            GEvent.addListener(marker, 'click', function() {
                ceneoGmap.gmap.openInfoWindowTabsHtml(new GLatLng(points[0].Y, points[0].X), tabs);
            });
            ceneoGmap.gmap.addOverlay(marker);
        }
        else {
            ceneoGmap.addMarker(points[0]);
        }
    },
    zoomIn: function(x) {
        ceneoGmap.gmap.setZoom(15);
        x.blur();
        x.innerHTML = 'oddal mapę';
        x.onclick = function() {
            return ceneoGmap.zoomOut(this);
        };
        return false;
    },
    zoomOut: function(x) {
        ceneoGmap.gmap.setZoom(ceneoGmap.types[ceneoGmap.current].ZoomLevel);
        x.blur();
        x.innerHTML = 'przybliż mapę';
        x.onclick = function() {
            return ceneoGmap.zoomIn(this);
        };
        return false;
    }
};
var ceneoPopups = {
	changes: null,
	compare: null,
	gallery: null
};
var ceneoPreview = {
	el: {},
	images: {},
	last_elem: false,
	init: function()
	{ceneoPreview
		ceneoPreview.el = {
			div: document.getElementById('js-preview'),
			img: document.getElementById('js-preview-image')
		};
		if(ceneoPreview.el.div)
		{
			forEach(document.getElementsByTagName('a'), function()
			{
				if(hasInSpaceSeparated('preview', this.rel))
				{
					this.onmouseover = function()
					{
						var x = ' ' + this.rel + ' ';
						ceneoPreview.last_elem=this;
						ceneoPreview.show((x.match(/\s+image\-\d+\s+/) + ' ').trim());
					};
					this.onmouseout = function()
					{
						ceneoPreview.hide();
					};
				}
			});
		}
	},
	show: function(img)
	{
		ceneoPreview.el.img.src = 'common/image/icon/loading.gif';
		var x = new Image();
		/*x.onload = function()
		{			
						
		};*/
		x.src = ceneoPreview.images[img];
		ceneoPreview.el.img.src = x.src;
		ceneoPreview.el.div.style.display = 'block';
			ceneoPreview.move(ceneoPreview.last_event,ceneoPreview.last_elem);		
	},
	hide: function()
	{
		ceneoPreview.el.div.style.display = 'none';		
	},
	
	move: function(e,elem)
	{
		wsize = ceneoTools.getWindowSize(); 
		wscroll = ceneoTools.getScroll();
		epos=ceneoTools.findPos(elem);		
  		w_w = wsize[0]; w_h=wsize[1]; 
  		w_x=wscroll[0]; w_y=wscroll[1];
  		e_x=epos[0]; e_y=epos[1];
  		
  		
  		e_w=elem.clientWidth; e_h=elem.clientHeight*0.5;
  		
  		el_h = ceneoPreview.el.div.clientHeight;  el_w = ceneoPreview.el.div.clientWidth ;
  		
  		m_left = e_x + e_w; 
  		m_top = e_y + e_h ;
  		
  		
  		
   		if( m_left + el_w >= w_w + w_x ){ m_left = e_x - el_w ; }
   		if( m_top + el_h >=w_h + w_y ) m_top = e_y - el_h ;
  		
  		ceneoPreview.el.div.style.top =  m_top + 'px';
		ceneoPreview.el.div.style.left =  m_left + 'px';
  		
	}
};

$(document).ready(function() {
    $("#product-desc-more-control").click(function() {
        $("#product-desc-more-control").hide();
        $(".product-desc-less-control").show();
        $('#product-desc-uni').animate({ height: ($('#product-desc-uni-inner').height() + 20) + "px" }, 400);
    });

    $(".product-desc-less-control").click(function() {
        $(".product-desc-less-control").hide();
        $("#product-desc-more-control").show();
        var h = $("#product-desc-uni_height").val();
        if (h == null)
            h = "0";
        $('#product-desc-uni').animate({ height: h + "px" }, 400);
        $('html,body').animate({ scrollTop: 0 }, 400);
        //$('html,body').animate({scrollTop: 0}, 400);
    });
});

var ceneoRecommend = {
	box: null,
	current: 0,
	init: function()
	{
		var x = document.getElementById('products-recommended-control');
		if(x)
		{
			forEach(x.getElementsByTagName('a'), function()
			{
				this.onclick = function()
				{
					ceneoRecommend.next();
					this.blur();
					return false;
				};
			});
			ceneoRecommend.box = document.getElementById('products-recommended');
			ceneoRecommend.box.onmouseout = function()
			{
				ceneoRecommend.timer = window.setInterval(ceneoRecommend.next, 2000);
			};
			ceneoRecommend.box.onmouseover = function()
			{
				window.clearInterval(ceneoRecommend.timer);
				ceneoRecommend.timer = null;
			};
			ceneoRecommend.timer = window.setInterval(ceneoRecommend.next, 2000);
		}
	},
	next: function()
	{
		var x = ceneoRecommend.box.getElementsByTagName('li');
		x[ceneoRecommend.current].className = 'hide';
		if(ceneoRecommend.current >= x.length - 1)
		{
			ceneoRecommend.current = 0;
		}
		else
		{
			ceneoRecommend.current++;
		}
		x[ceneoRecommend.current].className = 'show';
	},
	timer: null
};
    

// Define our positioning and style arrays
var at = [
		'bottom center'
	],
	my = [
		'top left'
	],
	styles = [
		'ceneo'
	];

// Create the tooltips only on document load
function attachDeliveryInfoTip(object) {
    $(object)
		.qtip({
		    content: {
		        text: function(api) {
		            var str = "";

        			            var queryElements = new Array();
        			            queryElements = object.rel.split(' ');
        			            $.getJSON("ShopDeliveryInfo/?data=" + queryElements[1] + '&productId=' + queryElements[2],

		            //var id = $(this).attr('id').replace("shopDelivery-", "").replace("shopDeliveryBasket-", "");
		            //$.getJSON("ShopDeliveryInfo/" + id,
		            function(offer) {
		                str = "<dl class=\"deliveryDetails\" >";
        			                if (offer.freeDeliveryFrom != undefined) {
        			                    str += "<dd class=\"freeDelivery\">Darmowa wysyłka od <strong>" + offer.freeDeliveryFrom + " zł</strong></dd>";
        			                }
		                var i = 0;
		                var j = 0;
		                for (i = 0; i < offer.data.length; i++) {

		                    if (offer.data[i].head.length > 0) {
		                        str += "<dt>" + offer.data[i].head + "</dt>";
		                    }

        			                    str += "<dd><ul>";
        			                    for (j = 0; j < offer.data[i].vals.length; j++) {
        			                        str += "<li>" + offer.data[i].keys[j];
        			                        if (offer.data[i].vals[j].label == "0,00 zł" && offer.data[i].head != "Odbiór osobisty") {
        			                            str += " <strong style='color:#F47820; font-size:14px'>";
        			                        }
        			                        else {
        			                            str += " <strong>";
        			                        }
        			                        str += offer.data[i].vals[j].label + "</strong></li>";
        			                    }
        			                    str += "</ul></dd>";
        			                }
        			                str += "</dl>";
        			                api.set('content.text', str);
        			                api.show();
        			            });
        			            api.set('content.text', str);
        			        },

        			        title: {
        			            text: 'Szczegóły dostawy',
        			            button: true
        			        }
        			    },

        			    position: {
        			        my: ['top right'],
        			        at: ['bottom center']  //...and opposite corner
        			    },
        			    show: {
        			        event: 'click',
        			        ready: true, // ... but show the tooltip when ready
        			        solo: true
        			    },
        			    hide: {
        			        effect: true,
        			        //hide if clicked (not on the tooltip itself):
        			        event: "unfocus"
        			    },
        			    style: {
        			        classes: 'ui-tooltip-shadow  ui-tooltip-' + styles[0]
        			    },
        			    events: {
        			        show: function(ev, a) {
        			            $('.ui-tooltip ').hide();
        			        }
        			    }
        			});
}

    function attachTip(object, shopInfoUrl, shopSelledProductsUrl, shopLocalizationUrl) {
        var text = '<ul class="shopDetails">' + (shopInfoUrl ? '<li><a href="' + shopInfoUrl + '">informacje o sklepie</a></li>' : '') + 
                   (shopSelledProductsUrl ? '<li><a href="' + shopSelledProductsUrl + '">sprzedawane produkty</a></li>' : '') +
                   (shopLocalizationUrl ? '<li><a href="' + shopLocalizationUrl + '">mapa punktów odbioru osobistego</a></li>' : '') + '</ul>';
    $(object)
			.qtip({
			    overwrite: false,
			    style: {
			        tip: { corner: 'leftMiddle', size: { x: 6, y: 10} }
			    },
			    content: {
			        text: text,
			        title: {
			            text: 'Szczegóły',
			            button: true
			        }
			    },
			    position: {
			        my: 'top left', 
			        at: 'bottom center' 
			    },
			    show: {
			        event: 'click',
			        ready: true, 
			        solo: true
			    },
			    hide: {
			        effect: true,
			        event: "unfocus"
			    },
			    style: {
			        classes: 'ui-tooltip-shadow ui-tooltip-rounded ui-tooltip-ceneo'
			    }
			});
}

var facebookLoaded = 0;
var googleLoaded = 0;
var twitterLoaded = 0;

var maxAttempts = 3;
if(navigator.appName.indexOf("microsoft") == -1){
    maxAttempts = 4
}

function attachTipForSocial(obj, socialType, url) {
    var text = "";
    var title = "";
    switch (socialType) {
        case 'facebook':
            if (isSocialNotLoadedProperly(socialType))
                facebookLoaded = 0;
            facebookLoad();

            text = '<div class="facebookLike socialTip"><div class="fb-like" data-send="false" data-layout="button_count" data-width="115px" data-show-faces="false" action="Lubię to!" href="' + url + '"></div></div>';
            title = "Facebook";
            break;
        case 'google':
            if (isSocialNotLoadedProperly(socialType))
                googleLoaded = 0;
            googleLoad();

            text = '<div class="gPlusOne socialTip"><g:plusone size="medium" href="' + url + '"></g:plusone><div>';
            title = "Google+";
            break;
        case 'twitter':
            if (isSocialNotLoadedProperly(socialType))
                twitterLoaded = 0;
            twitterLoad();

            text = '<div class="twitterShare socialTip"><a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-url="' + url + '" style="width:80px"></a><div>';
            title = "Twitter";
            break;
    }

    $(obj)
		.qtip({
			overwrite: false,
			style: {
			    tip: { corner: 'leftMiddle', size: { x: 6, y: 10} }
			},
			content: {
			    text: text,
			    title: {
			        text: title,
			        button: 'Close'
			    }
			},
			position: {
			    my: 'bottom center',
			    at: 'top center' 
			},
			show: {
			    event: 'mouseover',
			    ready: true,
			    solo: true
			},
			hide: {
			    effect: true,
			    event: "mouseleave",
			    fixed: true,
			    delay: 1000
			},
			style: {
			    classes: 'ui-tooltip-shadow ui-tooltip-rounded ui-tooltip-ceneo',
			    width: 150
			}
			    
		});
}
function facebookLoad() {
    if (facebookLoaded < maxAttempts) {
        facebookLoaded++;
    } else if(isSocialNotLoadedProperly('facebook')){
        facebookLoaded = 0;
    }
    else {
        return;
    }
    var cache = jQuery.ajaxSettings.cache;
    jQuery.ajaxSettings.cache = true;
    jQuery.getScript('http://connect.facebook.net/pl_PL/all.js', function () {
        FB.init({ appId: 'your_app_id-optional', status: true, cookie: true, xfbml: true });
        facebookLoad();
    });
    jQuery.ajaxSettings.cache = cache;
}


function googleLoad() {
    if (googleLoaded < maxAttempts) {
        googleLoaded++; ;
    } else if(isSocialNotLoadedProperly('google')){
        googleLoaded = 0;
    }
    else{
        return;
    }
    window.___gcfg = {lang: 'pl'};

    var cache = jQuery.ajaxSettings.cache;
    jQuery.ajaxSettings.cache = true;
    jQuery.getScript('https://apis.google.com/js/plusone.js', function () {
        googleLoad();
    });
    jQuery.ajaxSettings.cache = cache;
}
function twitterLoad() {
    if (twitterLoaded < maxAttempts) {
        twitterLoaded++; ;
    } else if(isSocialNotLoadedProperly('twitter')){
        twitterLoaded = 0;
    } else {
        return;
    }

    var cache = jQuery.ajaxSettings.cache;
    jQuery.ajaxSettings.cache = true;
    jQuery.getScript('http://platform.twitter.com/widgets.js', function () {
        twitterLoad();

    });
    jQuery.ajaxSettings.cache = cache;
}

//czasami nie laduje przyciskow
//naprawa podczas kolejnego zaladowania qtipa
function isSocialNotLoadedProperly(socialType) {
    switch (socialType) {
        case 'facebook':
            if (facebookLoaded == maxAttempts && $('.facebookLike') != null && ($('.facebookLike').html() == null || $('.facebookLike').html().indexOf('iframe') == -1)) {
                return true;
            }
            else
                return false;
            break;
        case 'google':
            if (googleLoaded == maxAttempts && $('.gPlusOne') != null && ($('.gPlusOne').html() == null || $('.gPlusOne').html().indexOf('iframe') == -1)) {
                return true;
            }
            else
                return false;
            break;
        case 'twitter':
            if (twitterLoaded == maxAttempts && $('.twitterShare') != null && ($('.twitterShare').html() == null || $('.twitterShare').html().indexOf('iframe') == -1)) {
                return true;
            }
            else
                return false;
            break;
    }
}
var ceneoShowcase = {
    current: $('.show').attr('id') == null ? 1 : $('.show').attr('id').split('showcase-content-')[1],
    el: {},
    interval: null,
    init: function() {
        var x = document.getElementById('showcase');
        if (x) {
            x.onmouseover = function() {
                window.clearInterval(ceneoShowcase.interval);
                ceneoShowcase.interval = null;
            };
            x.onmouseout = function() {
                    ceneoShowcase.interval = window.setInterval(ceneoShowcase.change, $('#showTime-' + ceneoShowcase.current).val());
            };
                ceneoShowcase.interval = window.setInterval(ceneoShowcase.change, $('#showTime-' + ceneoShowcase.current).val());
            ceneoShowcase.el = {
                content: document.getElementById('showcase-content'),
                controls: document.getElementById('showcase-controls')
            };
            forEach(ceneoShowcase.el.controls.getElementsByTagName('a'), function() {
                this.onclick = function() {
                    ceneoShowcase.change(this);
                    return false;
                };
            });
            sc[ceneoShowcase.current - 1]();
        }
    },
    change: function(el) {
        document.getElementById('showcase-control-' + ceneoShowcase.current).className = '';
        document.getElementById('showcase-content-' + ceneoShowcase.current).className = 'hide';
        if (el && el.href) {
            el.blur();
            ceneoShowcase.current = el.href.split('#showcase-content-')[1];
        }
        else {
            ceneoShowcase.current++;
            if (!document.getElementById('showcase-content-' + ceneoShowcase.current) || !document.getElementById('showcase-content-' + ceneoShowcase.current).tagName) {
                ceneoShowcase.current = 1;
            }
                window.clearInterval(ceneoShowcase.interval);          
                ceneoShowcase.interval = window.setInterval(ceneoShowcase.change, $('#showTime-' + ceneoShowcase.current).val());          
        }
        document.getElementById('showcase-control-' + ceneoShowcase.current).className = 'current';
        document.getElementById('showcase-content-' + ceneoShowcase.current).className = 'show';
        sc[ceneoShowcase.current - 1]();
    }
};

var ceneoStars = {
    init: function() {
        var x = document.getElementById('form_body_opinion');
        if (x) {
            forEach(x.getElementsByTagName('select'), function() {
                var html = '<ul class="rating" onmouseover="this.className = \'rating rating-active\';" onmouseout="this.className = \'rating rating-inactive\';">';
                forEach(this.getElementsByTagName('option'), function() {
                    html += '<li class="star-' + this.value + '"><a href="javascript:void(0);" title="' + this.text + '" onclick="return ceneoStars.select(this, ' + this.value + ');">' + this.text + '</a></li>';
                });
                html += '</ul>';
                this.style.display = 'none';
                var selects = this.parentNode.getElementsByTagName('label');
                if (selects.length > 0) {
                    selects[0].style.cursor = 'text';
                } 
                this.parentNode.innerHTML += html;
            });
        }
    },
    select: function(el, val) {
        var x = el.parentNode.parentNode;
        forEach(x.getElementsByTagName('a'), function() {
            this.className = '';
        });
        x.className = 'rating rating-inactive';
        el.className = 'selected';
        forEach(x.parentNode.getElementsByTagName('select')[0].getElementsByTagName('option'), function() {
            this.selected = (this.value == val);
        });
        el.blur();
        return false;
    }
};

/* === FUNCTIONS === */

function ceneoEnv()
{
	if(arguments.callee.done)
	{
		return;
	}
	arguments.callee.done = 1;
	ceneoBoxes.init();
	ceneoFilters.init();
	ceneoFiltersAlt.init();
	ceneoGallery.init(3);
	ceneoGmap.init();
	ceneoPreview.init();
	ceneoRecommend.init();
	//ceneoShipping.init();
	ceneoShowcase.init();
	ceneoStars.init();	

	forEach(document.getElementsByTagName('a'), function() {
	    if (hasInSpaceSeparated('external', this.rel)) {
	        this.target = '_blank';
	    }
	    if (hasInSpaceSeparated('gallery', this.rel)) {
	        //			this.onclick = function()
	        //			{
	        //				if(ceneoPopups.gallery !== null && !ceneoPopups.gallery.closed)
	        //				{
	        //					ceneoPopups.gallery.close();
	        //				}
	        //				this.blur();
	        //				this.href = '.?page=gallery'; // temp
	        //				ceneoPopups.gallery = window.open(this.href + ((this.href.indexOf('?') != -1) ? '&' : '?') + 'type=lite', 'ceneoPopupsGallery', 'width=637,height=450,resizable=0,scrollbars=1');
	        //				ceneoPopups.gallery.focus();
	        //				return false;
	        //			};
	    }
	});


	productsCompare = {
	    cName: "cProdCompare",

	    createCookie: function(value) {
	        document.cookie = productsCompare.cName + "=" + value + "; path=/";
	    },

	    readCookie: function(r) {
	        var nameEQ = productsCompare.cName + "=";
	        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);
	        }
	        if (r) {
	            return null;
	        } else {
	            productsCompare.createCookie("");
	            return productsCompare.readCookie(1);
	        }
	    },

	    eraseCookie: function() {
	        productsCompare.createCookie("");
	        $('input[id^="form-body-compare-chbx"]').attr('checked', false);
	    },

	    popup: function(text, showEraseButton) {
	        var containerStartStr = "<div style=\"widht:200px; height:70px; text-align:center;\">";
	        var containerEndStr = "</div>";
	        var okButtonStr = "<br/><br/><button style=\"width:100px;\" onclick=\"$.fancybox.close(); return false;\">OK</button> ";
	        var eraseButtonStr = "<button style=\"width:100px;\" onclick=\"productsCompare.eraseCookie(); $.fancybox.close(); return false;\">Wyczyść listę</button>";
	        displayFancyboxWithConfirmation(containerStartStr + text + okButtonStr + (showEraseButton ? eraseButtonStr : "") + containerEndStr);
	    },

	    getItems: function() {
	        var temp = productsCompare.readCookie();
	        var itemsStr = temp != null ? temp.split("#") : [];
	        var items = [];
	        var i = 0;
	        var temp;
	        for (i = 0; i < itemsStr.length; i++) {
	            if (itemsStr[i].length > 0) {
	                temp = itemsStr[i].split("_");
	                items.push({ pid: temp[0], cid: temp[1] });
	            }
	        }

	        return items;
	    },

	    isCategoryCorrect: function(cid) {
	        var correct = true;
	        var items = productsCompare.getItems();
	        var i = 0;
	        for (i = 0; i < items.length; i++) {
	            if (items[i].cid != cid)
	                return false;
	        }
	        return correct;
	    },

	    addRemove: function(item) {
	        var data = productsCompare.readCookie();
	        itemStr = item.pid + "_" + item.cid + "#";
	        if (data != null && data.indexOf(itemStr) != -1) {
	            data = data.replace(itemStr, "");
	        } else {
	            if (productsCompare.isCategoryCorrect(item.cid)) {
	                if (data != null) {
	                    data += itemStr;
	                } else {
	                    data = itemStr;
	                }
	            } else {
	                return false;
	            }
	        }
	        productsCompare.createCookie(data);
	        return true;
	    },

	    getDataFromCbx: function(cbx) {
	        return {
	            pid: cbx.value,
	            cid: cbx.id.replace("form-body-compare-chbx-", "").replace("-" + cbx.value, "")
	        };
	    },

	    showComparision: function() {
	        var items = productsCompare.getItems();
	        if (items.length === 0) {
	            productsCompare.popup("Zaznacz produkty do porównania", false);
	            return false;
	        }
	        else if (items.length == 1) {
	            productsCompare.popup("Zaznacz drugi produkt do porównania", false);
	            return false;
	        }
	        else if (items.length > 20) {
	            productsCompare.popup("Możesz porównać do 20 produktów za jednym razem", false);
	            return false;
	        }

	        var handle = "ProductsComparison.aspx?categoryId=" + items[0].cid;
	        var i = 0;
	        for (i = 0; i < items.length; i++) {
	            handle += "&productId=" + items[i].pid;
	        }

	        window.open(handle);
	        return false;
	    },

	    attachCbxActions: function() {
	        $('input[id^="form-body-compare-chbx"]').click(function() {
	            var itemData = productsCompare.getDataFromCbx(this);
	            var result = productsCompare.addRemove(itemData);
	            if (!result) {
	                productsCompare.popup("Porównywane produkty muszą należeć do tej samej kategorii", true);
	                this.checked = false;
	            }
	        });
	    },

	    attachLinksCookieClearAction: function() {
	        $(".tree a," +
	            "#header a," +
	            "#footer a," +
	            ".product > .desc > .params a,"+
	            "#listing-col-1 > .box > .corner a").click(function() {
	                productsCompare.eraseCookie();
	            });
	    },

	    selectItems: function() {
	        var items = productsCompare.getItems();
	        var i = 0;
	        for (i = 0; i < items.length; i++) {
	            $("#form-body-compare-chbx-" + items[i].cid + "-" + items[i].pid).attr('checked', true);
	        }
	    }
	}
	
	productsCompare.attachCbxActions();
	productsCompare.attachLinksCookieClearAction();
	productsCompare.selectItems();
	//end compare
	
	/*
	if((x = document.getElementById('changes-in-price')))
	{
		forEach(x.getElementsByTagName('a'), function()
		{
			this.onclick = function()
			{
				if(ceneoPopups.changes !== null && !ceneoPopups.changes.closed)
				{
					ceneoPopups.changes.close();
				}
				this.blur();
				this.href = '.?page=changes'; // temp
				ceneoPopups.changes = window.open(this.href + ((this.href.indexOf('?') != -1) ? '&' : '?') + 'type=lite', 'ceneoPopupsChanges', 'width=637,height=337,resizable=0,scrollbars=1');
				ceneoPopups.changes.focus();
				return false;
			};
		});
	}
	*/
	if((x = document.getElementById('mylist-clean')))
	{
		forEach(x.getElementsByTagName('a'), function()
		{
			this.onclick = function()
			{
				this.blur();
				return confirm('Czy chcesz usunąć całą zawartość listy produktów?');
			};
		});
	}
	if((x = document.getElementById('kredytonline')))
	{
		forEach(x.getElementsByTagName('form'), function()
		{
			this.target = '_blank';
		});
	}
	if(isIE)
	{
		forEach(document.getElementsByTagName('button'), function()
		{
			this.onmouseover = function()
			{
				this.className = 'hover';
			};
			this.onmouseout = function()
			{
				this.className = '';
			};
		});
	}
}

function adwordsConversionTracking() {
    var image = new Image();
    image.src = 'http://www.googleadservices.com/pagead/conversion/975832628/?label=7_8mCJTosQIQtIyo0QM&guid=ON&script=0';
}

function pageTracker_onmousedown(orderId, shopname, ProductID, ProductName, MainCategory, City, offerPosition, price, prefix) 
{
    if (prefix == null)
        prefix = '';
        
    try {
        _gaq.push([prefix + '_addTrans',
                    City + orderId,
                    shopname,
                    "1",
                    "",
                    "",
                    City,
                    "",
                    ""
                ]);
        _gaq.push([prefix + '_addItem',
                    City + orderId,
                    ProductID,
                    ProductName,
                    MainCategory,
                    "1",
                    "1"
                ]);
        _gaq.push([prefix + '_trackTrans']);
        
        if(prefix == 'c.')
            pageTracker_onmousedown(orderId, shopname, ProductID, ProductName, MainCategory, City, offerPosition, price, '');
        else { //wpinam sie tutaj zeby miec pewnosc pojedynczego wywolania
            reddot = new Image();
            var reddoturl = '/common/dot/cdot.gif?t=c';
            if (typeof _analyticsPagePath != "undefined") {
                reddoturl += '&path=' + encodeURIComponent(_analyticsPagePath);
            }
            reddoturl += '&ref=' + encodeURIComponent(document.referrer)
                    + '&op=' + encodeURIComponent(offerPosition)
                    + '&coid=' + encodeURIComponent(orderId)
                    + '&csn=' + encodeURIComponent(shopname)
                    + '&cpid=' + encodeURIComponent(ProductID)
                    + '&cpn=' + encodeURIComponent(ProductName)
                    + '&cmc=' + encodeURIComponent(MainCategory)
                    + '&cc=' + encodeURIComponent(City)
                    + '&opr=' + encodeURIComponent(price)

            //+'&cp='+encodeURIComponent(prefix)
                    ;
            reddot.src = reddoturl;
        }

        adwordsConversionTracking();
    }
    catch (err) {
        window_onerror('pagetrackerError-' + err, location.href, null);
    }
}

function clickWrapper(link, action, url) {
    try {
        link.href = action + url;
        link.target = '_blank';
    }
    catch (message) {
        window_onerror('clickWrapperError-' + message, location.href, null)
    }
}

var allegroTools = {
    timers: [null],
    productGalleryTimer: 0,

    loadAllegroContent: function(containerId, contentUrl) {
        if (contentUrl != "") {
            $.get(contentUrl, function(data, textStatus) {
                $("#" + containerId).html(data);
            }, "html");
        }
    },

    startLoadingTimer: function(timer, containerId, timeoutTarget, timeoutValue) {
        allegroTools.timers[timer] = setTimeout("allegroTools.loadAllegroContent(\"" + containerId + "\",\"" + timeoutTarget + "\");", timeoutValue);
    },

    clearLoadingTimer: function(timer) {
        if (allegroTools.timers[timer]) {
            clearTimeout(allegroTools.timers[timer]);
        }
    }
}

function add2basket(object, offerId, price, basketUrl) {
    $.getJSON("Add2Basket", { offerId: offerId, price: price, secs: new Date().getTime() }, function(json) {
        var messageFormBasket = '<br/><p>Oferta została dodana do koszyka.</p><p><a href="' + basketUrl.toString() + '">przejdź do koszyka »</a></p><br/>';
        if (!json.confirmed) {
            messageFormBasket = '<br/><p>Osiągnąłeś limit ofert w koszyku. Oferta nie została dodana.</p><p><a href="' + basketUrl.toString() + '">przejdź do koszyka »</a></p><br/>';
        }
        $(object).qtip({
            overwrite: true,
            show: {
                event: 'click',
                ready: true,
                solo: true
            },
            hide: { event: "unfocus" },
            onHide: function() {
                $(object).qtip('destroy');
            },
            content: {
                text: messageFormBasket,
                title: {
                    text: 'Do koszyka',
                    button: true
                }
            },
            position: {
                my: 'top right',
                at: 'bottom center'
            },
            style: {
                classes: 'ui-tooltip-shadow  ui-tooltip-ceneo'
            }
        });
        readBasketData();
    });
}

function add2basketWithFancyBox(object, offerId, price, basketUrl) {
    $(document).ready(function() {
        $.getJSON("Add2Basket", { offerId: offerId, price: price, secs: new Date().getTime() }, function(json) {
            var isBasketFull = false;
            if (!json.confirmed) {
                isBasketFull = true;
            }

            $.post('AddToBasketConfirmation/' + offerId + ',' + isBasketFull, function(data) {
                $.fancybox(
                    data,
		            {
		                'autoDimensions': false,
		                'height': 'auto',
		                'autoDimensions': true,
		                'transitionIn': 'none',
		                'transitionOut': 'none',
		                'showCloseButton': true,
		                'enableEscapeButton': true
		            }
	            );

                readBasketData();
            });
        });
    });
}
function showFancyBoxForUrl(object, url, width, height) {
    $(document).ready(function() {
        $.fancybox(
        '<iframe src="' + url + '" width="' + width + '" height="' + height + '"></iframe>',
        {
            'autoDimensions': true,
            'width': 'auto',
            'height': 'auto',
            'transitionIn': 'none',
            'transitionOut': 'none',
            'showCloseButton': true,
            'enableEscapeButton': true
        });
    });
}
function isEmailAdresValid(emailAdress) {
    var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
   
    return emailAdress.match(emailPattern) != null;
}

var notValidClassname = "textNotvalidBorder";

function blurEmailFieldValidation(obj, allowEmpty, allowWaterMark) {
    if(typeof allowWaterMark != "undefined" && allowWaterMark == true && $(obj).hasClass('blur'))
        return;
    if (typeof allowEmpty != "undefined" && allowEmpty == true && obj.value == '') {
        return;
    }
    if(!isEmailAdresValid(obj.value)){
        $(obj).addClass(notValidClassname);
    }
}
function blurEmptyValidation(obj) {
    if(obj.type == 'checkbox' && obj.checked != true){
        $(obj).parent().addClass(notValidClassname);
        return;
    }
    if (obj.value == '') {
        $(obj).addClass(notValidClassname);
        return false;
    }
    return true;
}
function focusHideValidation(obj) {
    var jObj = $(obj);
    if(jObj.hasClass(notValidClassname))
        jObj.removeClass(notValidClassname)
    if(obj.type == 'checkbox')
        jObj.parent().removeClass(notValidClassname);
}
function isFormValidate(obj){
    var reqInputs = $(obj.form).find('input.requiredField, textarea.requiredField');
    $.each(reqInputs, function(key, input){
        blurEmptyValidation(input);
    });
    return fieldsValid($(obj.form));
}
function isContainerValidate(obj){
    var reqInputs = obj.find('input.requiredField, textarea.requiredField');
    $.each(reqInputs, function(key, input){
        blurEmptyValidation(input);
    });
    var emailField = obj.find('input#email');
    if(!isEmailAdresValid(emailField.val())){
        emailField.addClass(notValidClassname);
    }
    return fieldsValid($(obj));
}
function fieldsValid(obj){
    return obj.find('input.' + notValidClassname).length == 0 && obj.find('span.' + notValidClassname).length == 0;
}
