var survey = {
    show : function(id, from, el) {
        if (typeof from != 'string' || from.length <= 0)
            from = '';
        el = typeof el == 'undefined' ? survey.count++ : el;
        if (!document.getElementById('survey'+el))
            document.write('<div id="survey'+el+'"></div>');
		var cbp = el;
        $.get('/survey/survey.php', {id: id, from: from, el: el}, function(data) {
            $('#survey'+cbp).html(data);
        });
        return false;
    },
    vote : function(form) {
        var answer = '';
        for (var i = 0; i < form.answer.length; ++i)
            if (form.answer[i].checked) {
                answer = form.answer[i].value;
                break;
            }
        var params = {
            id: form.id.value,
            answer: answer,
            captcha: form.captcha.value,
            ajax: 1,
            from: form.from.value,
            el: form.el.value
        };
        var data = [];
        for (i in params)
            data.push(i + '=' + encodeURIComponent(params[i]));
        data = data.join('&');
		var cbp = form.el.value;
		$.post(form.action, data, function(data) {
                $('#survey'+cbp).html(data);
        });
        return false;
    },
    results : function(id, from, el) {
		var cbp = el;
        $.get('/survey/survey.php', {id: id, results: 1, from: from, el: el}, function(data) {
            $('#survey'+cbp).html(data);
        });
        return false;
    },
    count : 0
};

function AptusNewsletter(from, ids) {
	if(!AptusNewsletter.Instances) {
		AptusNewsletter.Instances = [];
	}
	this.id = AptusNewsletter.Instances.length;
	AptusNewsletter.Instances[this.id] = this;
	this.formname = 'ajax_newsletter_form_' + this.id; // Nazwa formularza
	this.from = from; // Gdzie ma zostać wyświetlony newsletter (dla innych wyglądów formularza)
    this.ids = (typeof ids != 'object' ? [] : ids);
	this.form = function(id) {
		var params = {};
		params.formname = this.formname;
		params.from = this.from;
		params.url_from = location.href;
		params.id = this.id;
        if (this.ids.length > 0)
            params.ids = this.ids.join(',');
		$.get("/news/subscribe.php", params, function(data) {
			$("#AptusNewsletterHandler"+id).html(data);
		});
	}
	this.submit = function(id) {
		var params = {};
		var f = document.forms[AptusNewsletter.Instances[id].formname];
        var i;
		var asArray = false;
		if (f.elements.length > 0) {
			for (i = 0; i < f.elements.length; i++) {
				if (f.elements[i].name.indexOf('[]') != -1) {
					if ( ! params[f.elements[i].name])
						params[f.elements[i].name] = [];
					asArray = true;
				} else
					asArray = false;
				if (f.elements[i].type != 'checkbox' || f.elements[i].checked) {
					if (asArray)
						params[f.elements[i].name].push(f.elements[i].value);
					else
						params[f.elements[i].name] = f.elements[i].value;
				}
			}
		}
		params.id = id;
        var data = [];
        for (i in params) {
            if (typeof params[i] == 'object') {
                for (var j in params[i])
                    data.push(i + '=' + encodeURIComponent(params[i][j]));
            } else {
                data.push(i + '=' + encodeURIComponent(params[i]));
            }
        }
        data = data.join('&');
		$.post("/news/subscribe.php", data, function(data) {
			$("#AptusNewsletterHandler"+id).html(data);
		});
	}
	document.write("<div id=\"AptusNewsletterHandler"+this.id+"\"></div>");
	this.form(this.id);
}

function close_message(obj) {
	$(obj).parent().fadeOut(500);
}

function close_element(obj) {
	$(obj).fadeOut(500);
}

function toggle_fields(id, cb) {
    var additional = document.getElementById(id);
    if(!additional)
        return;
    additional.style.display = cb.checked ? 'block' : 'none';
}

function active_tab(tabs_index, active_tab_index) {
	var index = 1;
	$(".tabs").each(function() {
		if(index==tabs_index) {
			var tab_index = 1;
			$(this).find("a.tab").each(function() {
				if(tab_index==active_tab_index)
					$(this).addClass("active");
				else
					$(this).removeClass("active");
				tab_index++;
			});
			tab_index = 1;
			$(this).find("div.tab").each(function() {
				$(this).css("display", tab_index==active_tab_index ? "block" : "none" );
				tab_index++;
			});
		}
		index++;
	});
}

function prepare_tabs() {
	if ($.browser.msie && parseInt($.browser.version) == 7)
		setTimeout(prepare_tabs_do, 0);
	else
		prepare_tabs_do();
}

