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');
			}
		}
	}
}();