function prepare_tabs_do() {
	var index = 1;
	$(".tabs").each(function() {
		var tab_index = 1;
		$(this).find("a.tab").each(function() {
			$(this).attr({index: index, tab_index: tab_index});
			$(this).click(function () {active_tab($(this).attr('index'), $(this).attr('tab_index'));});
			if(tab_index==1)
				$(this).addClass("active");
			tab_index++;
		});
		tab_index = 1;
		$(this).find("div.tab").each(function() {
			$(this).css("display", tab_index==1 ? "block" : "none" );
			tab_index++;
		});
		index++;
	});
}

function limited_text() {
	var lt = $(".limited-text");
	var pr = lt.parents('.pbm');

	for (var i = (pr.length - 1); i >= 0 ; i--) {
		var tmp = pr.eq(i);
		tmp.css('z-index', 10 * (i+1));
	}
	lt.each(function() {
		var t = $(this);
		if(t.height() < t.find(".description").height()) {
			t.append('<div class="read-more"><a class="show-more"></a></div>');
			t.mouseenter(function(){
				t.find(".show-more").animate({opacity:1, top: 0}, {queue: false});
			});
			t.mouseleave(function(){
				t.find(".show-more").animate({opacity:0, top: -5}, {queue: false});
			});
			t.find(".read-more").find(".show-more").click(function() {
				var desc = t.find(".description");
				desc.stop(true, true);
				var dw = desc.width()+4;
				desc.attr('sh', t.height());
				desc.css('height', 'auto');
				var dh = desc.height();
				desc.addClass('focused');
				desc.css({height: t.height(), width: dw + 'px'});
				t.css('overflow', 'visible');

				desc.animate({height: dh, filter: ''});
				t.mouseleave(function () {
					desc.animate({height: desc.attr('sh') + 'px', filter: ''}, function () {
						desc.removeClass('focused');
						t.css('overflow', 'hidden');
						desc.css({width: 'auto', height: 'auto'});
					});
				});
			});
		}
	});
}

function article_slide(obj, current_index, next_index) {
	var slider = $(obj).parent().parent();
	slider.find(".slider_article_"+current_index).css("left",0);
	slider.find(".slider_article_"+next_index).css("left",( next_index>current_index ? $(obj).parent().width() : -$(obj).parent().width() ));
	slider.find(".slider_article_"+current_index).animate({left:( next_index>current_index ? -$(obj).parent().width() : $(obj).parent().width() ), opacity:0},1000);
	slider.find(".slider_article_"+next_index).animate({left:0,opacity:1},1000);
}

var fNewsletter = function () {
	return {
		form_name: 'newsletter_form',
		send: function (act) {
			var f = document.forms[fNewsletter.form_name];
			if ( ! f) return;
			f.newsletter_action.value = act;
			f.submit();
		}
	}
}();

function bookmark_add() {
	url = document.location;
	title = document.title;
	if(window.sidebar)
		window.sidebar.addPanel(title, url, "");
	else if(window.external)
		window.external.AddFavorite(url, title)
}

(function ($) {
if (!$) return;
$.fn.extend({
	fixPNG: function(sizingMethod, forceBG) {
		if (!($.browser.msie)) return this;
		var emptyimg = static_root + "/demo/x.gif";
		sizingMethod = sizingMethod || "scale";
		this.each(function() {
			var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
					imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
					src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
			this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
			if (isImg) this.src = emptyimg;
			else this.style.backgroundImage = "url(" + emptyimg + ")";
		});
		return this;

	}
});
})(jQuery);

function Autocomplete(id, custom) {
	/* konfiguracja domyślna */
	var c = {
		url: shop_root + 'ajax.php?search_autocomplete=1',
		delay: 500,
		minLen: 1,
		showLoader: true,
		textAppend: true, // dołącza nowy tekst zamiast zastępowania całej wartości inputa
		afterKeyPress: false
	}
	/* konfiguracja koniec */

	var isIE = $.browser.msie;
	var input;
	var t = this;
	var list = false;
	var currentIndex = -1;
	var sItems;
	var listOpen = false;
	var cancelHide = false;
	var getListTimeout;
	var loader = false;

	this.config = function (config) {
		for (var setting in config)
			if (typeof c[setting] != 'undefined')
				c[setting] = config[setting];
	}

	this.setup = function () {
		input = $('#' + id);
		input.attr('autocomplete', 'off');
		input.keydown(t.pressed);
		$(document.body).click(this.autoHide);
	}

	this.pressed = function (event) {
		var key = event.keyCode;
		if (key == 38 || key == 40) { // strzałki góra i dół
			if (listOpen) {
				if (sItems.length) {
					t.changePos(key == 38 ? -1 : 1);
				}
			} else if (list) {
				t.loader(1);
				t.getList();
			}
		//} else if (listOpen && key == 13) { // enter
			//t.selectItem(currentIndex);
			//return false;
		} else if ((key >= 48 && key <= 90) || (key >= 96 && key <= 111) || key >= 186 || key == 8 || key == 46) { // alfanumeryczne i specjalne
			t.cancelRequest();
			getListTimeout = setTimeout(t.getList, c.delay);
			t.loader(1);
		}
		if (typeof c.afterKeyPress == 'function')
			c.afterKeyPress(t);
	}

	this.cancelRequest = function () {
		clearTimeout(getListTimeout);
	}

	this.loader = function (show) {
		if ( ! c.showLoader) return;
		if ( ! loader) {
			loader = $('<div class="autocompleteLoader"></div>');
			$('body').append(loader);
		}
		var pos = input.offset();
		var style = show ? {left: (pos.left + parseInt(input.css('padding-left')) + input.width() - loader.width()), top: pos.top + parseInt(input.css('padding-top')), display: 'block'} : {display: 'none'};
		loader.css(style);
	}

	this.changePos = function (go) {
		var goTo;
		var maxIndex = sItems.length - 1;
		currentIndex = parseInt(currentIndex)
		if (currentIndex <= 0 && go == -1)
			goTo = maxIndex;
		else if (currentIndex == maxIndex && go == 1 )
			goTo = 0;
		else
			goTo = currentIndex + go;
		t.focusItem(goTo);
	}

	this.getList = function () {
		var val = input.val();
		if (val.length >= c.minLen) {
			$.get(c.url, {term: val}, t.buildList);
		} else {
			t.loader(0);
		}
	}

	this.buildList = function (data) {
		var tmp = $('.selectItem', data);
		if (tmp.length) {
			if ( ! list) {
				list = $('<div class="autocompleteList"></div>');
				$('body').append(list);
				list.click(function () {
					cancelHide = true;
				});
			}
			list.html(data);
			currentIndex = -1;
			var pos = input.offset();
			list.css({left: pos.left, top: (pos.top + input.outerHeight()), 'min-width': input.outerWidth(), display: 'block'});
			sItems = $('.selectItem', list).mouseenter(t.focus)
				.mouseleave(t.unfocus)
				.click(t.select);
			for (var i = 0; i < sItems.length; i++) {
				sItems.eq(i).attr('index', i);
			}
			listOpen = true;
		} else
			t.closeList();
		t.loader(0);
	}

	this.focus = function () {
		t.focusItem($(this).attr('index'));
	}

	this.focusItem = function (index) {
		if (currentIndex != -1)
			t.unfocusItem(currentIndex);
		sItems.eq(index).addClass('active');
		currentIndex = index;
	}

	this.unfocus = function () {
		t.unfocusItem($(this).attr('index'));
	}

	this.unfocusItem = function (index) {
		sItems.eq(index).removeClass('active');
	}

	// wykonuje akcje po wybraniu elementu
	this.select = function (event) {
		t.selectItem($(this).attr('index'), event);
	}

	this.selectItem = function (index, event) {
		var el = sItems.eq(index);
		if (el.attr('href')) {

		} else if (el.attr('onclick')) {
			if ( ! event)
				el.trigger('click');
		} else {
			t.setInputValue(el.text());
		}
		t.closeList();
	}

	this.setInputValue = function (text) {
		if (c.textAppend) {
			var value = input.val();
			var space = value.lastIndexOf(' ');
			if (space != -1)
				text = value.substr(0, space + 1) + text;
		}
		input.val(text);
	}

	this.autoHide = function () {
		if ( ! cancelHide)
			t.closeList();
		cancelHide = false;
	}

	this.closeList = function () {
		if ( ! list) return;
		list.css('display', 'none');
		listOpen = false;
	}

	if (custom)
		this.config(custom);
	this.setup();
}

function AdvancedSearch(formName) {

	var t = this;
	var f = document.forms[formName];
	var fe = f.elements;
	var dictId = false;
	var ac;

	this.setupDictionary = function () {
		$(fe['dictionary']).change(t.autocompleteDictionary);
		$(fe['word']).attr('id', 'adv_search_word');
		ac = new Autocomplete('adv_search_word', {afterKeyPress: t.autocompleteAfterKeyPress});
		t.setDict($(fe['dictionary']));
	}

	this.setDict = function (ob) {
		dictId = parseInt(ob.val());
		ac.config({url: shop_root + 'ajax.php?search_autocomplete=1&advanced=1&dictionary_id=' + dictId});
	}

	this.autocompleteDictionary = function () {
		var s = $(this);
		t.setDict(s);
		ac.getList();
	}

	this.autocompleteAfterKeyPress = function (autocomplete) {
		if ( ! dictId) {
			autocomplete.cancelRequest();
			autocomplete.loader(0);
		}
	}
}

function add2repository(obj, url) {
	$(obj).addClass("loading");
	$.getJSON(url, function(data) {
		$(obj).replaceWith('<span class="box repository '+data.class_name+'">'+data.message+'</span>');
	});
}

var DictFilters = function () {
	return {
		open: function (dict_id) {
			$.colorbox({href: shop_root + 'ajax.php', data: {filter_dict_list: 1, dict_id: dict_id}, opacity: 0.8});
		},
		tab: function (id) {
			var d = $('#filter_tabs div.tab');
			for (var i = 0; i < d.length; i++) {
				d.eq(i).css('display', d.eq(i).attr('id') == id ? 'block' : 'none');
			}
		}
	}
}();

function dhtml_tree(obj) {
	var children = obj.parentNode.children;
	if(children.length) {
		for(var i=0; i<children.length; i++) {
			if(children[i].tagName=="UL") {
				if(children[i].style.display=="none") {
					var t = children[i].parentNode.parentNode;
					if(t) {
						var ul	= t.getElementsByTagName("UL");
						if(ul.length)
							for(var ii=0; ii<ul.length; ii++)
								ul[ii].style.display = "none";
						var a = t.getElementsByTagName("A");
						if(a.length)
							for(var ii=0; ii<a.length; ii++)
								$(a[ii]).removeClass("open");
					}
					children[i].style.display = "block";
					var a = children[i-1];
					if(a)
						$(a).addClass("open");
				}
				else {
					children[i].style.display = "none";
					var ul	= children[i].getElementsByTagName("UL");
					if(ul.length)
						for(var ii=0; ii<ul.length; ii++)
							ul[ii].style.display = "none";
					var a = children[i].parentNode.getElementsByTagName("A");
					if(a.length)
						for(var ii=0; ii<a.length; ii++)
							$(a[ii]).removeClass("open");
				}
			}
		}
	}
}

function hasClass(obj, className) {
	if (typeof obj == 'undefined' || obj==null || !RegExp) {return false;}
	var r = new RegExp("(^|\\s)" + className + "(\\s|$)");
	if (typeof(obj)=="string") {
		return r.test(obj);
	}
	else if (typeof(obj)=="object" && obj.className) {
		return r.test(obj.className);
	}
	return false;
}

function windowOnBlur() {
	$('body').attr('status', 'unactive');
};
function windowOnFocus(){
	$('body').attr('status', 'active');
};
$(function() {
	if (/*@cc_on!@*/false) {
		document.onfocusin = windowOnFocus;
		document.onfocusout = windowOnBlur;
	}
	else {
		window.onfocus = windowOnFocus;
		window.onblur = windowOnBlur;
	}
});

/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.5
 *
 * Requires: 1.2.2+
 */
(function(a){function d(b){var c=b||window.event,d=[].slice.call(arguments,1),e=0,f=!0,g=0,h=0;return b=a.event.fix(c),b.type="mousewheel",b.wheelDelta&&(e=b.wheelDelta/120),b.detail&&(e=-b.detail/3),h=e,c.axis!==undefined&&c.axis===c.HORIZONTAL_AXIS&&(h=0,g=-1*e),c.wheelDeltaY!==undefined&&(h=c.wheelDeltaY/120),c.wheelDeltaX!==undefined&&(g=-1*c.wheelDeltaX/120),d.unshift(b,e,g,h),(a.event.dispatch||a.event.handle).apply(this,d)}var b=["DOMMouseScroll","mousewheel"];if(a.event.fixHooks)for(var c=b.length;c;)a.event.fixHooks[b[--c]]=a.event.mouseHooks;a.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=b.length;a;)this.addEventListener(b[--a],d,!1);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=b.length;a;)this.removeEventListener(b[--a],d,!1);else this.onmousewheel=null}},a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery)

function pSlider(id) {
	var t = this;
	var main; // główny div
	var cont; // div z overflow
	var slider; // przesuwany element
	var arr; // strzałki
	var slide_width; // szerokość slajdu
	var slides_count; // ilość slajdów
	var slide_number = 0; // aktywny slajd

	this.setup = function () {
		main = $('#' + id);
		cont = $('.container', main);
		slider = $('.slider', cont);
		slide_width = cont.innerWidth();
		arr = {
			left: {ob: $('.arr_left', main), visible: true},
			right: {ob: $('.arr_right', main), visible: true}
		};
		arr.left.ob.click(this.previous);
		arr.right.ob.click(this.next);
		var slides = $('.slide', slider);
		slides_count = slides.length;
		slider.css('width', slides_count * slide_width + 'px')
		for (var i = 0; i < slides_count; i++)
			slides.eq(i).css('width', slide_width + 'px');

		var i_slideIndex = 0;
		var _this = this;
		main.find('.navigation').find('a').each(function() {
			$(this).attr('slide_index', i_slideIndex);
			$(this).click(_this.slide);
			i_slideIndex++;
		});

		main.mousewheel(this.scroll);
		this.go2slide(0);
	}

	this.hideArrow = function (a) {
		if (arr[a].visible) {
			arr[a].ob.fadeOut(600);
			arr[a].visible = false;
		}
	}

	this.showArrow = function (a) {
		if ( ! arr[a].visible) {
			arr[a].ob.fadeIn(1000);
			arr[a].visible = true;
		}
	}

	this.setArrows = function (number) {
		if (number == 0) {
			this.hideArrow('left');
		} else
			this.showArrow('left');
		if (number == slides_count - 1) {
			this.hideArrow('right');
		} else
			this.showArrow('right');
	}

	this.go2slide = function (number) {
		if (number >= slides_count || number < 0) return;
		this.setArrows(number);
		var slider_position = - (number * slide_width) + 'px';
		slider.stop();
		slider.animate({
			marginLeft: slider_position
		}, 300);
		slide_number = number;
		main.find('.navigation').find('a').each(function() {
			if ($(this).attr('slide_index') == number)
				$(this).addClass('active');
			else
				$(this).removeClass('active');
		});
	}

	this.previous = function () {
		t.go2slide(slide_number - 1);
	}

	this.next = function () {
		t.go2slide(slide_number + 1);
	}

	this.slide = function () {
		$(this).parent().find('a').removeClass('active');
		$(this).addClass('active');
		t.go2slide($(this).attr('slide_index'));
		return false;
	}

	this.scroll = function (event, delta) {
		t.go2slide(parseInt(slide_number + parseInt(delta < 0 ? 1 : -1)));
		return false;
	}

	this.setup()
}

function toggle_sms(type)
{
	if(type==1) {
		if(document.form.send_sms) {
			if(document.form.send_sms.checked) {
				document.getElementById('divSummaryNoSMS').style.display='none';
				document.getElementById('divSummaryWithSMS').style.display='block';
				
				document.getElementById('divSummaryPriceSMS').style.display='block';
				document.getElementById('divSummaryNoPriceSMS').style.display='none';
			}
			else {
				document.getElementById('divSummaryWithSMS').style.display='none';
				document.getElementById('divSummaryNoSMS').style.display='block';
				
				document.getElementById('divSummaryPriceSMS').style.display='none';
				document.getElementById('divSummaryNoPriceSMS').style.display='block';
			}
		}
	}
	else if(type==2) {
		if(document.form.send_sms) {
			if(document.form.send_sms.checked) {
				document.getElementById('divSMSInfo').style.display='block';
			}
			else {
				document.getElementById('divSMSInfo').style.display='none';
			}
		}
	}
}

function addToCart(id, params) {
	params = params || {};
	params['action'] = 'add';
	params['id'] = id;
	params['ajax'] = 1;
	var result = false;
	$.ajax({
		url: shop_root+'product.php',
		data: params,
		async: false,
		type: 'POST',
		dataType: 'json',
		success: function(data) {
			if (data === 'ERROR')
				return;
			result = data;
		}
	});
	if (result === false)
		return false;

	$('#cart-box-sum').text(result['cart']['sum']);
	$('#cart-box-count').text(result['cart']['count']);
	$.colorbox({html: result['msg'], opacity: 0.1, width: 420, height: 200, close: 'Zamknij', fixed: false, scrolling: false});
	return true;
}

